context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Drawing; using System.Web.UI; using System.Web.UI.WebControls; using Vevo.WebUI.Ajax; using Vevo.WebUI.International; public partial class Components_PagingControl : BaseLanguageUserControl { private const int DefaultMaximumLinks = 10; private int _currentPageLoading; private int _numberOfPagesLoading; private void DeterminePageRange( out int low, out int high ) { low = CurrentPage - MaximumLinks / 2; if (low < 1) low = 1; // Assuming high value according to low value high = low + MaximumLinks - 1; if (high > NumberOfPages) high = NumberOfPages; // Need to re-adjust low value if the current page is around the upper bound value if (high - low + 1 < MaximumLinks) { low = high - MaximumLinks + 1; if (low < 1) low = 1; } } private void AddLabel( string text ) { Label space = new Label(); space.Text = text; space.CssClass = "PagingCurrent"; uxPlaceHolder.Controls.Add( space ); } private void AddText( string text ) { Literal space = new Literal(); space.Text = text; uxPlaceHolder.Controls.Add( space ); } private void AddSpace() { AddText( "&nbsp;" ); } private void AddDots() { AddText( ".." ); } private void AddOnePageLink( int pageNumber ) { LinkButton link = new LinkButton(); link.ID = "uxPage" + pageNumber + "LinkButton"; link.Text = pageNumber.ToString(); link.CommandArgument = pageNumber.ToString(); link.Command += new CommandEventHandler( Page_Command ); link.CssClass = "PagingNumber"; uxPlaceHolder.Controls.Add( link ); } private ScriptManager GetScriptManager() { return AjaxUtilities.GetScriptManager( this ); } private void AddLinkPrevious() { LinkButton previous = new LinkButton(); previous.ID = "uxPreviousLinkButton"; previous.Text = "[$Prev]"; previous.CssClass = "PagingPrev"; if (CurrentPage > 1) { previous.Enabled = true; previous.Command += new CommandEventHandler( Previous_Command ); } else { previous.Enabled = false; } uxPlaceHolder.Controls.Add( previous ); GetScriptManager().RegisterAsyncPostBackControl( previous ); } private void AddLinkNext() { LinkButton next = new LinkButton(); next.ID = "uxNextLinkButton"; next.Text = "[$Next]"; next.CssClass = "PagingNext"; if (CurrentPage < NumberOfPages) { next.Enabled = true; next.Command += new CommandEventHandler( Next_Command ); } else { next.Enabled = false; } uxPlaceHolder.Controls.Add( next ); GetScriptManager().RegisterAsyncPostBackControl( next ); } private void AddFirstLinkIfNecessary( int low ) { if (low > 1) { AddSpace(); AddOnePageLink( 1 ); if (low > 2) { AddSpace(); AddDots(); } } } private void AddLastLinkIfNecessary( int high ) { if (high < NumberOfPages) { if (high < NumberOfPages - 1) { AddDots(); AddSpace(); } AddOnePageLink( NumberOfPages ); AddSpace(); } } private void AddLinkPageNumber( int low, int high ) { AddSpace(); for (int pageNumber = low; pageNumber <= high; pageNumber++) { if (pageNumber == CurrentPage) AddLabel( pageNumber.ToString() ); else AddOnePageLink( pageNumber ); AddSpace(); } } private void Previous_Command( object sender, CommandEventArgs e ) { if (CurrentPage > 1) CurrentPage -= 1; //GetScriptManager().AddHistoryPoint( "page", CurrentPage.ToString() ); OnBubbleEvent( e ); } private void Next_Command( object sender, CommandEventArgs e ) { if (CurrentPage < NumberOfPages) CurrentPage += 1; //GetScriptManager().AddHistoryPoint( "page", CurrentPage.ToString() ); OnBubbleEvent( e ); } private void Page_Command( object sender, CommandEventArgs e ) { CurrentPage = Int32.Parse( e.CommandArgument.ToString() ); //GetScriptManager().AddHistoryPoint( "page", CurrentPage.ToString() ); OnBubbleEvent( e ); } private void GeneratePagingLinks() { int low, high; DeterminePageRange( out low, out high ); AddLinkPrevious(); AddFirstLinkIfNecessary( low ); AddLinkPageNumber( low, high ); AddLastLinkIfNecessary( high ); AddLinkNext(); } protected void ScriptManager_Navigate( object sender, HistoryEventArgs e ) { //if (!string.IsNullOrEmpty( e.State["page"] )) //{ // string args = e.State["page"]; // CurrentPage = int.Parse( args ); //} //else //{ // CurrentPage = 1; //} } // Need to generate controls here. In case of the postback, the Command or Click event // requires these controls to properly invoke the correct event. protected void Page_Load( object sender, EventArgs e ) { //GetScriptManager().Navigate += new EventHandler<HistoryEventArgs>( ScriptManager_Navigate ); GeneratePagingLinks(); _currentPageLoading = CurrentPage; _numberOfPagesLoading = NumberOfPages; AjaxUtilities.ScrollToTop( this ); } // Update control status in PreRender event. Wait parent page to set // number of pages first protected void Page_PreRender( object sender, EventArgs e ) { if (CurrentPage != _currentPageLoading || NumberOfPages != _numberOfPagesLoading) { uxPlaceHolder.Controls.Clear(); GeneratePagingLinks(); } } public int CurrentPage { get { if (ViewState["CurrentPage"] == null) { return 1; } else { int page = (int) ViewState["CurrentPage"]; if (page > NumberOfPages) { return NumberOfPages; } else { return page; } } } set { ViewState["CurrentPage"] = value; } } public int NumberOfPages { get { if (ViewState["NumberOfPages"] == null || (int) ViewState["NumberOfPages"] < 1) return 1; else return (int) ViewState["NumberOfPages"]; } set { ViewState["NumberOfPages"] = value; } } public int MaximumLinks { get { if (ViewState["MaximumLinks"] == null) return DefaultMaximumLinks; else if ((int) ViewState["MaximumLinks"] < 1) return 1; else return (int) ViewState["MaximumLinks"]; } set { ViewState["MaximumLinks"] = value; } } }
//----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation // // File: TextLine.cs // // Contents: Text line API // // Spec: http://team/sites/Avalon/Specs/Text%20Formatting%20API.doc // // Created: 2-25-2003 Worachai Chaoweeraprasit (wchao) // //------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; using MS.Internal.TextFormatting; using MS.Internal.PresentationCore; namespace System.Windows.Media.TextFormatting { /// <summary> /// Once a line is complete, FormatLine returns a TextLine object to the client. /// The text layout client may then use the TextLines measurement and drawing methods. /// </summary> public abstract class TextLine : ITextMetrics, IDisposable { /// <summary> /// Clean up text line internal resource /// </summary> public abstract void Dispose(); /// <summary> /// Client to draw the line /// </summary> /// <param name="drawingContext">drawing context</param> /// <param name="origin">drawing origin</param> /// <param name="inversion">indicate the inversion of the drawing surface</param> public abstract void Draw( DrawingContext drawingContext, Point origin, InvertAxes inversion ); /// <summary> /// Client to collapse the line and get a collapsed line that fits for display /// </summary> /// <param name="collapsingPropertiesList">a list of collapsing properties</param> public abstract TextLine Collapse( params TextCollapsingProperties[] collapsingPropertiesList ); /// <summary> /// Client to get a collection of collapsed cha----r ranges after a line has been collapsed /// </summary> public abstract IList<TextCollapsedRange> GetTextCollapsedRanges(); /// <summary> /// Client to get the character hit corresponding to the specified /// distance from the beginning of the line. /// </summary> /// <param name="distance">distance in text flow direction from the beginning of the line</param> /// <returns>character hit</returns> public abstract CharacterHit GetCharacterHitFromDistance( double distance ); /// <summary> /// Client to get the distance from the beginning of the line from the specified /// character hit. /// </summary> /// <param name="characterHit">character hit of the character to query the distance.</param> /// <returns>distance in text flow direction from the beginning of the line.</returns> public abstract double GetDistanceFromCharacterHit( CharacterHit characterHit ); /// <summary> /// Client to get the next character hit for caret navigation /// </summary> /// <param name="characterHit">the current character hit</param> /// <returns>the next character hit</returns> public abstract CharacterHit GetNextCaretCharacterHit( CharacterHit characterHit ); /// <summary> /// Client to get the previous character hit for caret navigation /// </summary> /// <param name="characterHit">the current character hit</param> /// <returns>the previous character hit</returns> public abstract CharacterHit GetPreviousCaretCharacterHit( CharacterHit characterHit ); /// <summary> /// Client to get the previous character hit after backspacing /// </summary> /// <param name="characterHit">the current character hit</param> /// <returns>the character hit after backspacing</returns> public abstract CharacterHit GetBackspaceCaretCharacterHit( CharacterHit characterHit ); /// <summary> /// Determine whether the input character hit is a valid caret stop. /// </summary> /// <param name="characterHit">the current character hit</param> /// <param name="cpFirst">the starting cp index of the line</param> /// <remarks> /// It is used by Framework to iterate through each codepoint in the line to /// see if the code point is a caret stop. In general, the leading edge of /// codepoint is a valid caret stop if moving forward and then backward will /// return back to it, vice versa for the trailing edge of a codepoint. /// </remarks> [FriendAccessAllowed] internal bool IsAtCaretCharacterHit(CharacterHit characterHit, int cpFirst) { // TrailingLength is used as a flag to indicate whether the character // hit is on the leading or trailing edge of the character. if (characterHit.TrailingLength == 0) { CharacterHit nextHit = GetNextCaretCharacterHit(characterHit); if (nextHit == characterHit) { // At this point we only know that no caret stop is available // after the input, we caliberate the input to the end of the line. nextHit = new CharacterHit(cpFirst + Length - 1, 1); } CharacterHit previousHit = GetPreviousCaretCharacterHit(nextHit); return previousHit == characterHit; } else { CharacterHit previousHit = GetPreviousCaretCharacterHit(characterHit); CharacterHit nextHit = GetNextCaretCharacterHit(previousHit); return nextHit == characterHit; } } /// <summary> /// Client to get an array of bounding rectangles of a range of characters within a text line. /// </summary> /// <param name="firstTextSourceCharacterIndex">index of first character of specified range</param> /// <param name="textLength">number of characters of the specified range</param> /// <returns>an array of bounding rectangles.</returns> public abstract IList<TextBounds> GetTextBounds( int firstTextSourceCharacterIndex, int textLength ); /// <summary> /// Client to get a collection of TextRun span objects within a line /// </summary> public abstract IList<TextSpan<TextRun>> GetTextRunSpans(); /// <summary> /// Client to get IndexedGlyphRuns enumerable to enumerate each IndexedGlyphRun object /// in the line. Through IndexedGlyphRun client can obtain glyph information of /// a text source character. /// </summary> public abstract IEnumerable<IndexedGlyphRun> GetIndexedGlyphRuns(); /// <summary> /// Client to get a boolean value indicates whether content of the line overflows /// the specified paragraph width. /// </summary> public abstract bool HasOverflowed { get; } /// <summary> /// Client to get a boolean value indicates whether a line has been collapsed /// </summary> public abstract bool HasCollapsed { get; } /// <summary> /// Client to get a Boolean flag indicating whether the line is truncated in the /// middle of a word. This flag is set only when TextParagraphProperties.TextWrapping /// is set to TextWrapping.Wrap and a single word is longer than the formatting /// paragraph width. In such situation, TextFormatter truncates the line in the middle /// of the word to honor the desired behavior specified by TextWrapping.Wrap setting. /// </summary> public virtual bool IsTruncated { get { return false; } } /// <summary> /// Client to acquire a state at the point where line is broken by line breaking process; /// can be null when the line ends by the ending of the paragraph. Client may pass this /// value back to TextFormatter as an input argument to TextFormatter.FormatLine when /// formatting the next line within the same paragraph. /// </summary> public abstract TextLineBreak GetTextLineBreak(); #region ITextMetrics /// <summary> /// Client to get the number of text source positions of this line /// </summary> public abstract int Length { get; } /// <summary> /// Client to get the number of whitespace characters at the end of the line. /// </summary> public abstract int TrailingWhitespaceLength { get; } /// <summary> /// Client to get the number of characters following the last character /// of the line that may trigger reformatting of the current line. /// </summary> public abstract int DependentLength { get; } /// <summary> /// Client to get the number of newline characters at line end /// </summary> public abstract int NewlineLength { get; } /// <summary> /// Client to get distance from paragraph start to line start /// </summary> public abstract double Start { get; } /// <summary> /// Client to get the total width of this line /// </summary> public abstract double Width { get; } /// <summary> /// Client to get the total width of this line including width of whitespace characters at the end of the line. /// </summary> public abstract double WidthIncludingTrailingWhitespace { get; } /// <summary> /// Client to get the height of the line /// </summary> public abstract double Height { get; } /// <summary> /// Client to get the height of the text (or other content) in the line; this property may differ from the Height /// property if the client specified the line height /// </summary> public abstract double TextHeight { get; } /// <summary> /// Client to get the height of the actual black of the line /// </summary> public abstract double Extent { get; } /// <summary> /// Client to get the distance from top to baseline of this text line /// </summary> public abstract double Baseline { get; } /// <summary> /// Client to get the distance from the top of the text (or other content) to the baseline of this text line; /// this property may differ from the Baseline property if the client specified the line height /// </summary> public abstract double TextBaseline { get; } /// <summary> /// Client to get the distance from the before edge of line height /// to the baseline of marker of the line if any. /// </summary> public abstract double MarkerBaseline { get; } /// <summary> /// Client to get the overall height of the list items marker of the line if any. /// </summary> public abstract double MarkerHeight { get; } /// <summary> /// Client to get the distance covering all black preceding the leading edge of the line. /// </summary> public abstract double OverhangLeading { get; } /// <summary> /// Client to get the distance covering all black following the trailing edge of the line. /// </summary> public abstract double OverhangTrailing { get; } /// <summary> /// Client to get the distance from the after edge of line height to the after edge of the extent of the line. /// </summary> public abstract double OverhangAfter { get; } #endregion } /// <summary> /// Indicate the inversion of axes of the drawing surface /// </summary> [Flags] public enum InvertAxes { /// <summary> /// Drawing surface is not inverted in either axis /// </summary> None = 0, /// <summary> /// Drawing surface is inverted in horizontal axis /// </summary> Horizontal = 1, /// <summary> /// Drawing surface is inverted in vertical axis /// </summary> Vertical = 2, /// <summary> /// Drawing surface is inverted in both axes /// </summary> Both = (Horizontal | Vertical), } }
using System; using System.Collections.Generic; using System.Globalization; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Input; namespace helloWorld { public enum GameState { MainMenu = 0, Game = 1 } /// <summary> /// This is the main type for your game /// </summary> public class Main : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; float leftTurn = (float)Math.PI / -2; GameState state = GameState.MainMenu; int lives = 3; int score = 0; double turnSpeed = 0.1; int screenWidth = 1920; int screenHeight = 1080; IScreenMovement movement; StarField backGround; Texture2D titleTexture; Texture2D shipTexture, exhaustTexture; Entity ship; List<Texture2D> rockTextures = new List<Texture2D> (); List<Asteroid> asteroids = new List<Asteroid> (); List<Asteroid> newAsteroids = new List<Asteroid> (); List<Asteroid> destroyedAsteroids = new List<Asteroid> (); Texture2D bulletTexture; List<Particle> bullets = new List<Particle> (); List<Particle> destroyedBullets = new List<Particle> (); TimeSpan bulletFired; TimeSpan bulletFlightTime = new TimeSpan (0, 0, 3); Thruster thruster; List<IParticleEmitter> particles = new List<IParticleEmitter> (); Dictionary<Char, Texture2D> numbers = new Dictionary<Char, Texture2D> (); Random rng = new Random(); Song BackgroundMusic; public Main() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; this.Window.Title = "Hello World"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); graphics.PreferredBackBufferWidth = screenWidth; graphics.PreferredBackBufferHeight = screenHeight; graphics.IsFullScreen = true; graphics.ApplyChanges(); SpawnShip (); spawnRocks (); MediaPlayer.IsRepeating = true; MediaPlayer.Play (BackgroundMusic); MediaPlayer.Volume = 0.5f; } protected void spawnRocks() { asteroids.Clear (); addNewRock (50, 50); addNewRock (screenWidth - 50, 50); addNewRock (screenWidth - 50, screenHeight - 50); addNewRock (50, screenHeight - 50); } protected void addNewRock(double x, double y) { var tempRock = new Asteroid (); tempRock.x = x; tempRock.y = y; tempRock.dx = rng.NextDouble () * 2.0 - 1.0; tempRock.dy = rng.NextDouble () * 2.0 - 1.0; tempRock.dangle = (rng.NextDouble () * 2 - 1) * 0.02; tempRock.phase = 3; tempRock.texture = rockTextures[tempRock.phase]; asteroids.Add (tempRock); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); titleTexture = Content.Load<Texture2D> ("title"); shipTexture = Content.Load<Texture2D> ("ship"); bulletTexture = Content.Load<Texture2D> ("bullet"); exhaustTexture = Content.Load<Texture2D> ("exhaust"); rockTextures.Add (Content.Load<Texture2D> ("rock_1")); rockTextures.Add (Content.Load<Texture2D> ("rock_2")); rockTextures.Add (Content.Load<Texture2D> ("rock_3")); rockTextures.Add (Content.Load<Texture2D> ("rock_4")); var starTextures = new List<Texture2D> (); starTextures.Add(Content.Load<Texture2D> ("star_0")); starTextures.Add(Content.Load<Texture2D> ("star_1")); starTextures.Add(Content.Load<Texture2D> ("star_2")); starTextures.Add(Content.Load<Texture2D> ("star_3")); numbers ['0'] = Content.Load<Texture2D> ("0"); numbers ['1'] = Content.Load<Texture2D> ("1"); numbers ['2'] = Content.Load<Texture2D> ("2"); numbers ['3'] = Content.Load<Texture2D> ("3"); numbers ['4'] = Content.Load<Texture2D> ("4"); numbers ['5'] = Content.Load<Texture2D> ("5"); numbers ['6'] = Content.Load<Texture2D> ("6"); numbers ['7'] = Content.Load<Texture2D> ("7"); numbers ['8'] = Content.Load<Texture2D> ("8"); numbers ['9'] = Content.Load<Texture2D> ("9"); BackgroundMusic = Content.Load<Song> ("bg"); backGround = new StarField (rng, screenWidth, screenHeight, starTextures); backGround.Init (); movement = new DonutSpace(screenWidth, screenHeight); thruster = new Thruster (rng, exhaustTexture, movement); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { GamePadState gamePadState = GamePad.GetState(PlayerIndex.One); KeyboardState keyboardState = Keyboard.GetState(); // For Mobile devices, this logic will close the Game when the Back button is pressed if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || keyboardState.IsKeyDown(Keys.Escape)) { if (state == GameState.MainMenu) { Exit (); } else { state = GameState.MainMenu; } } if (state == GameState.Game) { if (gamePadState.ThumbSticks.Left.X < -0.1 || keyboardState.IsKeyDown(Keys.Left)) { ship.angle -= turnSpeed; } if (gamePadState.ThumbSticks.Left.X > 0.1 || keyboardState.IsKeyDown(Keys.Right)) { ship.angle += turnSpeed; } if (gamePadState.ThumbSticks.Left.Y > 0.1 || keyboardState.IsKeyDown(Keys.Up)) { ship.dx += Math.Cos (ship.angle) * 0.1; ship.dy += Math.Sin (ship.angle) * 0.1; thruster.x = ship.x + Math.Cos (ship.angle) * -25; thruster.y = ship.y + Math.Sin (ship.angle) * -25; thruster.angle = ship.angle + Math.PI; thruster.Emit (gameTime); } if (GamePad.GetState (PlayerIndex.One).Buttons.A == ButtonState.Pressed || keyboardState.IsKeyDown(Keys.Space)) { Shoot (gameTime); } } else { if (GamePad.GetState (PlayerIndex.One).Buttons.A == ButtonState.Pressed || keyboardState.IsKeyDown(Keys.Space)) { spawnRocks (); SpawnShip (); lives = 3; score = 0; state = GameState.Game; } } bullets.RemoveAll (x => gameTime.TotalGameTime - x.SpawnTime > bulletFlightTime); foreach (var bullet in bullets) { movement.MoveEntity (bullet); var bulletOrigin = new Vector2 ((float)bullet.x, (float)bullet.y); var bulletCircle = new Circle (bulletOrigin, bullet.texture.Width / 2); foreach (var asteroid in asteroids) { var asteroidOrigin = new Vector2 ((float)asteroid.x, (float)asteroid.y); var asteroidCircle = new Circle (asteroidOrigin, asteroid.texture.Width / 2); if (bulletCircle.Intersects (asteroidCircle)) { DestroyAsteroid (asteroid, bullet, gameTime); } } } thruster.Update (gameTime); foreach (var asteroid in destroyedAsteroids) { asteroids.Remove (asteroid); } destroyedAsteroids.Clear (); foreach (var asteroid in newAsteroids) { asteroids.Add (asteroid); } newAsteroids.Clear (); foreach (var bullet in destroyedBullets) { bullets.Remove (bullet); } particles.RemoveAll (x => x.Done); foreach (var emitter in particles) { emitter.Update (gameTime); } if (asteroids.Count == 0) { spawnRocks (); } movement.MoveEntity (ship); var shipOrigin = new Vector2((float)ship.x, (float)ship.y); var shipCircle = new Circle (shipOrigin, ship.texture.Width / 2 - 4); foreach (var asteroid in asteroids) { movement.MoveEntity (asteroid); var asteroidOrigin = new Vector2 ((float)asteroid.x, (float)asteroid.y); var asteroidCircle = new Circle (asteroidOrigin, asteroid.texture.Width / 2 - 4); if (state == GameState.Game) { if (shipCircle.Intersects (asteroidCircle)) { ShipExplosion (gameTime); break; } } } backGround.Update (gameTime); base.Update(gameTime); } protected void DestroyAsteroid(Asteroid asteroid, Particle bullet, GameTime gameTime) { score++; destroyedAsteroids.Add (asteroid); destroyedBullets.Add (bullet); if (asteroid.phase > 0) { for (int i = 0; i < 3; i++) { var newAsteroid = new Asteroid (); newAsteroid.x = asteroid.x; newAsteroid.y = asteroid.y; newAsteroid.dx = rng.NextDouble () * 2.0 - 1.0; newAsteroid.dy = rng.NextDouble () * 2.0 - 1.0; newAsteroid.dangle = rng.NextDouble () * 0.02; newAsteroid.phase = asteroid.phase - 1; newAsteroid.texture = rockTextures[newAsteroid.phase]; newAsteroids.Add (newAsteroid); } } var explosion = new Explosion (rng, bulletTexture, movement) { ParticleCount = 10, ParticleSpeed = 4, ParticleLifeTime = new TimeSpan (0, 0, 0, 0, 250), EmitterLifeTime = new TimeSpan(0, 0, 0, 0, 10), x = bullet.x, y = bullet.y }; explosion.Emit (gameTime); particles.Add (explosion); } protected void Shoot(GameTime gameTime) { if (gameTime.TotalGameTime - bulletFired < new TimeSpan (0, 0, 0, 0, 500)) { return; } var bullet = new Particle () { x = ship.x, y = ship.y, angle = ship.angle, dx = Math.Cos (ship.angle) * 4, dy = Math.Sin (ship.angle) * 4, texture = bulletTexture, SpawnTime = gameTime.TotalGameTime }; bullets.Add (bullet); bulletFired = gameTime.TotalGameTime; } protected void ShipExplosion(GameTime gameTime) { var explosion = new Explosion (rng, bulletTexture, movement) { ParticleCount = 15, ParticleSpeed = 4, ParticleLifeTime = new TimeSpan (0, 0, 0, 0, 750), EmitterLifeTime = new TimeSpan(0, 0, 0, 0, 50), x = ship.x, y = ship.y }; explosion.Emit (gameTime); particles.Add (explosion); lives--; if (lives < 0) { state = GameState.MainMenu; } SpawnShip (); } protected void SpawnShip() { if (ship == null) { ship = new Entity (); } ship.x = screenWidth / 2; ship.y = screenHeight / 2; ship.dx = 0; ship.dy = 0; ship.angle = leftTurn; ship.texture = shipTexture; } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(); Vector2 location; Rectangle sourceRectangle; Vector2 origin; backGround.Draw (spriteBatch); thruster.Draw (spriteBatch); if (state == GameState.Game) { ship.Draw (spriteBatch); } foreach (var asteroid in asteroids) { asteroid.Draw (spriteBatch); } foreach (var bullet in bullets) { bullet.Draw (spriteBatch); } foreach (var emitter in particles) { emitter.Draw (spriteBatch); } if (state == GameState.Game) { for (int i = 0; i < lives; i++) { location = new Vector2 (ship.texture.Width / 2 * i + 20, ship.texture.Height / 2); sourceRectangle = new Rectangle (0, 0, ship.texture.Width, ship.texture.Height); origin = new Vector2 (ship.texture.Width / 2, ship.texture.Height / 2); spriteBatch.Draw(texture: ship.texture, position: location, sourceRectangle: sourceRectangle, color: Color.White, rotation: leftTurn, origin: origin, scale: new Vector2(0.5f)); } } else { location = new Vector2 (screenWidth / 2, screenHeight / 2); sourceRectangle = new Rectangle (0, 0, titleTexture.Width, titleTexture.Height); origin = new Vector2 (titleTexture.Width / 2, titleTexture.Height / 2); spriteBatch.Draw (texture: titleTexture, position: location, sourceRectangle: sourceRectangle, color: Color.White, rotation: 0.0f, origin: origin); } var scoreStr = score.ToString (CultureInfo.InvariantCulture); int index = 0; foreach (var chr in scoreStr) { location = new Vector2 (25 * index + 85, 12); sourceRectangle = new Rectangle (0, 0, 25, 25); origin = new Vector2 (0, 0); spriteBatch.Draw (texture: numbers[chr], position: location, sourceRectangle: sourceRectangle, color: Color.White, rotation: 0.0f, origin: origin); index++; } spriteBatch.End(); //TODO: Drawing on the edge (ie. two blits instead of one) base.Draw(gameTime); } } }
//----------------------------------------------------------------------- // <copyright company="CoApp Project"> // ResourceLib Original Code from http://resourcelib.codeplex.com // Original Copyright (c) 2008-2009 Vestris Inc. // Changes Copyright (c) 2011 Garrett Serack . All rights reserved. // </copyright> // <license> // MIT License // You may freely use and distribute this software under the terms of the following license agreement. // // 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 // </license> //----------------------------------------------------------------------- namespace ClrPlus.Windows.Api.Enumerations { /// <summary> /// Virtual key definitions. /// </summary> public enum VirtualKeys : uint { /// <summary> /// Standard virtual left mouse button. /// </summary> VK_LBUTTON = 0x01, /// <summary> /// Standard virtual right mouse button. /// </summary> VK_RBUTTON = 0x02, /// <summary> /// Ctrl-Break / Ctrl-C. /// </summary> VK_CANCEL = 0x03, /// <summary> /// Standard virtual middle mouse button. /// </summary> VK_MBUTTON = 0x04, /// <summary> /// </summary> VK_XBUTTON1 = 0x05, /// <summary> /// </summary> VK_XBUTTON2 = 0x06, /// <summary> /// Backspace. /// </summary> VK_BACK = 0x08, /// <summary> /// Tab. /// </summary> VK_TAB = 0x09, /// <summary> /// Delete. /// </summary> VK_CLEAR = 0x0C, /// <summary> /// Return. /// </summary> VK_RETURN = 0x0D, /// <summary> /// Shift. /// </summary> VK_SHIFT = 0x10, /// <summary> /// Control. /// </summary> VK_CONTROL = 0x11, /// <summary> /// Menu. /// </summary> VK_MENU = 0x12, /// <summary> /// Pause. /// </summary> VK_PAUSE = 0x13, /// <summary> /// Caps lock. /// </summary> VK_CAPITAL = 0x14, /// <summary> /// </summary> VK_KANA = 0x15, /// <summary> /// </summary> VK_JUNJA = 0x17, /// <summary> /// </summary> VK_FINAL = 0x18, /// <summary> /// </summary> VK_KANJI = 0x19, /// <summary> /// Escape. /// </summary> VK_ESCAPE = 0x1B, /// <summary> /// </summary> VK_CONVERT = 0x1C, /// <summary> /// </summary> VK_NONCONVERT = 0x1D, /// <summary> /// </summary> VK_ACCEPT = 0x1E, /// <summary> /// </summary> VK_MODECHANGE = 0x1F, /// <summary> /// Space. /// </summary> VK_SPACE = 0x20, /// <summary> /// </summary> VK_PRIOR = 0x21, /// <summary> /// </summary> VK_NEXT = 0x22, /// <summary> /// End. /// </summary> VK_END = 0x23, /// <summary> /// Home. /// </summary> VK_HOME = 0x24, /// <summary> /// Left arrow. /// </summary> VK_LEFT = 0x25, /// <summary> /// Up arrow. /// </summary> VK_UP = 0x26, /// <summary> /// Right arrow. /// </summary> VK_RIGHT = 0x27, /// <summary> /// Down arrow. /// </summary> VK_DOWN = 0x28, /// <summary> /// </summary> VK_SELECT = 0x29, /// <summary> /// Print Screen. /// </summary> VK_PRINT = 0x2A, /// <summary> /// </summary> VK_EXECUTE = 0x2B, /// <summary> /// </summary> VK_SNAPSHOT = 0x2C, /// <summary> /// Insert. /// </summary> VK_INSERT = 0x2D, /// <summary> /// Delete. /// </summary> VK_DELETE = 0x2E, /// <summary> /// </summary> VK_HELP = 0x2F, /// <summary> /// </summary> VK_LWIN = 0x5B, /// <summary> /// </summary> VK_RWIN = 0x5C, /// <summary> /// </summary> VK_APPS = 0x5D, /// <summary> /// </summary> VK_SLEEP = 0x5F, /// <summary> /// </summary> VK_NUMPAD0 = 0x60, /// <summary> /// </summary> VK_NUMPAD1 = 0x61, /// <summary> /// </summary> VK_NUMPAD2 = 0x62, /// <summary> /// </summary> VK_NUMPAD3 = 0x63, /// <summary> /// </summary> VK_NUMPAD4 = 0x64, /// <summary> /// </summary> VK_NUMPAD5 = 0x65, /// <summary> /// </summary> VK_NUMPAD6 = 0x66, /// <summary> /// </summary> VK_NUMPAD7 = 0x67, /// <summary> /// </summary> VK_NUMPAD8 = 0x68, /// <summary> /// </summary> VK_NUMPAD9 = 0x69, /// <summary> /// </summary> VK_MULTIPLY = 0x6A, /// <summary> /// </summary> VK_ADD = 0x6B, /// <summary> /// </summary> VK_SEPARATOR = 0x6C, /// <summary> /// </summary> VK_SUBTRACT = 0x6D, /// <summary> /// </summary> VK_DECIMAL = 0x6E, /// <summary> /// </summary> VK_DIVIDE = 0x6F, /// <summary> /// </summary> VK_F1 = 0x70, /// <summary> /// </summary> VK_F2 = 0x71, /// <summary> /// </summary> VK_F3 = 0x72, /// <summary> /// </summary> VK_F4 = 0x73, /// <summary> /// </summary> VK_F5 = 0x74, /// <summary> /// </summary> VK_F6 = 0x75, /// <summary> /// </summary> VK_F7 = 0x76, /// <summary> /// </summary> VK_F8 = 0x77, /// <summary> /// </summary> VK_F9 = 0x78, /// <summary> /// </summary> VK_F10 = 0x79, /// <summary> /// </summary> VK_F11 = 0x7A, /// <summary> /// </summary> VK_F12 = 0x7B, /// <summary> /// </summary> VK_F13 = 0x7C, /// <summary> /// </summary> VK_F14 = 0x7D, /// <summary> /// </summary> VK_F15 = 0x7E, /// <summary> /// </summary> VK_F16 = 0x7F, /// <summary> /// </summary> VK_F17 = 0x80, /// <summary> /// </summary> VK_F18 = 0x81, /// <summary> /// </summary> VK_F19 = 0x82, /// <summary> /// </summary> VK_F20 = 0x83, /// <summary> /// </summary> VK_F21 = 0x84, /// <summary> /// </summary> VK_F22 = 0x85, /// <summary> /// </summary> VK_F23 = 0x86, /// <summary> /// </summary> VK_F24 = 0x87, /// <summary> /// </summary> VK_NUMLOCK = 0x90, /// <summary> /// </summary> VK_SCROLL = 0x91, /// <summary> /// NEC PC-9800 keyboard '=' key on numpad. /// </summary> VK_OEM_NEC_EQUAL = 0x92, /// <summary> /// Fujitsu/OASYS keyboard 'Dictionary' key. /// </summary> VK_OEM_FJ_JISHO = 0x92, /// <summary> /// Fujitsu/OASYS keyboard 'Unregister word' key. /// </summary> VK_OEM_FJ_MASSHOU = 0x93, /// <summary> /// Fujitsu/OASYS keyboard 'Register word' key. /// </summary> VK_OEM_FJ_TOUROKU = 0x94, /// <summary> /// Fujitsu/OASYS keyboard 'Left OYAYUBI' key. /// </summary> VK_OEM_FJ_LOYA = 0x95, /// <summary> /// Fujitsu/OASYS keyboard 'Right OYAYUBI' key. /// </summary> VK_OEM_FJ_ROYA = 0x96, /// <summary> /// </summary> VK_LSHIFT = 0xA0, /// <summary> /// </summary> VK_RSHIFT = 0xA1, /// <summary> /// </summary> VK_LCONTROL = 0xA2, /// <summary> /// </summary> VK_RCONTROL = 0xA3, /// <summary> /// </summary> VK_LMENU = 0xA4, /// <summary> /// </summary> VK_RMENU = 0xA5, /// <summary> /// </summary> VK_BROWSER_BACK = 0xA6, /// <summary> /// </summary> VK_BROWSER_FORWARD = 0xA7, /// <summary> /// </summary> VK_BROWSER_REFRESH = 0xA8, /// <summary> /// </summary> VK_BROWSER_STOP = 0xA9, /// <summary> /// </summary> VK_BROWSER_SEARCH = 0xAA, /// <summary> /// </summary> VK_BROWSER_FAVORITES = 0xAB, /// <summary> /// </summary> VK_BROWSER_HOME = 0xAC, /// <summary> /// </summary> VK_VOLUME_MUTE = 0xAD, /// <summary> /// </summary> VK_VOLUME_DOWN = 0xAE, /// <summary> /// </summary> VK_VOLUME_UP = 0xAF, /// <summary> /// </summary> VK_MEDIA_NEXT_TRACK = 0xB0, /// <summary> /// </summary> VK_MEDIA_PREV_TRACK = 0xB1, /// <summary> /// </summary> VK_MEDIA_STOP = 0xB2, /// <summary> /// </summary> VK_MEDIA_PLAY_PAUSE = 0xB3, /// <summary> /// </summary> VK_LAUNCH_MAIL = 0xB4, /// <summary> /// </summary> VK_LAUNCH_MEDIA_SELECT = 0xB5, /// <summary> /// </summary> VK_LAUNCH_APP1 = 0xB6, /// <summary> /// </summary> VK_LAUNCH_APP2 = 0xB7, /// <summary> /// ';:' for US /// </summary> VK_OEM_1 = 0xBA, /// <summary> /// '+' any country /// </summary> VK_OEM_PLUS = 0xBB, /// <summary> /// ',' any country /// </summary> VK_OEM_COMMA = 0xBC, /// <summary> /// '-' any country /// </summary> VK_OEM_MINUS = 0xBD, /// <summary> /// '.' any country /// </summary> VK_OEM_PERIOD = 0xBE, /// <summary> /// '/?' for US /// </summary> VK_OEM_2 = 0xBF, /// <summary> /// '`~' for US /// </summary> VK_OEM_3 = 0xC0, /// <summary> /// '[{' for US /// </summary> VK_OEM_4 = 0xDB, /// <summary> /// '\|' for US /// </summary> VK_OEM_5 = 0xDC, /// <summary> /// ']}' for US /// </summary> VK_OEM_6 = 0xDD, /// <summary> /// ''"' for US /// </summary> VK_OEM_7 = 0xDE, /// <summary> /// </summary> VK_OEM_8 = 0xDF, /// <summary> /// 'AX' key on Japanese AX kbd /// </summary> VK_OEM_AX = 0xE1, /// <summary> /// "&lt;&gt;" or "\|" on RT 102-key kbd. /// </summary> VK_OEM_102 = 0xE2, /// <summary> /// Help key on ICO /// </summary> VK_ICO_HELP = 0xE3, /// <summary> /// 00 key on ICO /// </summary> VK_ICO_00 = 0xE4, /// <summary> /// </summary> VK_PROCESSKEY = 0xE5, /// <summary> /// </summary> VK_ICO_CLEAR = 0xE6, /// <summary> /// </summary> VK_PACKET = 0xE7, /// <summary> /// </summary> VK_OEM_RESET = 0xE9, /// <summary> /// </summary> VK_OEM_JUMP = 0xEA, /// <summary> /// </summary> VK_OEM_PA1 = 0xEB, /// <summary> /// </summary> VK_OEM_PA2 = 0xEC, /// <summary> /// </summary> VK_OEM_PA3 = 0xED, /// <summary> /// </summary> VK_OEM_WSCTRL = 0xEE, /// <summary> /// </summary> VK_OEM_CUSEL = 0xEF, /// <summary> /// </summary> VK_OEM_ATTN = 0xF0, /// <summary> /// </summary> VK_OEM_FINISH = 0xF1, /// <summary> /// </summary> VK_OEM_COPY = 0xF2, /// <summary> /// </summary> VK_OEM_AUTO = 0xF3, /// <summary> /// </summary> VK_OEM_ENLW = 0xF4, /// <summary> /// </summary> VK_OEM_BACKTAB = 0xF5, /// <summary> /// </summary> VK_ATTN = 0xF6, /// <summary> /// </summary> VK_CRSEL = 0xF7, /// <summary> /// </summary> VK_EXSEL = 0xF8, /// <summary> /// </summary> VK_EREOF = 0xF9, /// <summary> /// </summary> VK_PLAY = 0xFA, /// <summary> /// </summary> VK_ZOOM = 0xFB, /// <summary> /// </summary> VK_NONAME = 0xFC, /// <summary> /// </summary> VK_PA1 = 0xFD, /// <summary> /// </summary> VK_OEM_CLEAR = 0xFE } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ConvertToVector256Int16SByte() { var test = new SimpleUnaryOpTest__ConvertToVector256Int16SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using the pointer overload test.RunBasicScenario_Ptr(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using the pointer overload test.RunReflectionScenario_Ptr(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToVector256Int16SByte { private const int VectorSize = 32; private const int Op1ElementCount = 16 / sizeof(SByte); private const int RetElementCount = VectorSize / sizeof(Int16); private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private SimpleUnaryOpTest__DataTable<Int16, SByte> _dataTable; static SimpleUnaryOpTest__ConvertToVector256Int16SByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), 16); } public SimpleUnaryOpTest__ConvertToVector256Int16SByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), 16); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, SByte>(_data, new Int16[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.ConvertToVector256Int16( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Ptr() { var result = Avx2.ConvertToVector256Int16( (SByte*)(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.ConvertToVector256Int16( Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.ConvertToVector256Int16( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int16), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Ptr() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int16), new Type[] { typeof(SByte*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArrayPtr, typeof(SByte*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int16), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int16), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.ConvertToVector256Int16( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = Avx2.ConvertToVector256Int16(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = Avx2.ConvertToVector256Int16(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)); var result = Avx2.ConvertToVector256Int16(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ConvertToVector256Int16SByte(); var result = Avx2.ConvertToVector256Int16(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.ConvertToVector256Int16(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<SByte> firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), 16); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(SByte[] firstOp, Int16[] result, [CallerMemberName] string method = "") { if (result[0] != firstOp[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != firstOp[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ConvertToVector256Int16)}<Int16>(Vector128<SByte>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Threading.Tasks; using IdentityServer4.Models; using IdentityServer4.Extensions; using IdentityServer4.Hosting; using IdentityModel; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using System; using IdentityServer4.Services; using IdentityServer4.Configuration; using IdentityServer4.Stores; using IdentityServer4.ResponseHandling; using Microsoft.AspNetCore.Authentication; using System.Text.Encodings.Web; namespace IdentityServer4.Endpoints.Results { internal class AuthorizeResult : IEndpointResult { public AuthorizeResponse Response { get; } public AuthorizeResult(AuthorizeResponse response) { Response = response ?? throw new ArgumentNullException(nameof(response)); } internal AuthorizeResult( AuthorizeResponse response, IdentityServerOptions options, IUserSession userSession, IMessageStore<ErrorMessage> errorMessageStore, ISystemClock clock) : this(response) { _options = options; _userSession = userSession; _errorMessageStore = errorMessageStore; _clock = clock; } private IdentityServerOptions _options; private IUserSession _userSession; private IMessageStore<ErrorMessage> _errorMessageStore; private ISystemClock _clock; private void Init(HttpContext context) { _options = _options ?? context.RequestServices.GetRequiredService<IdentityServerOptions>(); _userSession = _userSession ?? context.RequestServices.GetRequiredService<IUserSession>(); _errorMessageStore = _errorMessageStore ?? context.RequestServices.GetRequiredService<IMessageStore<ErrorMessage>>(); _clock = _clock ?? context.RequestServices.GetRequiredService<ISystemClock>(); } public async Task ExecuteAsync(HttpContext context) { Init(context); if (Response.IsError) { await ProcessErrorAsync(context); } else { await ProcessResponseAsync(context); } } private async Task ProcessErrorAsync(HttpContext context) { // these are the conditions where we can send a response // back directly to the client, otherwise we're only showing the error UI var isSafeError = Response.Error == OidcConstants.AuthorizeErrors.AccessDenied || Response.Error == OidcConstants.AuthorizeErrors.AccountSelectionRequired || Response.Error == OidcConstants.AuthorizeErrors.LoginRequired || Response.Error == OidcConstants.AuthorizeErrors.ConsentRequired || Response.Error == OidcConstants.AuthorizeErrors.InteractionRequired; if (isSafeError) { // this scenario we can return back to the client await ProcessResponseAsync(context); } else { // we now know we must show error page await RedirectToErrorPageAsync(context); } } protected async Task ProcessResponseAsync(HttpContext context) { if (!Response.IsError) { // success response -- track client authorization for sign-out //_logger.LogDebug("Adding client {0} to client list cookie for subject {1}", request.ClientId, request.Subject.GetSubjectId()); await _userSession.AddClientIdAsync(Response.Request.ClientId); } await RenderAuthorizeResponseAsync(context); } private async Task RenderAuthorizeResponseAsync(HttpContext context) { if (Response.Request.ResponseMode == OidcConstants.ResponseModes.Query || Response.Request.ResponseMode == OidcConstants.ResponseModes.Fragment) { context.Response.SetNoCache(); context.Response.Redirect(BuildRedirectUri()); } else if (Response.Request.ResponseMode == OidcConstants.ResponseModes.FormPost) { context.Response.SetNoCache(); AddSecurityHeaders(context); await context.Response.WriteHtmlAsync(GetFormPostHtml()); } else { //_logger.LogError("Unsupported response mode."); throw new InvalidOperationException("Unsupported response mode"); } } private void AddSecurityHeaders(HttpContext context) { context.Response.AddScriptCspHeaders(_options.Csp, "sha256-orD0/VhH8hLqrLxKHD/HUEMdwqX6/0ve7c5hspX5VJ8="); var referrer_policy = "no-referrer"; if (!context.Response.Headers.ContainsKey("Referrer-Policy")) { context.Response.Headers.Add("Referrer-Policy", referrer_policy); } } private string BuildRedirectUri() { var uri = Response.RedirectUri; var query = Response.ToNameValueCollection().ToQueryString(); if (Response.Request.ResponseMode == OidcConstants.ResponseModes.Query) { uri = uri.AddQueryString(query); } else { uri = uri.AddHashFragment(query); } if (Response.IsError && !uri.Contains("#")) { // https://tools.ietf.org/html/draft-bradley-oauth-open-redirector-00 uri += "#_=_"; } return uri; } private const string FormPostHtml = "<html><head><meta http-equiv='X-UA-Compatible' content='IE=edge' /><base target='_self'/></head><body><form method='post' action='{uri}'>{body}<noscript><button>Click to continue</button></noscript></form><script>window.addEventListener('load', function(){document.forms[0].submit();});</script></body></html>"; private string GetFormPostHtml() { var html = FormPostHtml; var url = Response.Request.RedirectUri; url = HtmlEncoder.Default.Encode(url); html = html.Replace("{uri}", url); html = html.Replace("{body}", Response.ToNameValueCollection().ToFormPost()); return html; } private async Task RedirectToErrorPageAsync(HttpContext context) { var errorModel = new ErrorMessage { RequestId = context.TraceIdentifier, Error = Response.Error, ErrorDescription = Response.ErrorDescription, UiLocales = Response.Request?.UiLocales, DisplayMode = Response.Request?.DisplayMode, ClientId = Response.Request?.ClientId }; if (Response.RedirectUri != null && Response.Request?.ResponseMode != null) { // if we have a valid redirect uri, then include it to the error page errorModel.RedirectUri = BuildRedirectUri(); errorModel.ResponseMode = Response.Request.ResponseMode; } var message = new Message<ErrorMessage>(errorModel, _clock.UtcNow.UtcDateTime); var id = await _errorMessageStore.WriteAsync(message); var errorUrl = _options.UserInteraction.ErrorUrl; var url = errorUrl.AddQueryString(_options.UserInteraction.ErrorIdParameter, id); context.Response.RedirectToAbsoluteUrl(url); } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Text.Json; using JetBrains.Annotations; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; using JsonApiDotNetCore.Serialization.Objects; namespace JsonApiDotNetCore.Serialization.JsonConverters { /// <summary> /// Converts <see cref="ResourceObject" /> to/from JSON. /// </summary> [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public sealed class ResourceObjectConverter : JsonObjectConverter<ResourceObject> { private static readonly JsonEncodedText TypeText = JsonEncodedText.Encode("type"); private static readonly JsonEncodedText IdText = JsonEncodedText.Encode("id"); private static readonly JsonEncodedText LidText = JsonEncodedText.Encode("lid"); private static readonly JsonEncodedText MetaText = JsonEncodedText.Encode("meta"); private static readonly JsonEncodedText AttributesText = JsonEncodedText.Encode("attributes"); private static readonly JsonEncodedText RelationshipsText = JsonEncodedText.Encode("relationships"); private static readonly JsonEncodedText LinksText = JsonEncodedText.Encode("links"); private readonly IResourceGraph _resourceGraph; public ResourceObjectConverter(IResourceGraph resourceGraph) { _resourceGraph = resourceGraph; } /// <summary> /// Resolves the resource type and attributes against the resource graph. Because attribute values in <see cref="ResourceObject" /> are typed as /// <see cref="object" />, we must lookup and supply the target type to the serializer. /// </summary> public override ResourceObject Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // Inside a JsonConverter there is no way to know where in the JSON object tree we are. And the serializer is unable to provide // the correct position either. So we avoid an exception on missing/invalid 'type' element and postpone producing an error response // to the post-processing phase. var resourceObject = new ResourceObject { // The 'attributes' element may occur before 'type', but we need to know the resource type before we can deserialize attributes // into their corresponding CLR types. Type = TryPeekType(ref reader) }; ResourceContext resourceContext = resourceObject.Type != null ? _resourceGraph.TryGetResourceContext(resourceObject.Type) : null; while (reader.Read()) { switch (reader.TokenType) { case JsonTokenType.EndObject: { return resourceObject; } case JsonTokenType.PropertyName: { string propertyName = reader.GetString(); reader.Read(); switch (propertyName) { case "id": { if (reader.TokenType != JsonTokenType.String) { // Newtonsoft.Json used to auto-convert number to strings, while System.Text.Json does not. This is so likely // to hit users during upgrade that we special-case for this and produce a helpful error message. var jsonElement = ReadSubTree<JsonElement>(ref reader, options); throw new JsonException($"Failed to convert ID '{jsonElement}' of type '{jsonElement.ValueKind}' to type 'String'."); } resourceObject.Id = reader.GetString(); break; } case "lid": { resourceObject.Lid = reader.GetString(); break; } case "attributes": { if (resourceContext != null) { resourceObject.Attributes = ReadAttributes(ref reader, options, resourceContext); } else { reader.Skip(); } break; } case "relationships": { resourceObject.Relationships = ReadSubTree<IDictionary<string, RelationshipObject>>(ref reader, options); break; } case "links": { resourceObject.Links = ReadSubTree<ResourceLinks>(ref reader, options); break; } case "meta": { resourceObject.Meta = ReadSubTree<IDictionary<string, object>>(ref reader, options); break; } default: { reader.Skip(); break; } } break; } } } throw GetEndOfStreamError(); } private static string TryPeekType(ref Utf8JsonReader reader) { // https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to?pivots=dotnet-5-0#an-alternative-way-to-do-polymorphic-deserialization Utf8JsonReader readerClone = reader; while (readerClone.Read()) { if (readerClone.TokenType == JsonTokenType.PropertyName) { string propertyName = readerClone.GetString(); readerClone.Read(); switch (propertyName) { case "type": { return readerClone.GetString(); } default: { readerClone.Skip(); break; } } } } return null; } private static IDictionary<string, object> ReadAttributes(ref Utf8JsonReader reader, JsonSerializerOptions options, ResourceContext resourceContext) { var attributes = new Dictionary<string, object>(); while (reader.Read()) { switch (reader.TokenType) { case JsonTokenType.EndObject: { return attributes; } case JsonTokenType.PropertyName: { string attributeName = reader.GetString(); reader.Read(); AttrAttribute attribute = resourceContext.TryGetAttributeByPublicName(attributeName); PropertyInfo property = attribute?.Property; if (property != null) { object attributeValue; if (property.Name == nameof(Identifiable.Id)) { attributeValue = JsonInvalidAttributeInfo.Id; } else { try { attributeValue = JsonSerializer.Deserialize(ref reader, property.PropertyType, options); } catch (JsonException) { // Inside a JsonConverter there is no way to know where in the JSON object tree we are. And the serializer // is unable to provide the correct position either. So we avoid an exception and postpone producing an error // response to the post-processing phase, by setting a sentinel value. var jsonElement = ReadSubTree<JsonElement>(ref reader, options); attributeValue = new JsonInvalidAttributeInfo(attributeName, property.PropertyType, jsonElement.ToString(), jsonElement.ValueKind); } } attributes.Add(attributeName!, attributeValue); } else { reader.Skip(); } break; } } } throw GetEndOfStreamError(); } /// <summary> /// Ensures that attribute values are not wrapped in <see cref="JsonElement" />s. /// </summary> public override void Write(Utf8JsonWriter writer, ResourceObject value, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WriteString(TypeText, value.Type); if (value.Id != null) { writer.WriteString(IdText, value.Id); } if (value.Lid != null) { writer.WriteString(LidText, value.Lid); } if (!value.Attributes.IsNullOrEmpty()) { writer.WritePropertyName(AttributesText); WriteSubTree(writer, value.Attributes, options); } if (!value.Relationships.IsNullOrEmpty()) { writer.WritePropertyName(RelationshipsText); WriteSubTree(writer, value.Relationships, options); } if (value.Links != null && value.Links.HasValue()) { writer.WritePropertyName(LinksText); WriteSubTree(writer, value.Links, options); } if (!value.Meta.IsNullOrEmpty()) { writer.WritePropertyName(MetaText); WriteSubTree(writer, value.Meta, options); } writer.WriteEndObject(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// HttpSuccess operations. /// </summary> public partial interface IHttpSuccess { /// <summary> /// Return 200 status code if successful /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Head200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get 200 success /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<bool?>> Get200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put boolean value true returning 200 success /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Put200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Patch true Boolean value in request returning 200 /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Patch200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Post bollean value true in request that returns a 200 /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Post200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete simple boolean value true returns 200 /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Delete200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put true Boolean value in request returns 201 /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Put201WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Post true Boolean value in request returns 201 (Created) /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Post201WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put true Boolean value in request returns 202 (Accepted) /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Put202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Patch true Boolean value in request returns 202 /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Patch202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Post true Boolean value in request returns 202 (Accepted) /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Post202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete true Boolean value in request returns 202 (accepted) /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Delete202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 204 status code if successful /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Head204WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put true Boolean value in request returns 204 (no content) /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Put204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Patch true Boolean value in request returns 204 (no content) /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Patch204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Post true Boolean value in request returns 204 (no content) /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Post204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete true Boolean value in request returns 204 (no content) /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Delete204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 404 status code /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Head404WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.IO; using System.Linq; using System.Drawing; using System.Threading; using System.Diagnostics; using System.Threading.Tasks; using System.Collections.Generic; using System.Runtime.InteropServices; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; using Monodoc; using System.Text; namespace macdoc { public partial class AppDelegate : NSApplicationDelegate { static public RootTree Root; static public string MonodocDir; static public NSUrl MonodocBaseUrl; static MonodocDocumentController controller; static bool isOnLion = false; bool shouldOpenInitialFile = true; static void PrepareCache () { MonodocDir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "Library/Caches/MacDoc/"); var mdocimages = Path.Combine (MonodocDir, "mdocimages"); MonodocBaseUrl = new NSUrl (MonodocDir); if (!Directory.Exists (mdocimages)){ try { Directory.CreateDirectory (mdocimages); } catch {} } } static void ExtractImages () { var mdocAssembly = typeof (Node).Assembly; foreach (var res in mdocAssembly.GetManifestResourceNames ()){ if (!res.EndsWith (".png") || res.EndsWith (".jpg")) continue; var image = Path.Combine (MonodocDir, "mdocimages", res); if (File.Exists (image)) continue; try { using (var output = File.Create (image)) mdocAssembly.GetManifestResourceStream (res).CopyTo (output); } catch (UnauthorizedAccessException) {} } } public AppDelegate () { PrepareCache (); ExtractImages (); controller = new MonodocDocumentController (); // Some UI feature we use rely on Lion or better, so special case it try { var version = new NSDictionary ("/System/Library/CoreServices/SystemVersion.plist"); var osxVersion = Version.Parse (version.ObjectForKey (new NSString ("ProductVersion")).ToString ()); isOnLion = osxVersion.Major == 10 && osxVersion.Minor >= 7; } catch {} // Load documentation var args = Environment.GetCommandLineArgs (); IEnumerable<string> extraDocs = null, extraUncompiledDocs = null; if (args != null && args.Length > 1) { var extraDirs = args.Skip (1); extraDocs = extraDirs .Where (d => d.StartsWith ("+")) .Select (d => d.Substring (1)) .Where (d => Directory.Exists (d)); extraUncompiledDocs = extraDirs .Where (d => d.StartsWith ("@")) .Select (d => d.Substring (1)) .Where (d => Directory.Exists (d)); } if (extraUncompiledDocs != null) foreach (var dir in extraUncompiledDocs) RootTree.AddUncompiledSource (dir); Root = RootTree.LoadTree (); if (extraDocs != null) foreach (var dir in extraDocs) Root.AddSource (dir); var macDocPath = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "macdoc"); if (!Directory.Exists (macDocPath)) Directory.CreateDirectory (macDocPath); var helpSources = Root.HelpSources .Cast<HelpSource> () .Where (hs => !string.IsNullOrEmpty (hs.BaseFilePath) && !string.IsNullOrEmpty (hs.Name)) .Select (hs => Path.Combine (hs.BaseFilePath, hs.Name + ".zip")) .Where (File.Exists); IndexUpdateManager = new IndexUpdateManager (helpSources, macDocPath); BookmarkManager = new BookmarkManager (macDocPath); } int Run (string command) { var psi = new System.Diagnostics.ProcessStartInfo (command, " --need-update"); var t = ProcessUtils.StartProcess (psi, null, null, CancellationToken.None); t.Wait (); try { return t.Result; } catch { return 1; } } public override void FinishedLaunching (NSObject notification) { // Check if we are loaded with a search term and load a document for it var args = Environment.GetCommandLineArgs (); NSError error; var searchArgIdx = Array.IndexOf<string> (args, "--search"); if (searchArgIdx != -1 && args.Length > searchArgIdx + 1 && !string.IsNullOrEmpty (args [searchArgIdx + 1])) { var document = controller.OpenUntitledDocument (true, out error); if (document != null) ((MyDocument)document).LoadWithSearch (args[searchArgIdx + 1]); } var indexManager = IndexUpdateManager; indexManager.CheckIndexIsFresh ().ContinueWith (t => { if (t.IsFaulted) Logger.LogError ("Error while checking indexes", t.Exception); else if (!t.Result) indexManager.PerformSearchIndexCreation (); else indexManager.AdvertiseFreshIndex (); }).ContinueWith (t => Logger.LogError ("Error while creating indexes", t.Exception), TaskContinuationOptions.OnlyOnFaulted); // Check if there is a MonoTouch/MonoMac documentation installed and launch accordingly var products = Root.HelpSources.Where (hs => hs != null && hs.Name != null).ToProducts ().Distinct ().ToArray (); var message = new StringBuilder ("We have detected that your documentation for the following products can be improved by merging the Apple documentation:\n"); var toUpdate = new List<Product> (); foreach (var p in products) { bool needUpdate = false; var tool = ProductUtils.GetMergeToolForProduct (p); if (!File.Exists (tool)) continue; if (Run (tool) == 0) { toUpdate.Add (p); message.AppendFormat ("{0}\n", ProductUtils.GetFriendlyName (p)); } } if (toUpdate.Count > 0) LaunchDocumentationUpdate (toUpdate.ToArray (), message.ToString ()); } public static IndexUpdateManager IndexUpdateManager { get; private set; } public static BookmarkManager BookmarkManager { get; private set; } public static bool IsOnLionOrBetter { get { return isOnLion; } } public static bool RestartRequested { get; set; } public override void WillFinishLaunching (NSNotification notification) { var selector = new MonoMac.ObjCRuntime.Selector ("handleGetURLEvent:withReplyEvent:"); NSAppleEventManager.SharedAppleEventManager.SetEventHandler (this, selector, AEEventClass.Internet, AEEventID.GetUrl); } [Export ("handleGetURLEvent:withReplyEvent:")] public void HandleGetURLEvent (NSAppleEventDescriptor evt, NSAppleEventDescriptor replyEvt) { NSError error; shouldOpenInitialFile = evt.NumberOfItems == 0; // Received event is a list (1-based) of URL strings for (int i = 1; i <= evt.NumberOfItems; i++) { var innerDesc = evt.DescriptorAtIndex (i); // The next call works fine but is Lion-specific // controller.OpenDocument (new NSUrl (innerDesc.StringValue), i == evt.NumberOfItems, delegate {}); if (!string.IsNullOrEmpty (innerDesc.StringValue)) { NSUrl url = new NSUrl (innerDesc.StringValue); Call_OpenDocument (url, true, out error); } } } // If the application was launched with an url, we don't open a default window public override bool ApplicationShouldOpenUntitledFile (NSApplication sender) { return shouldOpenInitialFile; } // Prevent new document from being created when already launched public override bool ApplicationShouldHandleReopen (NSApplication sender, bool hasVisibleWindows) { return !hasVisibleWindows; } partial void HandlePrint (NSObject sender) { controller.CurrentDocument.PrintDocument (sender); } partial void HandleFind (NSMenuItem sender) { controller.CurrentMyDocument.MainWebView.PerformFindPanelAction (sender); } partial void HandleSearch (NSObject sender) { var searchField = controller.CurrentMyDocument.WindowForSheet.Toolbar.VisibleItems.Last ().View; controller.CurrentDocument.WindowForSheet.MakeFirstResponder (searchField); } public override void WillTerminate (NSNotification notification) { BookmarkManager.SaveBookmarks (); // Relaunch ourselves if it was requested if (RestartRequested) NSWorkspace.SharedWorkspace.LaunchApp (NSBundle.MainBundle.BundleIdentifier, NSWorkspaceLaunchOptions.NewInstance | NSWorkspaceLaunchOptions.Async, NSAppleEventDescriptor.NullDescriptor, IntPtr.Zero); } void LaunchDocumentationUpdate (Product [] products, string informative) { var infoDialog = new NSAlert { AlertStyle = NSAlertStyle.Informational, MessageText = "Documentation update available", InformativeText = informative + "\n\nWarning: If you have not downloaded the documentation with Xcode, this program will download the documentation from Apple servers which can take a long time.\n\nWould you like to update the documentation now?" }; infoDialog.AddButton ("Update now"); infoDialog.AddButton ("Remind me later"); var dialogResult = infoDialog.RunModal (); // If Cancel was clicked, just return if (dialogResult == (int)NSAlertButtonReturn.Second) return; var mergerTasks = products.Select (p => Task.Factory.StartNew (() => { var mergeToolPath = ProductUtils.GetMergeToolForProduct (p); var psi = new System.Diagnostics.ProcessStartInfo (mergeToolPath, null); return ProcessUtils.StartProcess (psi, null, null, CancellationToken.None); }).Unwrap ()); // No Task.WhenAll yet var tcs = new TaskCompletionSource<int> (); Task.Factory.ContinueWhenAll (mergerTasks.ToArray (), ts => { var faulteds = ts.Where (t => t.IsFaulted); if (faulteds.Any ()) tcs.SetException (faulteds.Select (t => t.Exception)); else tcs.SetResult (ts.Select (t => t.Result).FirstOrDefault (r => r != 0)); }); var mergeController = new AppleDocMergeWindowController (); mergeController.TrackProcessTask (tcs.Task); mergeController.ShowWindow (this); mergeController.Window.Center (); } // We use a working OpenDocument method that doesn't return anything because of MonoMac bug#3380 public void Call_OpenDocument (NSUrl absoluteUrl, bool displayDocument, out NSError outError) { outError = null; if (absoluteUrl == null) throw new ArgumentNullException ("absoluteUrl"); IntPtr outErrorPtr = Marshal.AllocHGlobal(4); Marshal.WriteInt32(outErrorPtr, 0); MonoMac.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr_bool_IntPtr (controller.Handle, selOpenDocumentWithContentsOfURLDisplayError_, absoluteUrl.Handle, displayDocument, outErrorPtr); } IntPtr selOpenDocumentWithContentsOfURLDisplayError_ = new Selector ("openDocumentWithContentsOfURL:display:error:").Handle; } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using log4net; using OpenSim.Data; using OpenMetaverse; using OpenSim.Framework; namespace Halcyon.Data.Inventory.MySQL { /// <summary> /// IInventorystorage adapter to the old mysql inventory system /// </summary> public class MySqlInventoryStorage : IInventoryStorage { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private MysqlStorageImpl _impl; public MySqlInventoryStorage(string connStr) { _impl = new MysqlStorageImpl(connStr); } public List<InventoryFolderBase> GetInventorySkeleton(UUID userId) { List<InventoryFolderBase> retFolders = new List<InventoryFolderBase>(); InventoryFolderBase rootFolder = _impl.getUserRootFolder(userId); if (rootFolder != null) { retFolders.Add(rootFolder); retFolders.AddRange(_impl.getFolderHierarchy(rootFolder.ID)); } else { // Handle a null here but throw the same exception Cassandra does. throw new InventoryStorageException("[MySqlInventoryStorage]: Unable to retrieve folder skeleton: root folder"); } return retFolders; } public InventoryFolderBase GetFolder(UUID folderId) { InventoryFolderBase folder = _impl.getInventoryFolder(folderId); if (folder == null) { throw new InventoryObjectMissingException(String.Format("Unable to find folder {0}", folderId)); } //now we need the descendents List<InventoryItemBase> items = _impl.getInventoryInFolder(folderId); List<InventoryFolderBase> folders = _impl.getInventoryFolders(folderId); folder.Items.AddRange(items); foreach (InventoryFolderBase subFolder in folders) { InventorySubFolderBase sub= new InventorySubFolderBase { ID = subFolder.ID, Name = subFolder.Name, Owner = subFolder.Owner, Type = subFolder.Type }; folder.SubFolders.Add(sub); } return folder; } public InventoryFolderBase GetFolderAttributes(UUID folderId) { return _impl.getInventoryFolder(folderId); } public void CreateFolder(InventoryFolderBase folder) { _impl.addInventoryFolder(folder); } public void SaveFolder(InventoryFolderBase folder) { folder.Version++; _impl.updateInventoryFolder(folder); } public void MoveFolder(InventoryFolderBase folder, UUID parentId) { // Don't do anything with a folder that wants to set its new parent to the same folder as its current parent. if (folder.ParentID == parentId) { m_log.WarnFormat("[Inventory]: Refusing to move folder {0} to new parent {1} for {2}. The source and destination are the same", folder.ID, parentId, folder.Owner); return; } // Don't do anything with a folder that wants to set its new parent to UUID.Zero if (parentId == UUID.Zero) { m_log.WarnFormat("[Inventory]: Refusing to move folder {0} to new parent {1} for {2}. New parent has ID UUID.Zero", folder.ID, parentId, folder.Owner); return; } _impl.moveInventoryFolder(folder, parentId); } public UUID SendFolderToTrash(InventoryFolderBase folder, UUID trashFolderHint) { InventoryFolderBase trashFolder = _impl.findUserFolderForType(folder.Owner, (int)FolderType.Trash); this.MoveFolder(folder, trashFolder.ID); return trashFolder.ID; } public InventoryFolderBase FindFolderForType(UUID owner, AssetType type) { InventoryFolderBase folder = _impl.findUserFolderForType(owner, (int)type); if (folder != null) { return folder; } else if (type == (AssetType)FolderType.Root) { //this is a special case for the legacy inventory services. //the root folder type asset type may have been incorrectly saved //as the old AssetType.RootFolder (which is 9), //rather than AssetType.Folder (which is 8) with FolderType.Root (which is also 8). folder = _impl.findUserFolderForType(owner, (int)FolderType.OldRoot); if (folder == null) { //this is another special case for the legacy inventory services. //the root folder type may be incorrectly set to folder instead of RootFolder //we must find it a different way in this case return _impl.getUserRootFolder(owner); } } return null; } // Cassandra version searches the parentage tree for an ancestor folder with a matching type (e.g. Trash) public InventoryFolderBase FindTopLevelFolderFor(UUID owner, UUID folderID) { return _impl.findUserTopLevelFolderFor(owner, folderID); } public void PurgeFolderContents(InventoryFolderBase folder) { _impl.deleteFolderContents(folder.ID); } public void PurgeFolder(InventoryFolderBase folder) { _impl.deleteInventoryFolder(folder); } public void PurgeEmptyFolder(InventoryFolderBase folder) { PurgeFolder(folder); // no optimization for this in the legacy implementation } public void PurgeFolders(IEnumerable<InventoryFolderBase> folders) { foreach (InventoryFolderBase folder in folders) { _impl.deleteInventoryFolder(folder); } } public InventoryItemBase GetItem(UUID itemId, UUID parentFolderHint) { return _impl.getInventoryItem(itemId); } public List<InventoryItemBase> GetItems(IEnumerable<UUID> itemIds, bool throwOnNotFound) { m_log.ErrorFormat("[Inventory]: GetItems NOT IMPLEMENTED"); throw new NotImplementedException(); } public void CreateItem(InventoryItemBase item) { // TODO: Maybe. Cassandra does a CheckAndFixItemParentFolder(item) here. Not sure if that should be replicated here too... ~Ricky 20151007 _impl.addInventoryItem(item); } public void SaveItem(InventoryItemBase item) { // TODO: Maybe. Cassandra does a CheckAndFixItemParentFolder(item) here. Not sure if that should be replicated here too... ~Ricky 20151007 _impl.updateInventoryItem(item); } public void MoveItem(InventoryItemBase item, InventoryFolderBase parentFolder) { item.Folder = parentFolder.ID; _impl.updateInventoryItem(item); } public UUID SendItemToTrash(InventoryItemBase item, UUID trashFolderHint) { InventoryFolderBase trashFolder = _impl.findUserFolderForType(item.Owner, (int)FolderType.Trash); this.MoveItem(item, trashFolder); return trashFolder.ID; } public void PurgeItem(InventoryItemBase item) { _impl.deleteInventoryItem(item); } public void PurgeItems(IEnumerable<InventoryItemBase> items) { foreach (InventoryItemBase item in items) { _impl.deleteInventoryItem(item); } } public void ActivateGestures(UUID userId, IEnumerable<UUID> itemIds) { foreach (UUID id in itemIds) { InventoryItemBase item = _impl.getInventoryItem(id); if (item != null) { item.Flags |= (uint)1; _impl.updateInventoryItem(item); } } } public void DeactivateGestures(UUID userId, IEnumerable<UUID> itemIds) { foreach (UUID id in itemIds) { InventoryItemBase item = _impl.getInventoryItem(id); if (item != null) { item.Flags &= ~(uint)1; _impl.updateInventoryItem(item); } } } public List<InventoryItemBase> GetActiveGestureItems(UUID userId) { return _impl.fetchActiveGestures(userId); } } }
#region Namespaces using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; #endregion namespace ArdanStudios.Common.Utilities { #region Class - SocketClient /// <summary> This class abstract a socket </summary> public class SocketClient : IDisposable { #region Delegate Function Types /// <summary> Called when a message is extracted from the socket </summary> public delegate void MESSAGE_HANDLER(SocketClient socket); /// <summary> Called when a socket connection is closed </summary> public delegate void CLOSE_HANDLER(SocketClient socket); /// <summary> Called when a socket error occurs </summary> public delegate void ERROR_HANDLER(SocketClient socket, Exception exception); #endregion #region Static Properties /// <summary> Maintain the next unique key </summary> private static long NextUniqueKey = 0; #endregion #region Private Properties /// <summary> Flag when disposed is called </summary> private bool Disposed = false; /// <summary> The SocketServer for this socket object </summary> private SocketServer SocketServer = null; /// <summary> The socket for the accepted client connection </summary> private Socket ClientSocket = null; /// <summary> A TcpClient object for client established connections </summary> private TcpClient TcpClient = null; /// <summary> A network stream object </summary> private NetworkStream NetworkStream = null; /// <summary> RetType: A callback object for processing recieved socket data </summary> private AsyncCallback CallbackReadFunction = null; /// <summary> RetType: A callback object for processing send socket data </summary> private AsyncCallback CallbackWriteFunction = null; /// <summary> A reference to a user supplied function to be called when a socket message arrives </summary> private MESSAGE_HANDLER MessageHandler = null; /// <summary> A reference to a user supplied function to be called when a socket connection is closed </summary> private CLOSE_HANDLER CloseHandler = null; /// <summary> A reference to a user supplied function to be called when a socket error occurs </summary> private ERROR_HANDLER ErrorHandler = null; #endregion #region Public Properties /// <summary> The IpAddress of the connection </summary> public string IpAddress = null; /// <summary> The Port of the connection </summary>summary> public int Port = int.MinValue; /// <summary> The index position in the server dictionary of socket connections </summary> public int SocketIndex = -1; /// <summary> A raw buffer to capture data comming off the socket </summary> public byte[] RawBuffer = null; /// <summary> Size of the raw buffer for received socket data </summary> public int SizeOfRawBuffer = 0; /// <summary> The length of the message </summary> public int MessageLength = 0; /// <summary> A unique key for the socket object </summary> public long UniqueKey = 0; /// <summary> A flag to determine if the Socket Client is connected </summary> public bool IsConnected { get { return (ClientSocket != null) ? ClientSocket.Connected : (TcpClient != null) ? TcpClient.Connected : false; } } #endregion #region User Defined Public Properties /// <summary> A string buffer to be used by the application developer </summary> public StringBuilder StringBuffer = null; /// <summary> A memory stream buffer to be used by the application developer </summary> public MemoryStream MessageBuffer = null; /// <summary> A byte buffer to be used by the application developer </summary> public byte[] ByteBuffer = null; /// <summary> A list buffer to be used by the application developer </summary> public List<byte> ListBuffer = null; /// <summary> The number of bytes that have been buffered </summary> public int BufferedBytes = 0; /// <summary> A reference to a user defined object to be passed through the handler functions </summary> public object UserArg = null; /// <summary> UserDefined flag to indicate if the socket object is available for use </summary> public bool IsAvailable = false; #endregion #region Constructor /// <summary> Constructor for client support </summary> /// <param name="sizeOfRawBuffer"> The size of the raw buffer </param> /// <param name="sizeOfByteBuffer"> The size of the byte buffer </param> /// <param name="userArg"> A Reference to the Users arguments </param> /// <param name="messageHandler"> Reference to the user defined message handler function </param> /// <param name="closeHandler"> Reference to the user defined close handler function </param> /// <param name="errorHandler"> Reference to the user defined error handler function </param> public SocketClient(int sizeOfRawBuffer, int sizeOfByteBuffer, object userArg, MESSAGE_HANDLER messageHandler, CLOSE_HANDLER closeHandler, ERROR_HANDLER errorHandler) { // Create the raw buffer SizeOfRawBuffer = sizeOfRawBuffer; RawBuffer = new byte[SizeOfRawBuffer]; // Save the user argument UserArg = userArg; // Allocate a String Builder class for Application developer use StringBuffer = new StringBuilder(); // Allocate a Memory Stream class for Application developer use MessageBuffer = new MemoryStream(); // Allocate a byte buffer for Application developer use ByteBuffer = new byte[sizeOfByteBuffer]; BufferedBytes = 0; // Allocate a list buffer for Application developer use ListBuffer = new List<byte>(); // Set the handler functions MessageHandler = messageHandler; CloseHandler = closeHandler; ErrorHandler = errorHandler; // Set the async socket function handlers CallbackReadFunction = new AsyncCallback(ReceiveComplete); CallbackWriteFunction = new AsyncCallback(SendComplete); // Set available flags IsAvailable = true; // Set the unique key for this object UniqueKey = NewUniqueKey(); } /// <summary> Constructor for SocketServer Suppport </summary> /// <param name="socketServer"> A Reference to the parent SocketServer </param> /// <param name="clientSocket"> The Socket object we are encapsulating </param> /// <param name="ipAddress"> The IpAddress of the remote server </param> /// <param name="port"> The Port of the remote server </param> /// <param name="sizeOfRawBuffer"> The size of the raw buffer </param> /// <param name="sizeOfByteBuffer"> The size of the byte buffer </param> /// <param name="userArg"> A Reference to the Users arguments </param> /// <param name="messageHandler"> Reference to the user defined message handler function </param> /// <param name="closeHandler"> Reference to the user defined close handler function </param> /// <param name="errorHandler"> Reference to the user defined error handler function </param> public SocketClient(SocketServer socketServer, Socket clientSocket, string ipAddress, int port, int sizeOfRawBuffer, int sizeOfByteBuffer, object userArg, MESSAGE_HANDLER messageHandler, CLOSE_HANDLER closeHandler, ERROR_HANDLER errorHandler) { // Set reference to SocketServer SocketServer = socketServer; // Set when this socket came from a SocketServer Accept ClientSocket = clientSocket; // Set the Ipaddress and Port IpAddress = ipAddress; Port = port; // Set the server index SocketIndex = clientSocket.Handle.ToInt32(); // Set the handler functions MessageHandler = messageHandler; CloseHandler = closeHandler; ErrorHandler = errorHandler; // Create the raw buffer SizeOfRawBuffer = sizeOfRawBuffer; RawBuffer = new byte[SizeOfRawBuffer]; // Save the user argument UserArg = userArg; // Allocate a String Builder class for Application developer use StringBuffer = new StringBuilder(); // Allocate a Memory Stream class for Application developer use MessageBuffer = new MemoryStream(); // Allocate a byte buffer for Application developer use ByteBuffer = new byte[sizeOfByteBuffer]; BufferedBytes = 0; // Allocate a list buffer for Application developer use ListBuffer = new List<byte>(); // Init the NetworkStream reference NetworkStream = new NetworkStream(ClientSocket); // Set the async socket function handlers CallbackReadFunction = new AsyncCallback(ReceiveComplete); CallbackWriteFunction = new AsyncCallback(SendComplete); // Set Available flags IsAvailable = true; // Set the unique key for this object UniqueKey = NewUniqueKey(); // Set these socket options ClientSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReceiveBuffer, sizeOfRawBuffer); ClientSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.SendBuffer, sizeOfRawBuffer); ClientSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.KeepAlive, 1); ClientSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.DontLinger, 1); ClientSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Tcp, System.Net.Sockets.SocketOptionName.NoDelay, 1); } /// <summary> Dispose </summary> public void Dispose() { try { Dispose(true); GC.SuppressFinalize(this); } catch { } } /// <summary> Dispose the server </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!Disposed) { // Note disposing has been done. Disposed = true; // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { try { Disconnect(); } catch { } } } } #endregion #region Private Methods /// <summary> Called when a message arrives </summary> /// <param name="ar"> An async result interface </param> private void ReceiveComplete(IAsyncResult ar) { try { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "NetThreadPool"; } // Is the Network Stream object valid if ((NetworkStream != null) && (NetworkStream.CanRead)) { // Read the current bytes from the stream buffer MessageLength = NetworkStream.EndRead(ar); // If there are bytes to process else the connection is lost if (MessageLength > 0) { try { // A message came in send it to the MessageHandler MessageHandler(this); } catch { } // Wait for a new message Receive(); } else { if (NetworkStream != null) { Disconnect(); } // Call the close handler CloseHandler(this); } } else { if (NetworkStream != null) { Disconnect(); } // Call the close handler CloseHandler(this); } } catch (Exception exception) { if (NetworkStream != null) { Disconnect(); if ((!exception.Message.Contains("forcibly closed")) && (!exception.Message.Contains("thread exit"))) { ErrorHandler(this, exception); } } // Call the close handler CloseHandler(this); } ar.AsyncWaitHandle.Close(); } /// <summary> Called when a message is sent </summary> /// <param name="ar"> An async result interface </param> private void SendComplete(IAsyncResult ar) { try { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "NetThreadPool"; } // Is the Network Stream object valid if ((NetworkStream != null) && (NetworkStream.CanWrite)) { NetworkStream.EndWrite(ar); } } catch { } ar.AsyncWaitHandle.Close(); } #endregion #region Public Methods /// <summary> Called to generate a unique key </summary> /// <returns> long </returns> public static long NewUniqueKey() { // Set the unique key for this object return Interlocked.Increment(ref SocketClient.NextUniqueKey); } /// <summary> Function used to connect to a server </summary> /// <param name="ipAddress"> The address to connect to </param> /// <param name="port"> The Port to connect to </param> public void Connect(string ipAddress, int port) { // If this object was disposed and they are trying to re-connect clear the flag if (Disposed == true) { throw new Exception("ClientSocket Has Been Disposed"); } if (NetworkStream == null) { // Set the Ipaddress and Port IpAddress = ipAddress; Port = port; try { IPAddress useIpAddress = null; IPHostEntry hostEntries = Dns.GetHostEntry(IpAddress); foreach (IPAddress address in hostEntries.AddressList) { // Find the IPv4 address first if (address.AddressFamily == AddressFamily.InterNetwork) { useIpAddress = address; break; } } // Now just use the first address if (useIpAddress == null) { useIpAddress = hostEntries.AddressList[0]; } IpAddress = useIpAddress.ToString(); } catch { IpAddress = ipAddress; } // Attempt to establish a connection TcpClient = new TcpClient(IpAddress, Port); NetworkStream = TcpClient.GetStream(); // Set these socket options TcpClient.ReceiveBufferSize = SizeOfRawBuffer; TcpClient.SendBufferSize = SizeOfRawBuffer; TcpClient.NoDelay = true; TcpClient.LingerState = new System.Net.Sockets.LingerOption(false, 0); // Start to receive messages Receive(); } } /// <summary> Called to disconnect the client </summary> public void Disconnect() { try { // Remove the socket from the list if (SocketServer != null) { SocketServer.RemoveSocket(this); } // Set when this socket came from a SocketServer Accept if (ClientSocket != null) { ClientSocket.Close(); } // Set when this socket came from a SocketClient Connect if (TcpClient != null) { TcpClient.Close(); } // Set it both cases if (NetworkStream != null) { NetworkStream.Close(); } // Clean up the connection state ClientSocket = null; TcpClient = null; NetworkStream = null; } catch (Exception exception) { ErrorHandler(this, exception); } } /// <summary> Function to send a string to the server </summary> /// <param name="message"> A string to send </param> public void Send(string message) { try { if ((NetworkStream != null) && (NetworkStream.CanWrite)) { // Convert the string into a Raw Buffer byte[] pRawBuffer = System.Text.Encoding.ASCII.GetBytes(message); // Issue an asynchronus write NetworkStream.BeginWrite(pRawBuffer, 0, pRawBuffer.Length, CallbackWriteFunction, null); } else { throw new Exception("No Connection"); } } catch { Disconnect(); throw; } } /// <summary> Function to send a raw buffer to the server </summary> /// <param name="rawBuffer"> A Raw buffer of bytes to send </param> public void Send(byte[] rawBuffer) { try { if ((NetworkStream != null) && (NetworkStream.CanWrite)) { // Issue an asynchronus write NetworkStream.BeginWrite(rawBuffer, 0, rawBuffer.Length, CallbackWriteFunction, null); } else { throw new Exception("No Connection"); } } catch { Disconnect(); throw; } } /// <summary> Function to send a char to the server </summary> /// <param name="charValue"> A Raw char to send </param> public void Send(char charValue) { try { if ((NetworkStream != null) && (NetworkStream.CanWrite)) { // Convert the character to a byte byte[] pRawBuffer = { Convert.ToByte(charValue) }; // Issue an asynchronus write NetworkStream.BeginWrite(pRawBuffer, 0, pRawBuffer.Length, CallbackWriteFunction, null); } else { throw new Exception("No Connection"); } } catch { Disconnect(); throw; } } /// <summary> Wait for a message to arrive </summary> public void Receive() { if ((NetworkStream != null) && (NetworkStream.CanRead)) { // Issue an asynchronous read NetworkStream.BeginRead(RawBuffer, 0, SizeOfRawBuffer, CallbackReadFunction, null); } else { throw new Exception("Unable To Read From Stream"); } } #endregion } #endregion #region Class - SocketServer /// <summary> This class accepts multiple socket connections and handles them asychronously </summary> public class SocketServer : IDisposable { #region Delagate Function Types /// <summary> Called when a message is extracted from the socket </summary> public delegate void MESSAGE_HANDLER(SocketClient socket); /// <summary> Called when a socket connection is closed </summary> public delegate void CLOSE_HANDLER(SocketClient socket); /// <summary> Called when a socket error occurs </summary> public delegate void ERROR_HANDLER(SocketClient socket, Exception exception); /// <summary> Called when a socket connection is accepted </summary> public delegate void ACCEPT_HANDLER(SocketClient socket); #endregion #region Private Properties /// <summary> Flag when disposed is called </summary> private bool Disposed = false; /// <summary> A TcpListener object to accept socket connections </summary> private TcpListener TcpListener = null; /// <summary> Size of the raw buffer for received socket data </summary> private int SizeOfRawBuffer = 0; /// <summary> Size of the raw buffer for user purpose </summary> private int SizeOfByteBuffer = 0; /// <summary> RetType: A thread to process accepting socket connections </summary> private Thread AcceptThread = null; /// <summary> A reference to a user supplied function to be called when a socket message arrives </summary> private MESSAGE_HANDLER MessageHandler = null; /// <summary> A reference to a user supplied function to be called when a socket connection is closed </summary> private CLOSE_HANDLER CloseHandler = null; /// <summary> A reference to a user supplied function to be called when a socket error occurs </summary> private ERROR_HANDLER ErrorHandler = null; /// <summary> A reference to a user supplied function to be called when a socket connection is accepted </summary> private ACCEPT_HANDLER AcceptHandler = null; /// <summary> RefTypeArray: An Array of SocketClient objects </summary> private List<SocketClient> SocketClientList = new List<SocketClient>(); #endregion #region Public Properties /// <summary> The IpAddress to either connect to or listen on </summary> public string IpAddress = null; /// <summary> The Port to either connect to or listen on </summary> public int Port = int.MinValue; /// <summary> A reference to a user defined object to be passed through the handler functions </summary> public object UserArg = null; #endregion #region Constructor /// <summary> Constructor </summary> public SocketServer() { } /// <summary> Dispose function to shutdown the SocketManager </summary> public void Dispose() { try { Dispose(true); GC.SuppressFinalize(this); } catch { } } /// <summary> Dispose the server </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!Disposed) { // Note disposing has been done. Disposed = true; // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { // Stop the server if the thread is running if (AcceptThread != null) { Stop(); } } } } #endregion #region Private Methods /// <summary> Function to process and accept socket connection requests </summary> private void AcceptConnections() { Socket socket = null; try { IPAddress useIpAddress = null; IPHostEntry hostEntries = Dns.GetHostEntry(IpAddress); foreach (IPAddress address in hostEntries.AddressList) { // Find the IPv4 address first if (address.AddressFamily == AddressFamily.InterNetwork) { useIpAddress = address; break; } } // Now just use the first address if (useIpAddress == null) { useIpAddress = hostEntries.AddressList[0]; } IpAddress = useIpAddress.ToString(); // Create a new TCPListner and start it up TcpListener = new TcpListener(useIpAddress, Port); TcpListener.Start(); for (;;) { try { // If a client connects, accept the connection. socket = TcpListener.AcceptSocket(); } catch (System.Net.Sockets.SocketException e) { // Did we stop the TCPListener if (e.ErrorCode != 10004) { // Call the error handler ErrorHandler(null, e); ErrorHandler(null, new Exception("Waiting for new connection 1")); // Close the socket down if it exists if (socket != null) { if (socket.Connected) { socket.Dispose(); } } } else { ErrorHandler(null, new Exception("Shutting Down Accept Thread")); break; } } catch (Exception e) { // Call the error handler ErrorHandler(null, e); ErrorHandler(null, new Exception("Waiting for new connection 2")); // Close the socket down if it exists if (socket != null) { if (socket.Connected) { socket.Dispose(); } } } try { if (socket.Connected) { string remoteEndPoint = socket.RemoteEndPoint.ToString(); // Create a SocketClient object SocketClient clientSocket = new SocketClient(this, socket, (remoteEndPoint.Length < 15) ? string.Empty : remoteEndPoint.Substring(0, 15), Port, SizeOfRawBuffer, SizeOfByteBuffer, UserArg, new SocketClient.MESSAGE_HANDLER(MessageHandler), new SocketClient.CLOSE_HANDLER(CloseHandler), new SocketClient.ERROR_HANDLER(ErrorHandler)); // Add it to the list lock (SocketClientList) { SocketClientList.Add(clientSocket); } // Call the Accept Handler AcceptHandler(clientSocket); // Wait for a message clientSocket.Receive(); } } catch (Exception e) { // Call the error handler ErrorHandler(null, e); ErrorHandler(null, new Exception("Waiting for new connection 3")); } } } catch (Exception e) { // Call the error handler ErrorHandler(null, e); ErrorHandler(null, new Exception("Shutting Down Accept Thread")); // Close the socket down if it exists if (socket != null) { if (socket.Connected) { socket.Dispose(); } } } } #endregion #region Public Methods /// <summary> Function to start the SocketServer </summary> /// <param name="ipAddress"> The IpAddress to listening on </param> /// <param name="port"> The Port to listen on </param> /// <param name="sizeOfRawBuffer"> Size of the Raw Buffer </param> /// <param name="sizeOfByteBuffer"> Size of the byte buffer </param> /// <param name="userArg"> User supplied arguments </param> /// <param name="messageHandler"> Function pointer to the user MessageHandler function </param> /// <param name="acceptHandler"> Function pointer to the user AcceptHandler function </param> /// <param name="closeHandler"> Function pointer to the user CloseHandler function </param> /// <param name="errorHandler"> Function pointer to the user ErrorHandler function </param> public void Start(string ipAddress, int port, int sizeOfRawBuffer, int sizeOfByteBuffer, object userArg, MESSAGE_HANDLER messageHandler, ACCEPT_HANDLER acceptHandler, CLOSE_HANDLER closeHandler, ERROR_HANDLER errorHandler) { // Is an AcceptThread currently running if (AcceptThread == null) { // Set connection values IpAddress = ipAddress; Port = port; // Save the Handler Functions MessageHandler = messageHandler; AcceptHandler = acceptHandler; CloseHandler = closeHandler; ErrorHandler = errorHandler; // Save the buffer size and user arguments SizeOfRawBuffer = sizeOfRawBuffer; SizeOfByteBuffer = sizeOfByteBuffer; UserArg = userArg; // Start the listening thread if one is currently not running ThreadStart tsThread = new ThreadStart(AcceptConnections); AcceptThread = new Thread(tsThread); AcceptThread.Name = string.Format("SocketAccept-{0}", ipAddress); AcceptThread.Start(); } } /// <summary> Function to stop the SocketServer. It can be restarted with Start </summary> public void Stop() { // Abort the accept thread if (AcceptThread != null) { TcpListener.Stop(); AcceptThread.Join(); AcceptThread = null; } lock (SocketClientList) { // Dispose of all of the socket connections foreach (SocketClient socketClient in SocketClientList) { socketClient.Dispose(); } } // Wait for all of the socket client objects to be destroyed GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); // Empty the Socket Client List SocketClientList.Clear(); // Clear the Handler Functions MessageHandler = null; AcceptHandler = null; CloseHandler = null; ErrorHandler = null; // Clear the buffer size and user arguments SizeOfRawBuffer = 0; UserArg = null; } /// <summary> Funciton to remove a socket from the list of sockets </summary> /// <param name="socketClient"> A reference to a socket to remove </param> public void RemoveSocket(SocketClient socketClient) { try { lock (SocketClientList) { // Remove ths client socket object from the list SocketClientList.Remove(socketClient); } } catch (Exception exception) { ErrorHandler(socketClient, exception); } } /// <summary> Called to retrieve the socket object by the Socket Index </summary> /// <param name="socketIndex"></param> public SocketClient RetrieveSocket(Int32 socketIndex) { SocketClient socketClient = null; try { lock (SocketClientList) { // If the server index exists, return it socketClient = SocketClientList.FirstOrDefault(k => k.SocketIndex == socketIndex); } } catch (Exception) { } return socketClient; } /// <summary> Called to send a message to call socket clients </summary> /// <param name="rawBuffer"></param> public void SendAll(Byte[] rawBuffer) { lock (SocketClientList) { // If the server index exists, return it foreach (SocketClient socketClient in SocketClientList) { socketClient.Send(rawBuffer); } } } /// <summary> Called to send a message to call socket clients </summary> /// <param name="message"></param> public void SendAll(string message) { lock (SocketClientList) { // If the server index exists, return it foreach (SocketClient socketClient in SocketClientList) { socketClient.Send(message); } } } #endregion } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System; #if NETCOREAPP using System.Buffers; #endif using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using Microsoft.Extensions.WebEncoders.Sources; #if WebEncoders_In_WebUtilities namespace Microsoft.AspNetCore.WebUtilities #else namespace Microsoft.Extensions.Internal #endif { /// <summary> /// Contains utility APIs to assist with common encoding and decoding operations. /// </summary> #if WebEncoders_In_WebUtilities public #else internal #endif static class WebEncoders { /// <summary> /// Decodes a base64url-encoded string. /// </summary> /// <param name="input">The base64url-encoded input to decode.</param> /// <returns>The base64url-decoded form of the input.</returns> /// <remarks> /// The input must not contain any whitespace or padding characters. /// Throws <see cref="FormatException"/> if the input is malformed. /// </remarks> public static byte[] Base64UrlDecode(string input) { if (input == null) { throw new ArgumentNullException(nameof(input)); } return Base64UrlDecode(input, offset: 0, count: input.Length); } /// <summary> /// Decodes a base64url-encoded substring of a given string. /// </summary> /// <param name="input">A string containing the base64url-encoded input to decode.</param> /// <param name="offset">The position in <paramref name="input"/> at which decoding should begin.</param> /// <param name="count">The number of characters in <paramref name="input"/> to decode.</param> /// <returns>The base64url-decoded form of the input.</returns> /// <remarks> /// The input must not contain any whitespace or padding characters. /// Throws <see cref="FormatException"/> if the input is malformed. /// </remarks> public static byte[] Base64UrlDecode(string input, int offset, int count) { if (input == null) { throw new ArgumentNullException(nameof(input)); } ValidateParameters(input.Length, nameof(input), offset, count); // Special-case empty input if (count == 0) { return Array.Empty<byte>(); } // Create array large enough for the Base64 characters, not just shorter Base64-URL-encoded form. var buffer = new char[GetArraySizeRequiredToDecode(count)]; return Base64UrlDecode(input, offset, buffer, bufferOffset: 0, count: count); } /// <summary> /// Decodes a base64url-encoded <paramref name="input"/> into a <c>byte[]</c>. /// </summary> /// <param name="input">A string containing the base64url-encoded input to decode.</param> /// <param name="offset">The position in <paramref name="input"/> at which decoding should begin.</param> /// <param name="buffer"> /// Scratch buffer to hold the <see cref="char"/>s to decode. Array must be large enough to hold /// <paramref name="bufferOffset"/> and <paramref name="count"/> characters as well as Base64 padding /// characters. Content is not preserved. /// </param> /// <param name="bufferOffset"> /// The offset into <paramref name="buffer"/> at which to begin writing the <see cref="char"/>s to decode. /// </param> /// <param name="count">The number of characters in <paramref name="input"/> to decode.</param> /// <returns>The base64url-decoded form of the <paramref name="input"/>.</returns> /// <remarks> /// The input must not contain any whitespace or padding characters. /// Throws <see cref="FormatException"/> if the input is malformed. /// </remarks> public static byte[] Base64UrlDecode(string input, int offset, char[] buffer, int bufferOffset, int count) { if (input == null) { throw new ArgumentNullException(nameof(input)); } if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } ValidateParameters(input.Length, nameof(input), offset, count); if (bufferOffset < 0) { throw new ArgumentOutOfRangeException(nameof(bufferOffset)); } if (count == 0) { return Array.Empty<byte>(); } // Assumption: input is base64url encoded without padding and contains no whitespace. var paddingCharsToAdd = GetNumBase64PaddingCharsToAddForDecode(count); var arraySizeRequired = checked(count + paddingCharsToAdd); Debug.Assert(arraySizeRequired % 4 == 0, "Invariant: Array length must be a multiple of 4."); if (buffer.Length - bufferOffset < arraySizeRequired) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, EncoderResources.WebEncoders_InvalidCountOffsetOrLength, nameof(count), nameof(bufferOffset), nameof(input)), nameof(count)); } // Copy input into buffer, fixing up '-' -> '+' and '_' -> '/'. var i = bufferOffset; for (var j = offset; i - bufferOffset < count; i++, j++) { var ch = input[j]; if (ch == '-') { buffer[i] = '+'; } else if (ch == '_') { buffer[i] = '/'; } else { buffer[i] = ch; } } // Add the padding characters back. for (; paddingCharsToAdd > 0; i++, paddingCharsToAdd--) { buffer[i] = '='; } // Decode. // If the caller provided invalid base64 chars, they'll be caught here. return Convert.FromBase64CharArray(buffer, bufferOffset, arraySizeRequired); } /// <summary> /// Gets the minimum <c>char[]</c> size required for decoding of <paramref name="count"/> characters /// with the <see cref="Base64UrlDecode(string, int, char[], int, int)"/> method. /// </summary> /// <param name="count">The number of characters to decode.</param> /// <returns> /// The minimum <c>char[]</c> size required for decoding of <paramref name="count"/> characters. /// </returns> public static int GetArraySizeRequiredToDecode(int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count == 0) { return 0; } var numPaddingCharsToAdd = GetNumBase64PaddingCharsToAddForDecode(count); return checked(count + numPaddingCharsToAdd); } /// <summary> /// Encodes <paramref name="input"/> using base64url encoding. /// </summary> /// <param name="input">The binary input to encode.</param> /// <returns>The base64url-encoded form of <paramref name="input"/>.</returns> public static string Base64UrlEncode(byte[] input) { if (input == null) { throw new ArgumentNullException(nameof(input)); } return Base64UrlEncode(input, offset: 0, count: input.Length); } /// <summary> /// Encodes <paramref name="input"/> using base64url encoding. /// </summary> /// <param name="input">The binary input to encode.</param> /// <param name="offset">The offset into <paramref name="input"/> at which to begin encoding.</param> /// <param name="count">The number of bytes from <paramref name="input"/> to encode.</param> /// <returns>The base64url-encoded form of <paramref name="input"/>.</returns> public static string Base64UrlEncode(byte[] input, int offset, int count) { if (input == null) { throw new ArgumentNullException(nameof(input)); } ValidateParameters(input.Length, nameof(input), offset, count); #if NETCOREAPP return Base64UrlEncode(input.AsSpan(offset, count)); #else // Special-case empty input if (count == 0) { return string.Empty; } var buffer = new char[GetArraySizeRequiredToEncode(count)]; var numBase64Chars = Base64UrlEncode(input, offset, buffer, outputOffset: 0, count: count); return new string(buffer, startIndex: 0, length: numBase64Chars); #endif } /// <summary> /// Encodes <paramref name="input"/> using base64url encoding. /// </summary> /// <param name="input">The binary input to encode.</param> /// <param name="offset">The offset into <paramref name="input"/> at which to begin encoding.</param> /// <param name="output"> /// Buffer to receive the base64url-encoded form of <paramref name="input"/>. Array must be large enough to /// hold <paramref name="outputOffset"/> characters and the full base64-encoded form of /// <paramref name="input"/>, including padding characters. /// </param> /// <param name="outputOffset"> /// The offset into <paramref name="output"/> at which to begin writing the base64url-encoded form of /// <paramref name="input"/>. /// </param> /// <param name="count">The number of <c>byte</c>s from <paramref name="input"/> to encode.</param> /// <returns> /// The number of characters written to <paramref name="output"/>, less any padding characters. /// </returns> public static int Base64UrlEncode(byte[] input, int offset, char[] output, int outputOffset, int count) { if (input == null) { throw new ArgumentNullException(nameof(input)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } ValidateParameters(input.Length, nameof(input), offset, count); if (outputOffset < 0) { throw new ArgumentOutOfRangeException(nameof(outputOffset)); } var arraySizeRequired = GetArraySizeRequiredToEncode(count); if (output.Length - outputOffset < arraySizeRequired) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, EncoderResources.WebEncoders_InvalidCountOffsetOrLength, nameof(count), nameof(outputOffset), nameof(output)), nameof(count)); } #if NETCOREAPP return Base64UrlEncode(input.AsSpan(offset, count), output.AsSpan(outputOffset)); #else // Special-case empty input. if (count == 0) { return 0; } // Use base64url encoding with no padding characters. See RFC 4648, Sec. 5. // Start with default Base64 encoding. var numBase64Chars = Convert.ToBase64CharArray(input, offset, count, output, outputOffset); // Fix up '+' -> '-' and '/' -> '_'. Drop padding characters. for (var i = outputOffset; i - outputOffset < numBase64Chars; i++) { var ch = output[i]; if (ch == '+') { output[i] = '-'; } else if (ch == '/') { output[i] = '_'; } else if (ch == '=') { // We've reached a padding character; truncate the remainder. return i - outputOffset; } } return numBase64Chars; #endif } /// <summary> /// Get the minimum output <c>char[]</c> size required for encoding <paramref name="count"/> /// <see cref="byte"/>s with the <see cref="Base64UrlEncode(byte[], int, char[], int, int)"/> method. /// </summary> /// <param name="count">The number of characters to encode.</param> /// <returns> /// The minimum output <c>char[]</c> size required for encoding <paramref name="count"/> <see cref="byte"/>s. /// </returns> public static int GetArraySizeRequiredToEncode(int count) { var numWholeOrPartialInputBlocks = checked(count + 2) / 3; return checked(numWholeOrPartialInputBlocks * 4); } #if NETCOREAPP /// <summary> /// Encodes <paramref name="input"/> using base64url encoding. /// </summary> /// <param name="input">The binary input to encode.</param> /// <returns>The base64url-encoded form of <paramref name="input"/>.</returns> [SkipLocalsInit] public static string Base64UrlEncode(ReadOnlySpan<byte> input) { const int StackAllocThreshold = 128; if (input.IsEmpty) { return string.Empty; } int bufferSize = GetArraySizeRequiredToEncode(input.Length); char[]? bufferToReturnToPool = null; Span<char> buffer = bufferSize <= StackAllocThreshold ? stackalloc char[StackAllocThreshold] : bufferToReturnToPool = ArrayPool<char>.Shared.Rent(bufferSize); var numBase64Chars = Base64UrlEncode(input, buffer); var base64Url = new string(buffer.Slice(0, numBase64Chars)); if (bufferToReturnToPool != null) { ArrayPool<char>.Shared.Return(bufferToReturnToPool); } return base64Url; } private static int Base64UrlEncode(ReadOnlySpan<byte> input, Span<char> output) { Debug.Assert(output.Length >= GetArraySizeRequiredToEncode(input.Length)); if (input.IsEmpty) { return 0; } // Use base64url encoding with no padding characters. See RFC 4648, Sec. 5. Convert.TryToBase64Chars(input, output, out int charsWritten); // Fix up '+' -> '-' and '/' -> '_'. Drop padding characters. for (var i = 0; i < charsWritten; i++) { var ch = output[i]; if (ch == '+') { output[i] = '-'; } else if (ch == '/') { output[i] = '_'; } else if (ch == '=') { // We've reached a padding character; truncate the remainder. return i; } } return charsWritten; } #endif private static int GetNumBase64PaddingCharsToAddForDecode(int inputLength) { switch (inputLength % 4) { case 0: return 0; case 2: return 2; case 3: return 1; default: throw new FormatException( string.Format( CultureInfo.CurrentCulture, EncoderResources.WebEncoders_MalformedInput, inputLength)); } } private static void ValidateParameters(int bufferLength, string inputName, int offset, int count) { if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (bufferLength - offset < count) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, EncoderResources.WebEncoders_InvalidCountOffsetOrLength, nameof(count), nameof(offset), inputName), nameof(count)); } } } }
// ReSharper disable All using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using Frapid.Configuration; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.DbPolicy; using Frapid.Framework.Extensions; using Npgsql; using Frapid.NPoco; using Serilog; namespace Frapid.Config.DataAccess { /// <summary> /// Provides simplified data access features to perform SCRUD operation on the database table "config.smtp_configs". /// </summary> public class SmtpConfig : DbAccess, ISmtpConfigRepository { /// <summary> /// The schema of this table. Returns literal "config". /// </summary> public override string _ObjectNamespace => "config"; /// <summary> /// The schema unqualified name of this table. Returns literal "smtp_configs". /// </summary> public override string _ObjectName => "smtp_configs"; /// <summary> /// Login id of application user accessing this table. /// </summary> public long _LoginId { get; set; } /// <summary> /// User id of application user accessing this table. /// </summary> public int _UserId { get; set; } /// <summary> /// The name of the database on which queries are being executed to. /// </summary> public string _Catalog { get; set; } /// <summary> /// Performs SQL count on the table "config.smtp_configs". /// </summary> /// <returns>Returns the number of rows of the table "config.smtp_configs".</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long Count() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT COUNT(*) FROM config.smtp_configs;"; return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.smtp_configs" to return all instances of the "SmtpConfig" class. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "SmtpConfig" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetAll() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.smtp_configs ORDER BY smtp_id;"; return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.smtp_configs" to return all instances of the "SmtpConfig" class to export. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "SmtpConfig" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<dynamic> Export() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.smtp_configs ORDER BY smtp_id;"; return Factory.Get<dynamic>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.smtp_configs" with a where filter on the column "smtp_id" to return a single instance of the "SmtpConfig" class. /// </summary> /// <param name="smtpId">The column "smtp_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped instance of "SmtpConfig" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.SmtpConfig Get(int smtpId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get entity \"SmtpConfig\" filtered by \"SmtpId\" with value {SmtpId} was denied to the user with Login ID {_LoginId}", smtpId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.smtp_configs WHERE smtp_id=@0;"; return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql, smtpId).FirstOrDefault(); } /// <summary> /// Gets the first record of the table "config.smtp_configs". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "SmtpConfig" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.SmtpConfig GetFirst() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the first record of entity \"SmtpConfig\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.smtp_configs ORDER BY smtp_id LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Gets the previous record of the table "config.smtp_configs" sorted by smtpId. /// </summary> /// <param name="smtpId">The column "smtp_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "SmtpConfig" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.SmtpConfig GetPrevious(int smtpId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the previous entity of \"SmtpConfig\" by \"SmtpId\" with value {SmtpId} was denied to the user with Login ID {_LoginId}", smtpId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.smtp_configs WHERE smtp_id < @0 ORDER BY smtp_id DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql, smtpId).FirstOrDefault(); } /// <summary> /// Gets the next record of the table "config.smtp_configs" sorted by smtpId. /// </summary> /// <param name="smtpId">The column "smtp_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "SmtpConfig" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.SmtpConfig GetNext(int smtpId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the next entity of \"SmtpConfig\" by \"SmtpId\" with value {SmtpId} was denied to the user with Login ID {_LoginId}", smtpId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.smtp_configs WHERE smtp_id > @0 ORDER BY smtp_id LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql, smtpId).FirstOrDefault(); } /// <summary> /// Gets the last record of the table "config.smtp_configs". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "SmtpConfig" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.SmtpConfig GetLast() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the last record of entity \"SmtpConfig\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.smtp_configs ORDER BY smtp_id DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Executes a select query on the table "config.smtp_configs" with a where filter on the column "smtp_id" to return a multiple instances of the "SmtpConfig" class. /// </summary> /// <param name="smtpIds">Array of column "smtp_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped collection of "SmtpConfig" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.SmtpConfig> Get(int[] smtpIds) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}. smtpIds: {smtpIds}.", this._LoginId, smtpIds); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.smtp_configs WHERE smtp_id IN (@0);"; return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql, smtpIds); } /// <summary> /// Custom fields are user defined form elements for config.smtp_configs. /// </summary> /// <returns>Returns an enumerable custom field collection for the table config.smtp_configs</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get custom fields for entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } string sql; if (string.IsNullOrWhiteSpace(resourceId)) { sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='config.smtp_configs' ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql); } sql = "SELECT * from config.get_custom_field_definition('config.smtp_configs'::text, @0::text) ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId); } /// <summary> /// Displayfields provide a minimal name/value context for data binding the row collection of config.smtp_configs. /// </summary> /// <returns>Returns an enumerable name and value collection for the table config.smtp_configs</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>(); if (string.IsNullOrWhiteSpace(this._Catalog)) { return displayFields; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get display field for entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT smtp_id AS key, configuration_name as value FROM config.smtp_configs;"; using (NpgsqlCommand command = new NpgsqlCommand(sql)) { using (DataTable table = DbOperation.GetDataTable(this._Catalog, command)) { if (table?.Rows == null || table.Rows.Count == 0) { return displayFields; } foreach (DataRow row in table.Rows) { if (row != null) { DisplayField displayField = new DisplayField { Key = row["key"].ToString(), Value = row["value"].ToString() }; displayFields.Add(displayField); } } } } return displayFields; } /// <summary> /// Inserts or updates the instance of SmtpConfig class on the database table "config.smtp_configs". /// </summary> /// <param name="smtpConfig">The instance of "SmtpConfig" class to insert or update.</param> /// <param name="customFields">The custom field collection.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object AddOrEdit(dynamic smtpConfig, List<Frapid.DataAccess.Models.CustomField> customFields) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } smtpConfig.audit_user_id = this._UserId; smtpConfig.audit_ts = System.DateTime.UtcNow; object primaryKeyValue = smtpConfig.smtp_id; if (Cast.To<int>(primaryKeyValue) > 0) { this.Update(smtpConfig, Cast.To<int>(primaryKeyValue)); } else { primaryKeyValue = this.Add(smtpConfig); } string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" + "SELECT custom_field_setup_id " + "FROM config.custom_field_setup " + "WHERE form_name=config.get_custom_field_form_name('config.smtp_configs')" + ");"; Factory.NonQuery(this._Catalog, sql); if (customFields == null) { return primaryKeyValue; } foreach (var field in customFields) { sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " + "SELECT config.get_custom_field_setup_id_by_table_name('config.smtp_configs', @0::character varying(100)), " + "@1, @2;"; Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value); } return primaryKeyValue; } /// <summary> /// Inserts the instance of SmtpConfig class on the database table "config.smtp_configs". /// </summary> /// <param name="smtpConfig">The instance of "SmtpConfig" class to insert.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object Add(dynamic smtpConfig) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to add entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}. {SmtpConfig}", this._LoginId, smtpConfig); throw new UnauthorizedException("Access is denied."); } } return Factory.Insert(this._Catalog, smtpConfig, "config.smtp_configs", "smtp_id"); } /// <summary> /// Inserts or updates multiple instances of SmtpConfig class on the database table "config.smtp_configs"; /// </summary> /// <param name="smtpConfigs">List of "SmtpConfig" class to import.</param> /// <returns></returns> public List<object> BulkImport(List<ExpandoObject> smtpConfigs) { if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to import entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}. {smtpConfigs}", this._LoginId, smtpConfigs); throw new UnauthorizedException("Access is denied."); } } var result = new List<object>(); int line = 0; try { using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName)) { using (ITransaction transaction = db.GetTransaction()) { foreach (dynamic smtpConfig in smtpConfigs) { line++; smtpConfig.audit_user_id = this._UserId; smtpConfig.audit_ts = System.DateTime.UtcNow; object primaryKeyValue = smtpConfig.smtp_id; if (Cast.To<int>(primaryKeyValue) > 0) { result.Add(smtpConfig.smtp_id); db.Update("config.smtp_configs", "smtp_id", smtpConfig, smtpConfig.smtp_id); } else { result.Add(db.Insert("config.smtp_configs", "smtp_id", smtpConfig)); } } transaction.Complete(); } return result; } } catch (NpgsqlException ex) { string errorMessage = $"Error on line {line} "; if (ex.Code.StartsWith("P")) { errorMessage += Factory.GetDbErrorResource(ex); throw new DataAccessException(errorMessage, ex); } errorMessage += ex.Message; throw new DataAccessException(errorMessage, ex); } catch (System.Exception ex) { string errorMessage = $"Error on line {line} "; throw new DataAccessException(errorMessage, ex); } } /// <summary> /// Updates the row of the table "config.smtp_configs" with an instance of "SmtpConfig" class against the primary key value. /// </summary> /// <param name="smtpConfig">The instance of "SmtpConfig" class to update.</param> /// <param name="smtpId">The value of the column "smtp_id" which will be updated.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Update(dynamic smtpConfig, int smtpId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to edit entity \"SmtpConfig\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {SmtpConfig}", smtpId, this._LoginId, smtpConfig); throw new UnauthorizedException("Access is denied."); } } Factory.Update(this._Catalog, smtpConfig, smtpId, "config.smtp_configs", "smtp_id"); } /// <summary> /// Deletes the row of the table "config.smtp_configs" against the primary key value. /// </summary> /// <param name="smtpId">The value of the column "smtp_id" which will be deleted.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Delete(int smtpId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to delete entity \"SmtpConfig\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", smtpId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "DELETE FROM config.smtp_configs WHERE smtp_id=@0;"; Factory.NonQuery(this._Catalog, sql, smtpId); } /// <summary> /// Performs a select statement on table "config.smtp_configs" producing a paginated result of 10. /// </summary> /// <returns>Returns the first page of collection of "SmtpConfig" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetPaginatedResult() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the first page of the entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}.", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.smtp_configs ORDER BY smtp_id LIMIT 10 OFFSET 0;"; return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql); } /// <summary> /// Performs a select statement on table "config.smtp_configs" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result.</param> /// <returns>Returns collection of "SmtpConfig" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetPaginatedResult(long pageNumber) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; const string sql = "SELECT * FROM config.smtp_configs ORDER BY smtp_id LIMIT 10 OFFSET @0;"; return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql, offset); } public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName) { const string sql = "SELECT * FROM config.filters WHERE object_name='config.smtp_configs' AND lower(filter_name)=lower(@0);"; return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList(); } /// <summary> /// Performs a filtered count on table "config.smtp_configs". /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns number of rows of "SmtpConfig" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.smtp_configs WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.SmtpConfig(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.smtp_configs" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns collection of "SmtpConfig" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.smtp_configs WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.SmtpConfig(), filters); sql.OrderBy("smtp_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql); } /// <summary> /// Performs a filtered count on table "config.smtp_configs". /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns number of rows of "SmtpConfig" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountFiltered(string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.smtp_configs WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.SmtpConfig(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.smtp_configs" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns collection of "SmtpConfig" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetFiltered(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"SmtpConfig\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.smtp_configs WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.SmtpConfig(), filters); sql.OrderBy("smtp_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.SmtpConfig>(this._Catalog, sql); } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonEditor.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // MenuItems and in-Editor scripts for PhotonNetwork. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Reflection; using UnityEditor; using UnityEditorInternal; using UnityEngine; public class Text { public string WindowTitle = "PUN Wizard"; public string SetupWizardWarningTitle = "Warning"; public string SetupWizardWarningMessage = "You have not yet run the Photon setup wizard! Your game won't be able to connect. See Windows -> Photon Unity Networking."; public string MainMenuButton = "Main Menu"; public string ConnectButton = "Connect to Photon Cloud"; public string UsePhotonLabel = "Using the Photon Cloud is free for development. If you don't have an account yet, enter your email and register."; public string SendButton = "Send"; public string EmailLabel = "Email:"; public string SignedUpAlreadyLabel = "I am already signed up. Let me enter my AppId."; public string SetupButton = "Setup"; public string RegisterByWebsiteLabel = "I want to register by a website."; public string AccountWebsiteButton = "Open account website"; public string SelfHostLabel = "I want to host my own server. Let me set it up."; public string SelfHostSettingsButton = "Open self-hosting settings"; public string MobileExportNoteLabel = "Build for mobiles impossible. Get PUN+ or Unity Pro for mobile."; public string MobilePunPlusExportNoteLabel = "PUN+ available. Using native sockets for iOS/Android."; public string EmailInUseLabel = "The provided e-mail-address has already been registered."; public string KnownAppIdLabel = "Ah, I know my Application ID. Get me to setup."; public string SeeMyAccountLabel = "Mh, see my account page"; public string SelfHostSettingButton = "Open self-hosting settings"; public string OopsLabel = "Oops!"; public string SeeMyAccountPage = ""; public string CancelButton = "Cancel"; public string PhotonCloudConnect = "Connect to Photon Cloud"; public string SetupOwnHostLabel = "Setup own Photon Host"; public string PUNWizardLabel = "Photon Unity Networking (PUN) Wizard"; public string SettingsButton = "Settings"; public string SetupServerCloudLabel = "Setup wizard for setting up your own server or the cloud."; public string WarningPhotonDisconnect = ""; public string ConverterLabel = "Converter"; public string StartButton = "Start"; public string UNtoPUNLabel = "Converts pure Unity Networking to Photon Unity Networking."; public string SettingsFileLabel = "Settings File"; public string LocateSettingsButton = "Locate settings asset"; public string SettingsHighlightLabel = "Highlights the used photon settings file in the project."; public string DocumentationLabel = "Documentation"; public string OpenPDFText = "Open PDF"; public string OpenPDFTooltip = "Opens the local documentation pdf."; public string OpenDevNetText = "Open DevNet"; public string OpenDevNetTooltip = "Online documentation for Photon."; public string OpenCloudDashboardText = "Open Cloud Dashboard"; public string OpenCloudDashboardTooltip = "Review Cloud App information and statistics."; public string OpenForumText = "Open Forum"; public string OpenForumTooltip = "Online support for Photon."; public string QuestionsLabel = "Questions? Need help or want to give us feedback? You are most welcome!"; public string SeeForumButton = "See the Photon Forum"; public string OpenDashboardButton = "Open Dashboard (web)"; public string AppIdLabel = "Your AppId"; public string AppIdInfoLabel = "The AppId a Guid that identifies your game in the Photon Cloud. Find it on your dashboard page."; public string CloudRegionLabel = "Cloud Region"; public string RegionalServersInfo = "Photon Cloud has regional servers. Picking one near your customers improves ping times. You could use more than one but this setup does not support it."; public string SaveButton = "Save"; public string SettingsSavedTitle = "Success"; public string SettingsSavedMessage = "Saved your settings."; public string OkButton = "Ok"; public string SeeMyAccountPageButton = "Mh, see my account page"; public string SetupOwnServerLabel = "Running my app in the cloud was fun but...\nLet me setup my own Photon server."; public string OwnHostCloudCompareLabel = "I am not quite sure how 'my own host' compares to 'cloud'."; public string ComparisonPageButton = "See comparison page"; public string YourPhotonServerLabel = "Your Photon Server"; public string AddressIPLabel = "Address/ip:"; public string PortLabel = "Port:"; public string LicensesLabel = "Licenses"; public string LicenseDownloadText = "Free License Download"; public string LicenseDownloadTooltip = "Get your free license for up to 100 concurrent players."; public string TryPhotonAppLabel = "Running my own server is too much hassle..\nI want to give Photon's free app a try."; public string GetCloudAppButton = "Get the free cloud app"; public string ConnectionTitle = "Connecting"; public string ConnectionInfo = "Connecting to the account service.."; public string ErrorTextTitle = "Error"; public string ServerSettingsMissingLabel = "Photon Unity Networking (PUN) is missing the 'ServerSettings' script. Re-import PUN to fix this."; public string MoreThanOneLabel = "There are more than one "; public string FilesInResourceFolderLabel = " files in 'Resources' folder. Check your project to keep only one. Using: "; public string IncorrectRPCListTitle = "Warning: RPC-list becoming incompatible!"; public string IncorrectRPCListLabel = "Your project's RPC-list is full, so we can't add some RPCs just compiled.\n\nBy removing outdated RPCs, the list will be long enough but incompatible with older client builds!\n\nMake sure you change the game version where you use PhotonNetwork.ConnectUsingSettings()."; public string RemoveOutdatedRPCsLabel = "Remove outdated RPCs"; public string FullRPCListTitle = "Warning: RPC-list is full!"; public string FullRPCListLabel = "Your project's RPC-list is too long for PUN.\n\nYou can change PUN's source to use short-typed RPC index. Look for comments 'LIMITS RPC COUNT'\n\nAlternatively, remove some RPC methods (use more parameters per RPC maybe).\n\nAfter a RPC-list refresh, make sure you change the game version where you use PhotonNetwork.ConnectUsingSettings()."; public string SkipRPCListUpdateLabel = "Skip RPC-list update"; public string PUNNameReplaceTitle = "Warning: RPC-list Compatibility"; public string PUNNameReplaceLabel = "PUN replaces RPC names with numbers by using the RPC-list. All clients must use the same list for that.\n\nClearing it most likely makes your client incompatible with previous versions! Change your game version or make sure the RPC-list matches other clients."; public string RPCListCleared = "Clear RPC-list"; public string ServerSettingsCleanedWarning = "Cleared the PhotonServerSettings.RpcList! This makes new builds incompatible with older ones. Better change game version in PhotonNetwork.ConnectUsingSettings()."; } [InitializeOnLoad] public class PhotonEditor : EditorWindow { public static Text CurrentLang = new Text(); protected static AccountService.Origin RegisterOrigin = AccountService.Origin.Pun; protected Vector2 scrollPos = Vector2.zero; protected static string DocumentationLocation = "Assets/Photon Unity Networking/PhotonNetwork-Documentation.pdf"; protected static string UrlFreeLicense = "https://www.exitgames.com/en/OnPremise/Dashboard"; protected static string UrlDevNet = "http://doc.exitgames.com/en/pun/current/getting-started/pun-overview"; protected static string UrlForum = "http://forum.exitgames.com"; protected static string UrlCompare = "http://doc.exitgames.com/en/realtime/current/getting-started/onpremise-or-saas"; protected static string UrlHowToSetup = "http://doc.exitgames.com/en/onpremise/current/getting-started/photon-server-in-5min"; protected static string UrlAppIDExplained = "http://doc.exitgames.com/en/realtime/current/getting-started/obtain-your-app-id"; protected static string UrlAccountPage = "https://www.exitgames.com/Account/SignIn?email="; // opened in browser protected static string UrlCloudDashboard = "https://cloud.exitgames.com/Dashboard?email="; private enum GUIState { Uninitialized, Main, Setup } private enum PhotonSetupStates { RegisterForPhotonCloud, EmailAlreadyRegistered, SetupPhotonCloud, SetupSelfHosted } private GUIState guiState = GUIState.Uninitialized; private bool isSetupWizard = false; bool open = false; bool helpRegion = false; private PhotonSetupStates photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; private static double lastWarning = 0; private static bool postCompileActionsDone; private string photonAddress = "127.0.0.1"; private int photonPort = ServerSettings.DefaultMasterPort; private string emailAddress = string.Empty; private string cloudAppId = string.Empty; private static bool dontCheckPunSetupField; private static Texture2D HelpIcon; private static Texture2D WizardIcon; protected static Type WindowType = typeof(PhotonEditor); private static string[] cloudServerRegionNames; private static bool isPunPlus; private static bool androidLibExists; private static bool iphoneLibExists; /// <summary> /// Can be used to (temporarily) disable the checks for PUN Setup and scene PhotonViews. /// This will prevent scene PhotonViews from being updated, so be careful. /// When you re-set this value, checks are used again and scene PhotonViews get IDs as needed. /// </summary> protected static bool dontCheckPunSetup { get { return dontCheckPunSetupField; } set { if (dontCheckPunSetupField != value) { dontCheckPunSetupField = value; } } } static PhotonEditor() { EditorApplication.projectWindowChanged += EditorUpdate; EditorApplication.hierarchyWindowChanged += EditorUpdate; EditorApplication.playmodeStateChanged += PlaymodeStateChanged; EditorApplication.update += OnUpdate; HelpIcon = AssetDatabase.LoadAssetAtPath("Assets/Photon Unity Networking/Editor/PhotonNetwork/help.png", typeof(Texture2D)) as Texture2D; WizardIcon = AssetDatabase.LoadAssetAtPath("Assets/Photon Unity Networking/photoncloud-icon.png", typeof(Texture2D)) as Texture2D; // to be used in toolbar, the enum needs conversion to string[] being done here, once. Array enumValues = Enum.GetValues(typeof(CloudServerRegion)); cloudServerRegionNames = new string[enumValues.Length]; for (int i = 0; i < cloudServerRegionNames.Length; i++) { cloudServerRegionNames[i] = enumValues.GetValue(i).ToString(); } // detect optional packages PhotonEditor.CheckPunPlus(); } static void CheckPunPlus() { androidLibExists = File.Exists("Assets/Plugins/Android/libPhotonSocketPlugin.so"); iphoneLibExists = File.Exists("Assets/Plugins/IPhone/libPhotonSocketPlugin.a"); isPunPlus = androidLibExists || iphoneLibExists; } private static void ImportWin8Support() { if (EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode) { return; // don't import while compiling } #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_5 const string win8Package = "Assets/Plugins/Photon3Unity3D-Win8.unitypackage"; bool win8LibsExist = File.Exists("Assets/Plugins/WP8/Photon3Unity3D.dll") && File.Exists("Assets/Plugins/Metro/Photon3Unity3D.dll"); if (!win8LibsExist && File.Exists(win8Package)) { AssetDatabase.ImportPackage(win8Package, false); } #endif } [MenuItem("Window/Photon Unity Networking/PUN Wizard &p")] protected static void Init() { PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor; win.InitPhotonSetupWindow(); win.isSetupWizard = false; win.SwitchMenuState(GUIState.Main); } /// <summary>Creates an Editor window, showing the cloud-registration wizard for Photon (entry point to setup PUN).</summary> protected static void ShowRegistrationWizard() { PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor; win.isSetupWizard = true; win.InitPhotonSetupWindow(); } /// <summary>Re-initializes the Photon Setup window and shows one of three states: register cloud, setup cloud, setup self-hosted.</summary> protected void InitPhotonSetupWindow() { this.minSize = MinSize; this.SwitchMenuState(GUIState.Setup); this.ReApplySettingsToWindow(); switch (PhotonEditor.Current.HostType) { case ServerSettings.HostingOption.PhotonCloud: this.photonSetupState = PhotonSetupStates.SetupPhotonCloud; break; case ServerSettings.HostingOption.SelfHosted: this.photonSetupState = PhotonSetupStates.SetupSelfHosted; break; case ServerSettings.HostingOption.NotSet: default: this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; break; } } // called 100 times / sec private static void OnUpdate() { // after a compile, check RPCs to create a cache-list if (!postCompileActionsDone && !EditorApplication.isCompiling && !EditorApplication.isPlayingOrWillChangePlaymode) { #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_5 if (EditorApplication.isUpdating) return; #endif postCompileActionsDone = true; // on compile, this falls back to false (without actively doing anything) PhotonEditor.UpdateRpcList(); #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_5 PhotonEditor.ImportWin8Support(); #endif } } // called in editor, opens wizard for initial setup, keeps scene PhotonViews up to date and closes connections when compiling (to avoid issues) private static void EditorUpdate() { if (dontCheckPunSetup || PhotonEditor.Current == null) { return; } // serverSetting is null when the file gets deleted. otherwise, the wizard should only run once and only if hosting option is not (yet) set if (!PhotonEditor.Current.DisableAutoOpenWizard && PhotonEditor.Current.HostType == ServerSettings.HostingOption.NotSet) { ShowRegistrationWizard(); } // Workaround for TCP crash. Plus this surpresses any other recompile errors. if (EditorApplication.isCompiling) { if (PhotonNetwork.connected) { if (lastWarning > EditorApplication.timeSinceStartup - 3) { // Prevent error spam Debug.LogWarning(CurrentLang.WarningPhotonDisconnect); lastWarning = EditorApplication.timeSinceStartup; } PhotonNetwork.Disconnect(); } } } // called in editor on change of play-mode (used to show a message popup that connection settings are incomplete) private static void PlaymodeStateChanged() { if (dontCheckPunSetup || EditorApplication.isPlaying || !EditorApplication.isPlayingOrWillChangePlaymode) { return; } if (PhotonEditor.Current.HostType == ServerSettings.HostingOption.NotSet) { EditorUtility.DisplayDialog(CurrentLang.SetupWizardWarningTitle, CurrentLang.SetupWizardWarningMessage, CurrentLang.OkButton); } } private void SwitchMenuState(GUIState newState) { this.guiState = newState; if (this.isSetupWizard && newState != GUIState.Setup) { this.Close(); } } protected virtual void OnGUI() { PhotonSetupStates oldGuiState = this.photonSetupState; // used to fix an annoying Editor input field issue: wont refresh until focus is changed. GUI.SetNextControlName(""); this.scrollPos = GUILayout.BeginScrollView(this.scrollPos); if (this.guiState == GUIState.Uninitialized) { this.ReApplySettingsToWindow(); this.guiState = (PhotonEditor.Current.HostType == ServerSettings.HostingOption.NotSet) ? GUIState.Setup : GUIState.Main; } if (this.guiState == GUIState.Main) { this.OnGuiMainWizard(); } else { this.OnGuiRegisterCloudApp(); } GUILayout.EndScrollView(); if (oldGuiState != this.photonSetupState) { GUI.FocusControl(""); } } protected virtual void OnGuiRegisterCloudApp() { GUI.skin.label.wordWrap = true; if (!this.isSetupWizard) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.MainMenuButton, GUILayout.ExpandWidth(false))) { this.SwitchMenuState(GUIState.Main); } GUILayout.EndHorizontal(); GUILayout.Space(15); } if (this.photonSetupState == PhotonSetupStates.RegisterForPhotonCloud) { GUI.skin.label.fontStyle = FontStyle.Bold; GUILayout.Label(CurrentLang.ConnectButton); EditorGUILayout.Separator(); GUI.skin.label.fontStyle = FontStyle.Normal; GUILayout.Label(CurrentLang.UsePhotonLabel); EditorGUILayout.Separator(); this.emailAddress = EditorGUILayout.TextField(CurrentLang.EmailLabel, this.emailAddress); if (GUILayout.Button(CurrentLang.SendButton)) { GUIUtility.keyboardControl = 0; this.RegisterWithEmail(this.emailAddress); } GUILayout.Space(20); GUILayout.Label(CurrentLang.SignedUpAlreadyLabel); if (GUILayout.Button(CurrentLang.SetupButton)) { this.photonSetupState = PhotonSetupStates.SetupPhotonCloud; } EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.RegisterByWebsiteLabel); if (GUILayout.Button(CurrentLang.AccountWebsiteButton)) { EditorUtility.OpenWithDefaultApp(UrlAccountPage + Uri.EscapeUriString(this.emailAddress)); } EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.SelfHostLabel); if (GUILayout.Button(CurrentLang.SelfHostSettingsButton)) { this.photonAddress = ServerSettings.DefaultServerAddress; this.photonPort = ServerSettings.DefaultMasterPort; this.photonSetupState = PhotonSetupStates.SetupSelfHosted; } GUILayout.FlexibleSpace(); if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.Android) || !InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.iPhone)) { GUILayout.Label(CurrentLang.MobileExportNoteLabel); } EditorGUILayout.Separator(); } else if (this.photonSetupState == PhotonSetupStates.EmailAlreadyRegistered) { GUI.skin.label.fontStyle = FontStyle.Bold; GUILayout.Label(CurrentLang.OopsLabel); GUI.skin.label.fontStyle = FontStyle.Normal; GUILayout.Label(CurrentLang.EmailInUseLabel); if (GUILayout.Button(CurrentLang.SeeMyAccountPageButton)) { EditorUtility.OpenWithDefaultApp(UrlCloudDashboard + Uri.EscapeUriString(this.emailAddress)); } EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.KnownAppIdLabel); GUILayout.BeginHorizontal(); if (GUILayout.Button(CurrentLang.CancelButton)) { this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } if (GUILayout.Button(CurrentLang.SetupButton)) { this.photonSetupState = PhotonSetupStates.SetupPhotonCloud; } GUILayout.EndHorizontal(); } else if (this.photonSetupState == PhotonSetupStates.SetupPhotonCloud) { // cloud setup GUI.skin.label.fontStyle = FontStyle.Bold; GUILayout.Label(CurrentLang.PhotonCloudConnect); GUI.skin.label.fontStyle = FontStyle.Normal; EditorGUILayout.Separator(); this.OnGuiSetupCloudAppId(); this.OnGuiCompareAndHelpOptions(); } else if (this.photonSetupState == PhotonSetupStates.SetupSelfHosted) { // self-hosting setup GUI.skin.label.fontStyle = FontStyle.Bold; GUILayout.Label(CurrentLang.SetupOwnHostLabel); GUI.skin.label.fontStyle = FontStyle.Normal; EditorGUILayout.Separator(); this.OnGuiSetupSelfhosting(); this.OnGuiCompareAndHelpOptions(); } } protected virtual void OnGuiMainWizard() { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label(WizardIcon); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.PUNWizardLabel, EditorStyles.boldLabel); if (isPunPlus) { GUILayout.Label(CurrentLang.MobilePunPlusExportNoteLabel); } else if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.Android) || !InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.iPhone)) { GUILayout.Label(CurrentLang.MobileExportNoteLabel); } EditorGUILayout.Separator(); // settings button GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.SettingsButton, EditorStyles.boldLabel, GUILayout.Width(100)); if (GUILayout.Button(new GUIContent(CurrentLang.SetupButton, CurrentLang.SetupServerCloudLabel))) { this.InitPhotonSetupWindow(); } GUILayout.EndHorizontal(); EditorGUILayout.Separator(); // find / select settings asset GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.SettingsFileLabel, EditorStyles.boldLabel, GUILayout.Width(100)); if (GUILayout.Button(new GUIContent(CurrentLang.LocateSettingsButton, CurrentLang.SettingsHighlightLabel))) { EditorGUIUtility.PingObject(PhotonEditor.Current); } GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); // converter GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.ConverterLabel, EditorStyles.boldLabel, GUILayout.Width(100)); if (GUILayout.Button(new GUIContent(CurrentLang.StartButton, CurrentLang.UNtoPUNLabel))) { PhotonConverter.RunConversion(); } GUILayout.EndHorizontal(); EditorGUILayout.Separator(); // documentation GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.DocumentationLabel, EditorStyles.boldLabel, GUILayout.Width(100)); GUILayout.BeginVertical(); if (GUILayout.Button(new GUIContent(CurrentLang.OpenPDFText, CurrentLang.OpenPDFTooltip))) { EditorUtility.OpenWithDefaultApp(DocumentationLocation); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenDevNetText, CurrentLang.OpenDevNetTooltip))) { EditorUtility.OpenWithDefaultApp(UrlDevNet); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip))) { EditorUtility.OpenWithDefaultApp(UrlCloudDashboard + Uri.EscapeUriString(this.emailAddress)); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenForumText, CurrentLang.OpenForumTooltip))) { EditorUtility.OpenWithDefaultApp(UrlForum); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } protected virtual void OnGuiCompareAndHelpOptions() { GUILayout.FlexibleSpace(); GUILayout.Label(CurrentLang.QuestionsLabel); if (GUILayout.Button(CurrentLang.SeeForumButton)) { Application.OpenURL(UrlForum); } if (photonSetupState != PhotonSetupStates.SetupSelfHosted) { if (GUILayout.Button(CurrentLang.OpenDashboardButton)) { EditorUtility.OpenWithDefaultApp(UrlCloudDashboard + Uri.EscapeUriString(this.emailAddress)); } } } protected virtual void OnGuiSetupCloudAppId() { GUILayout.Label(CurrentLang.AppIdLabel); GUILayout.BeginHorizontal(); this.cloudAppId = EditorGUILayout.TextField(this.cloudAppId); open = GUILayout.Toggle(open, HelpIcon, GUIStyle.none, GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); if (open) GUILayout.Label(CurrentLang.AppIdInfoLabel); EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.CloudRegionLabel); int selectedRegion = ServerSettings.FindRegionForServerAddress(this.photonAddress); GUILayout.BeginHorizontal(); int toolbarValue = GUILayout.Toolbar(selectedRegion, cloudServerRegionNames); // the enum CloudServerRegion is converted into a string[] in init (toolbar can't use enum) helpRegion = GUILayout.Toggle(helpRegion, HelpIcon, GUIStyle.none, GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); if (helpRegion) GUILayout.Label(CurrentLang.RegionalServersInfo); if (selectedRegion != toolbarValue) { //Debug.Log("Replacing region: " + selectedRegion + " with: " + toolbarValue); this.photonAddress = ServerSettings.FindServerAddressForRegion(toolbarValue); } EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); if (GUILayout.Button(CurrentLang.CancelButton)) { GUIUtility.keyboardControl = 0; this.ReApplySettingsToWindow(); } if (GUILayout.Button(CurrentLang.SaveButton)) { GUIUtility.keyboardControl = 0; this.cloudAppId = this.cloudAppId.Trim(); PhotonEditor.Current.UseCloud(this.cloudAppId, selectedRegion); PhotonEditor.Save(); EditorUtility.DisplayDialog(CurrentLang.SettingsSavedTitle, CurrentLang.SettingsSavedMessage, CurrentLang.OkButton); } GUILayout.EndHorizontal(); GUILayout.Space(20); GUILayout.Label(CurrentLang.SetupOwnServerLabel); if (GUILayout.Button(CurrentLang.SelfHostSettingsButton)) { this.photonAddress = ServerSettings.DefaultServerAddress; this.photonPort = ServerSettings.DefaultMasterPort; this.photonSetupState = PhotonSetupStates.SetupSelfHosted; } EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.OwnHostCloudCompareLabel); if (GUILayout.Button(CurrentLang.ComparisonPageButton)) { Application.OpenURL(UrlCompare); } } protected virtual void OnGuiSetupSelfhosting() { GUILayout.Label(CurrentLang.YourPhotonServerLabel); this.photonAddress = EditorGUILayout.TextField(CurrentLang.AddressIPLabel, this.photonAddress); this.photonPort = EditorGUILayout.IntField(CurrentLang.PortLabel, this.photonPort); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); if (GUILayout.Button(CurrentLang.CancelButton)) { GUIUtility.keyboardControl = 0; this.ReApplySettingsToWindow(); } if (GUILayout.Button(CurrentLang.SaveButton)) { GUIUtility.keyboardControl = 0; PhotonEditor.Current.UseMyServer(this.photonAddress, this.photonPort, null); PhotonEditor.Save(); EditorUtility.DisplayDialog(CurrentLang.SettingsSavedTitle, CurrentLang.SettingsSavedMessage, CurrentLang.OkButton); } GUILayout.EndHorizontal(); EditorGUILayout.Separator(); // license GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.LicensesLabel, EditorStyles.boldLabel, GUILayout.Width(100)); if (GUILayout.Button(new GUIContent(CurrentLang.LicenseDownloadText, CurrentLang.LicenseDownloadTooltip))) { EditorUtility.OpenWithDefaultApp(UrlFreeLicense); } GUILayout.EndHorizontal(); GUILayout.Space(20); GUILayout.Label(CurrentLang.TryPhotonAppLabel); if (GUILayout.Button(CurrentLang.GetCloudAppButton)) { this.cloudAppId = string.Empty; this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.OwnHostCloudCompareLabel); if (GUILayout.Button(CurrentLang.ComparisonPageButton)) { Application.OpenURL(UrlCompare); } } protected virtual void RegisterWithEmail(string email) { EditorUtility.DisplayProgressBar(CurrentLang.ConnectionTitle, CurrentLang.ConnectionInfo, 0.5f); var client = new AccountService(); client.RegisterByEmail(email, RegisterOrigin); // this is the synchronous variant using the static RegisterOrigin. "result" is in the client EditorUtility.ClearProgressBar(); if (client.ReturnCode == 0) { PhotonEditor.Current.UseCloud(client.AppId, 0); PhotonEditor.Save(); this.ReApplySettingsToWindow(); this.photonSetupState = PhotonSetupStates.SetupPhotonCloud; } else { if (client.Message.Contains(CurrentLang.EmailInUseLabel)) { this.photonSetupState = PhotonSetupStates.EmailAlreadyRegistered; } else { EditorUtility.DisplayDialog(CurrentLang.ErrorTextTitle, client.Message, CurrentLang.OkButton); // Debug.Log(client.Exception); this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } } } #region SettingsFileHandling private static ServerSettings currentSettings; private Vector2 MinSize = new Vector2(350, 400); public static ServerSettings Current { get { if (currentSettings == null) { // find out if ServerSettings can be instantiated (existing script check) ScriptableObject serverSettingTest = CreateInstance("ServerSettings"); if (serverSettingTest == null) { Debug.LogError(CurrentLang.ServerSettingsMissingLabel); return null; } DestroyImmediate(serverSettingTest); // try to load settings from file ReLoadCurrentSettings(); // if still not loaded, create one if (currentSettings == null) { string settingsPath = Path.GetDirectoryName(PhotonNetwork.serverSettingsAssetPath); if (!Directory.Exists(settingsPath)) { Directory.CreateDirectory(settingsPath); AssetDatabase.ImportAsset(settingsPath); } currentSettings = (ServerSettings)ScriptableObject.CreateInstance("ServerSettings"); if (currentSettings != null) { AssetDatabase.CreateAsset(currentSettings, PhotonNetwork.serverSettingsAssetPath); } else { Debug.LogError(CurrentLang.ServerSettingsMissingLabel); } } } return currentSettings; } protected set { currentSettings = value; } } public static void Save() { EditorUtility.SetDirty(PhotonEditor.Current); } public static void ReLoadCurrentSettings() { // this now warns developers if there are more than one settings files in resources folders. first will be used. UnityEngine.Object[] settingFiles = Resources.LoadAll(PhotonNetwork.serverSettingsAssetFile, typeof(ServerSettings)); if (settingFiles != null && settingFiles.Length > 0) { PhotonEditor.Current = (ServerSettings)settingFiles[0]; if (settingFiles.Length > 1) { Debug.LogWarning(CurrentLang.MoreThanOneLabel + PhotonNetwork.serverSettingsAssetFile + CurrentLang.FilesInResourceFolderLabel + AssetDatabase.GetAssetPath(PhotonEditor.Current)); } } } protected void ReApplySettingsToWindow() { this.cloudAppId = string.IsNullOrEmpty(PhotonEditor.Current.AppID) ? string.Empty : PhotonEditor.Current.AppID; this.photonAddress = string.IsNullOrEmpty(PhotonEditor.Current.ServerAddress) ? string.Empty : PhotonEditor.Current.ServerAddress; this.photonPort = PhotonEditor.Current.ServerPort; } public static void UpdateRpcList() { HashSet<string> additionalRpcs = new HashSet<string>(); HashSet<string> currentRpcs = new HashSet<string>(); var types = GetAllSubTypesInScripts(typeof(MonoBehaviour)); foreach (var mono in types) { MethodInfo[] methods = mono.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (MethodInfo method in methods) { if (method.IsDefined(typeof(UnityEngine.RPC), false)) { currentRpcs.Add(method.Name); if (!PhotonEditor.Current.RpcList.Contains(method.Name)) { additionalRpcs.Add(method.Name); } } } } if (additionalRpcs.Count > 0) { // LIMITS RPC COUNT if (additionalRpcs.Count + PhotonEditor.Current.RpcList.Count >= byte.MaxValue) { if (currentRpcs.Count <= byte.MaxValue) { bool clearList = EditorUtility.DisplayDialog(CurrentLang.IncorrectRPCListTitle, CurrentLang.IncorrectRPCListLabel, CurrentLang.RemoveOutdatedRPCsLabel, CurrentLang.CancelButton); if (clearList) { PhotonEditor.Current.RpcList.Clear(); PhotonEditor.Current.RpcList.AddRange(currentRpcs); } else { return; } } else { EditorUtility.DisplayDialog(CurrentLang.FullRPCListTitle, CurrentLang.FullRPCListLabel, CurrentLang.SkipRPCListUpdateLabel); return; } } PhotonEditor.Current.RpcList.AddRange(additionalRpcs); EditorUtility.SetDirty(PhotonEditor.Current); } } public static void ClearRpcList() { bool clearList = EditorUtility.DisplayDialog(CurrentLang.PUNNameReplaceTitle, CurrentLang.PUNNameReplaceLabel, CurrentLang.RPCListCleared, CurrentLang.CancelButton); if (clearList) { PhotonEditor.Current.RpcList.Clear(); Debug.LogWarning(CurrentLang.ServerSettingsCleanedWarning); } } public static System.Type[] GetAllSubTypesInScripts(System.Type aBaseClass) { var result = new System.Collections.Generic.List<System.Type>(); System.Reflection.Assembly[] AS = System.AppDomain.CurrentDomain.GetAssemblies(); foreach (var A in AS) { // this skips all but the Unity-scripted assemblies for RPC-list creation. You could remove this to search all assemblies in project if (!A.FullName.StartsWith("Assembly-")) { // Debug.Log("Skipping Assembly: " + A); continue; } //Debug.Log("Assembly: " + A.FullName); System.Type[] types = A.GetTypes(); foreach (var T in types) { if (T.IsSubclassOf(aBaseClass)) result.Add(T); } } return result.ToArray(); } #endregion }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Leeroy.Json; using Logos.Git.GitHub; using Logos.Utility; using Logos.Utility.Logging; namespace Leeroy { /// <summary> /// Watches a single build repository, monitoring its submodules for changes. /// </summary> public class Watcher { public Watcher(BuildProject project, BuildServerClient buildServerClient, GitHubClient gitHubClient, CancellationToken token) { m_project = project; m_buildServerClient = buildServerClient; m_gitHubClient = gitHubClient; SplitRepoUrl(m_project.RepoUrl, out m_server, out m_user, out m_repo); m_branch = m_project.Branch ?? "master"; m_token = token; m_submodules = new Dictionary<string, Submodule>(); m_retryDelay = TimeSpan.FromSeconds(15); Log = LogManager.GetLogger("Watcher/{0}".FormatInvariant(m_project.Name)); Log.Info("Watching '{0}' branch in {1}/{2}.", m_branch, m_user, m_repo); } public Task CreateTask() { return Task.Factory.StartNew(Program.FailOnException<object>(Run), m_token, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning); } private void Run(object obj) { Dictionary<string, string> updatedSubmodules = new Dictionary<string, string>(); while (!m_token.IsCancellationRequested) { // check for changes to the build repo itself (and reload the submodules if so) string commitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, m_branch, m_updatingSubmodulesFailed); if (commitId == null) { Log.Info("Getting last commit ID failed; assuming branch doesn't exist."); commitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, "master"); if (commitId == null) { Log.Error("Getting commit ID for 'master' failed; will stop monitoring project."); break; } GitReference reference = m_gitHubClient.CreateReference(m_user, m_repo, m_branch, commitId); if (reference == null) { Log.Error("Failed to create new branch '{0}' (based on master = {1}); will stop monitoring project.", m_branch, commitId); break; } Log.Info("Sleeping for five seconds to allow GitHub API time to learn about the new branch."); Thread.Sleep(TimeSpan.FromSeconds(5)); } if (commitId != m_lastBuildCommitId) { if (m_lastBuildCommitId != null) { Log.Info("Build repo commit ID has changed from {0} to {1}; reloading submodules.", m_lastBuildCommitId, commitId); StartBuild(); } try { GetSubmodules(); } catch (WatcherException ex) { Log.Error("Getting submodules failed; will stop monitoring project.", ex); break; } updatedSubmodules.Clear(); } else { // check for changes in the submodules bool submoduleChanged = false; bool submoduleHasError = false; foreach (var pair in m_submodules) { Submodule submodule = pair.Value; commitId = m_gitHubClient.GetLatestCommitId(submodule.User, submodule.Repo, submodule.Branch, m_updatingSubmodulesFailed); if (commitId == null) { Log.Error("Submodule '{0}' doesn't have a latest commit for branch '{1}'; will stop monitoring project.", pair.Key, submodule.Branch); submoduleHasError = true; } else if (commitId != submodule.LatestCommitId && commitId != updatedSubmodules.GetValueOrDefault(pair.Key)) { Log.Info("Submodule '{0}' has changed from {1} to {2}; waiting for more changes.", pair.Key, submodule.LatestCommitId.Substring(0, 8), commitId.Substring(0, 8)); updatedSubmodules[pair.Key] = commitId; submoduleChanged = true; } } // abort if there were errors if (submoduleHasError) break; // pause for five seconds between each check m_token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)); // if any submodule changed, loop again (to allow changes to multiple submodules to be batched) if (submoduleChanged) continue; // if there were updated submodules, create a new commit m_updatingSubmodulesFailed = false; if (updatedSubmodules.Count != 0) { try { if (UpdateSubmodules(updatedSubmodules)) { m_retryDelay = TimeSpan.FromSeconds(15); } else { m_updatingSubmodulesFailed = true; m_retryDelay = m_retryDelay + m_retryDelay; TimeSpan maximumRetryDelay = TimeSpan.FromMinutes(30); if (m_retryDelay > maximumRetryDelay) m_retryDelay = maximumRetryDelay; Log.Info("Failed to update submodules; will wait {0} before trying again.", m_retryDelay); } updatedSubmodules.Clear(); // wait for the build to start, and/or for gitdata to be updated with the new commit data m_token.WaitHandle.WaitOne(m_retryDelay); } catch (WatcherException ex) { Log.Error("Updating submodules failed; will stop monitoring project.", ex); break; } } } } } // Triggers a Jenkins build by accessing the build URL. private void StartBuild() { // concatenate all build URL List<Uri> uris = new List<Uri>(m_project.BuildUrls ?? Enumerable.Empty<Uri>()); if (m_project.BuildUrl != null) uris.Add(m_project.BuildUrl); foreach (Uri uri in uris) m_buildServerClient.QueueBuild(uri); } // Gets the list of all submodules in the build repo. private void GetSubmodules() { m_submodules.Clear(); Log.Info("Getting latest commit.", m_user, m_repo, m_branch); m_lastBuildCommitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, m_branch); if (string.IsNullOrEmpty(m_lastBuildCommitId)) { string message = "No latest commit for {0}/{1}/{2}.".FormatInvariant(m_user, m_repo, m_branch); Log.Error(message); throw new WatcherException(message); } m_token.ThrowIfCancellationRequested(); Log.Info("Latest commit is {0}; getting details.", m_lastBuildCommitId); GitCommit gitCommit = m_gitHubClient.GetGitCommit(m_user, m_repo, m_lastBuildCommitId); if (gitCommit == null) { string message = "Getting commit {0} for {1}/{2}/{3} failed.".FormatInvariant(m_lastBuildCommitId, m_user, m_repo, m_branch); Log.Error(message); throw new WatcherException(message); } m_token.ThrowIfCancellationRequested(); Log.Debug("Fetching commit tree ({0}).", gitCommit.Tree.Sha); GitTree tree = m_gitHubClient.GetTree(gitCommit); if (tree == null) { string message = "Getting tree {0} for {1}/{2}/{3} failed.".FormatInvariant(gitCommit.Tree.Sha, m_user, m_repo, m_branch); Log.Error(message); throw new WatcherException(message); } m_token.ThrowIfCancellationRequested(); // if the new "submodules" property is specified, Leeroy will sync the submodules in the repo with the configuration file; // otherwise, the contents of the build repo will be used to initialize the submodule list if (m_project.Submodules != null) SyncSubmodules(gitCommit, tree); else LoadSubmodules(tree); } private void LoadSubmodules(GitTree buildRepoTree) { string gitModulesBlob = ReadGitModulesBlob(buildRepoTree); if (gitModulesBlob == null) { Log.Error("Tree {0} doesn't contain a .gitmodules file.", buildRepoTree.Sha); return; } using (StringReader reader = new StringReader(gitModulesBlob)) { foreach (var submodule in ParseConfigFile(reader).Where(x => x.Key.StartsWith("submodule ", StringComparison.Ordinal))) { // get submodule details string path = submodule.Value["path"]; string url = submodule.Value["url"]; string server, user, repo; if (!SplitRepoUrl(url, out server, out user, out repo)) { Log.Error("{0} is not a valid Git URL".FormatInvariant(url)); continue; } // find submodule in repo, and add it to list of tracked submodules GitTreeItem submoduleItem = buildRepoTree.Items.FirstOrDefault(x => x.Type == "commit" && x.Mode == "160000" && x.Path == path); if (submoduleItem == null) { Log.Warn(".gitmodules contains [{0}] but there is no submodule at path '{1}'.", submodule.Key, path); } else { // use specified branch; else default to tracking the build repo's branch string branch; if (m_project.SubmoduleBranches == null || !m_project.SubmoduleBranches.TryGetValue(path, out branch)) branch = m_branch; Log.Info("Adding new submodule: '{0}' = '{1}'.", path, url); m_submodules.Add(path, new Submodule { Url = url, User = user, Repo = repo, Branch = branch, LatestCommitId = submoduleItem.Sha }); } } } } // Loads the desired list of submodules from the configuration file. private void SyncSubmodules(GitCommit buildRepoCommit, GitTree buildRepoTree) { ReadSubmodulesFromConfig(); // find submodules that should be present in the build repo, but aren't bool updateSubmodules = false; foreach (KeyValuePair<string, Submodule> pair in m_submodules) { string path = pair.Key; Submodule submodule = pair.Value; GitTreeItem submoduleItem = buildRepoTree.Items.FirstOrDefault(x => x.Type == "commit" && x.Mode == "160000" && x.Path == path); if (submoduleItem != null) { submodule.LatestCommitId = submoduleItem.Sha; } else { submodule.LatestCommitId = m_gitHubClient.GetLatestCommitId(submodule.User, submodule.Repo, submodule.Branch); if (submodule.LatestCommitId == null) throw new WatcherException("Submodule '{0}' doesn't have a latest commit for branch '{1}'; will stop monitoring project.".FormatInvariant(pair.Key, submodule.Branch)); Log.Info("Submodule at path '{0}' is missing; it will be added.", pair.Key); updateSubmodules = true; } } // find extra submodules that aren't in the configuration file List<string> extraSubmodulePaths = buildRepoTree.Items .Where(x => x.Type == "commit" && x.Mode == "160000" && !m_submodules.ContainsKey(x.Path)) .Select(x => x.Path) .ToList(); if (extraSubmodulePaths.Count != 0) { Log.Info("Extra submodule paths: {0}".FormatInvariant(string.Join(", ", extraSubmodulePaths))); updateSubmodules = true; } // determine if .gitmodules needs to be updated bool rewriteGitModules = false; string gitModulesBlob = ReadGitModulesBlob(buildRepoTree); using (StringReader reader = new StringReader(gitModulesBlob ?? "")) { var existingGitModules = ParseConfigFile(reader) .Where(x => x.Key.StartsWith("submodule ", StringComparison.Ordinal)) .Select(x => new { Path = x.Value["path"], Url = x.Value["url"] }) .OrderBy(x => x.Path, StringComparer.Ordinal) .ToList(); var desiredGitModules = m_submodules.Select(x => new { Path = x.Key, x.Value.Url }).OrderBy(x => x.Path, StringComparer.Ordinal).ToList(); if (!existingGitModules.SequenceEqual(desiredGitModules)) { Log.Info(".gitmodules needs to be updated."); rewriteGitModules = true; } } if (updateSubmodules || rewriteGitModules) UpdateSubmodules(buildRepoCommit, buildRepoTree, rewriteGitModules); } private void ReadSubmodulesFromConfig() { // read submodules configuration foreach (KeyValuePair<string, string> pair in m_project.Submodules) { string url = pair.Key; string branch = pair.Value; // translate shorthand "User/Repo" into "git@git:User/Repo.git" if (Regex.IsMatch(url, @"^[^/]+/[^/]+$")) url = @"git@git:" + url + ".git"; string server, user, repo; SplitRepoUrl(url, out server, out user, out repo); Submodule submodule = new Submodule { Url = url, User = user, Repo = repo, Branch = branch }; string path = Path.GetFileNameWithoutExtension(url); if (path == null) throw new WatcherException("Couldn't determine path for submodule. Url={0}, Branch={1}".FormatInvariant(url, branch)); Log.Info("Adding new submodule: '{0}' = '{1}'.", path, url); m_submodules.Add(path, submodule); } } private string ReadGitModulesBlob(GitTree tree) { GitTreeItem gitModulesItem = tree.Items.FirstOrDefault(x => x.Type == "blob" && x.Path == ".gitmodules"); if (gitModulesItem == null) return null; GitBlob gitModulesBlob = m_gitHubClient.GetBlob(gitModulesItem); return gitModulesBlob.GetContent(); } private void UpdateSubmodules(GitCommit buildRepoCommit, GitTree buildRepoTree, bool rewriteGitModules) { // copy most items from the existing commit tree const string gitModulesPath = ".gitmodules"; List<GitTreeItem> treeItems = buildRepoTree.Items .Where(x => (x.Type != "commit" && x.Type != "blob") || (x.Type == "blob" && (!rewriteGitModules || x.Path != gitModulesPath))).ToList(); // add all the submodules treeItems.AddRange(m_submodules.Select(x => new GitTreeItem { Mode = "160000", Path = x.Key, Sha = x.Value.LatestCommitId, Type = "commit", })); if (rewriteGitModules) { // create the contents of the .gitmodules file string gitModules; using (StringWriter sw = new StringWriter { NewLine = "\n" }) { foreach (var pair in m_submodules.OrderBy(x => x.Key, StringComparer.Ordinal)) { sw.WriteLine("[submodule \"{0}\"]", pair.Key); sw.WriteLine("\tpath = {0}", pair.Key); sw.WriteLine("\turl = {0}", pair.Value.Url); } gitModules = sw.ToString(); } // create the blob GitBlob gitModulesBlob = CreateBlob(gitModules); treeItems.Add(new GitTreeItem { Mode = "100644", Path = gitModulesPath, Sha = gitModulesBlob.Sha, Type = "blob", }); } const string commitMessage = "Update submodules to match Leeroy configuration."; GitCommit newCommit = CreateNewCommit(buildRepoCommit, null, treeItems, commitMessage); Log.Info("Created new commit for synced submodules: {0}; moving branch.", newCommit.Sha); // advance the branch pointer to the new commit if (TryAdvanceBranch(newCommit.Sha)) { Log.Info("Build repo updated successfully to commit {0}.", newCommit.Sha); m_lastBuildCommitId = newCommit.Sha; } } private bool UpdateSubmodules(IDictionary<string, string> updatedSubmodules) { Log.Info("Updating the following submodules: {0}.", string.Join(", ", updatedSubmodules.Keys)); // get previous commit (that we will be updating) GitCommit commit = m_gitHubClient.GetGitCommit(m_user, m_repo, m_lastBuildCommitId); GitTree oldTree = m_gitHubClient.GetTree(commit); // add updated submodules List<GitTreeItem> treeItems = new List<GitTreeItem>(updatedSubmodules.Select(x => new GitTreeItem { Mode = "160000", Path = x.Key, Sha = x.Value, Type = "commit", })); // update build number const string buildNumberPath = "SolutionBuildNumber.txt"; int buildVersion = 0; GitTreeItem buildVersionItem = oldTree.Items.FirstOrDefault(x => x.Type == "blob" && x.Path == buildNumberPath); if (buildVersionItem != null) { GitBlob buildVersionBlob = m_gitHubClient.GetBlob(buildVersionItem); buildVersion = int.Parse(buildVersionBlob.GetContent().Trim()); buildVersion++; Log.Debug("Updating build number to {0}.", buildVersion); string buildVersionString = "{0}\r\n".FormatInvariant(buildVersion); GitBlob newBuildVersionBlob = CreateBlob(buildVersionString); treeItems.Add(new GitTreeItem { Mode = "100644", Path = buildNumberPath, Sha = newBuildVersionBlob.Sha, Type = "blob", }); Log.Debug("New build number blob is {0}", buildVersionBlob.Sha); } // create commit message StringBuilder commitMessage = new StringBuilder(); commitMessage.AppendLine("Build {0}".FormatInvariant(buildVersion)); // append details for each repository foreach (var pair in updatedSubmodules) { string submodulePath = pair.Key; Submodule submodule = m_submodules[submodulePath]; CommitComparison comparison = m_gitHubClient.CompareCommits(submodule.User, submodule.Repo, submodule.LatestCommitId, pair.Value); if (comparison != null) { string authors = string.Join(", ", comparison.Commits.Select(x => x.GitCommit.Author.Name + " <" + x.GitCommit.Author.Email + ">").Distinct().OrderBy(x => x, StringComparer.InvariantCultureIgnoreCase)); if (authors.Length > 0) { commitMessage.AppendLine(); commitMessage.AppendLine("Authors: {0}".FormatInvariant(authors)); } foreach (Commit comparisonCommit in comparison.Commits.Reverse().Take(5)) { // read the first line of the commit message string message; using (StringReader reader = new StringReader(comparisonCommit.GitCommit.Message ?? "")) message = reader.ReadLine(); commitMessage.AppendLine(); commitMessage.AppendLine("{0}: {1}".FormatInvariant(comparisonCommit.GitCommit.Author.Name, message)); commitMessage.AppendLine(" {0}/{1}".FormatInvariant(submodulePath, comparisonCommit.Sha)); Commit fullCommit = m_gitHubClient.GetCommit(submodule.User, submodule.Repo, comparisonCommit.Sha); if (fullCommit != null && fullCommit.Files != null) { foreach (CommitFile file in fullCommit.Files) commitMessage.AppendLine(" {0}".FormatInvariant(file.Filename)); } } if (comparison.TotalCommits > 5) { commitMessage.AppendLine(); commitMessage.AppendLine("... and {0} more commits to {1}.".FormatInvariant(comparison.TotalCommits - 5, submodulePath)); } } else { commitMessage.AppendLine(); commitMessage.AppendLine("Updated {0} from {1} to {2} (no details available).".FormatInvariant(submodulePath, submodule.LatestCommitId.Substring(0, 8), pair.Value.Substring(0, 8))); } } GitCommit newCommit = CreateNewCommit(commit, oldTree.Sha, treeItems, commitMessage.ToString()); Log.Info("Created new commit for build {0}: {1}; moving branch.", buildVersion, newCommit.Sha); // advance the branch pointer to the new commit if (TryAdvanceBranch(newCommit.Sha)) { Log.Info("Build repo updated successfully to commit {0}.", newCommit.Sha); m_lastBuildCommitId = newCommit.Sha; foreach (var pair in updatedSubmodules) m_submodules[pair.Key].LatestCommitId = pair.Value; StartBuild(); return true; } else { return false; } } private GitBlob CreateBlob(string content) { string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(content)); GitBlob newBlob = new GitBlob { Content = base64, Encoding = "base64" }; newBlob = m_gitHubClient.CreateBlob(m_user, m_repo, newBlob); if (newBlob == null) throw new WatcherException("Couldn't create blob with content '{0}'.".FormatInvariant(content.Substring(Math.Min(100, content.Length)))); return newBlob; } private GitCommit CreateNewCommit(GitCommit parentCommit, string baseTreeSha, List<GitTreeItem> treeItems, string commitMessage) { // create new tree GitCreateTree newTree = new GitCreateTree { BaseTree = baseTreeSha, Tree = treeItems.ToArray() }; GitTree tree = m_gitHubClient.CreateTree(m_user, m_repo, newTree); if (tree == null) throw new WatcherException("Couldn't create new tree."); Log.Debug("Created new tree: {0}.", tree.Sha); // create a commit GitCreateCommit createCommit = new GitCreateCommit { Message = commitMessage, Parents = new[] { parentCommit.Sha }, Tree = tree.Sha, }; GitCommit newCommit = m_gitHubClient.CreateCommit(m_user, m_repo, createCommit); if (newCommit == null) throw new WatcherException("Couldn't create new commit."); return newCommit; } private bool TryAdvanceBranch(string newSha) { // advance the branch pointer to the new commit GitReference reference = m_gitHubClient.UpdateReference(m_user, m_repo, m_branch, new GitUpdateReference { Sha = newSha }); if (reference != null && reference.Object.Sha == newSha) { Log.Info("Branch '{0}' now references '{1}'.", m_branch, newSha); return true; } else { Log.Warn("Branch '{0}' could not be updated to reference '{1}'.", m_branch, newSha); return false; } } // Parses a git configuration file into blocks. private IEnumerable<KeyValuePair<string, Dictionary<string, string>>> ParseConfigFile(TextReader reader) { string currentSection = null; Dictionary<string, string> values = null; string line; while ((line = reader.ReadLine()) != null) { if (string.IsNullOrWhiteSpace(line)) continue; // check for [section heading] if (line[0] == '[' && line[line.Length - 1] == ']') { if (currentSection != null) yield return new KeyValuePair<string, Dictionary<string, string>>(currentSection, values); currentSection = line.Substring(1, line.Length - 2); values = new Dictionary<string, string>(); } else if (currentSection != null && line.IndexOf('=') != -1) { // parse 'name = value' pair int equalsIndex = line.IndexOf('='); string key = line.Substring(0, equalsIndex).Trim(); string value = line.Substring(equalsIndex + 1).Trim(); values.Add(key, value); } else { Log.Warn("Couldn't parse .gitmodules line: {0}", line); } } if (currentSection != null) yield return new KeyValuePair<string, Dictionary<string, string>>(currentSection, values); } private static bool SplitRepoUrl(string url, out string server, out string user, out string repo) { Match m = Regex.Match(url, @"^git@(?'server'[^:]+):(?'user'[^/]+)/(?'repo'.*?)\.git$"); server = m.Groups["server"].Value; user = m.Groups["user"].Value; repo = m.Groups["repo"].Value; return m.Success; } readonly BuildProject m_project; readonly BuildServerClient m_buildServerClient; readonly GitHubClient m_gitHubClient; readonly string m_server; readonly string m_user; readonly string m_repo; readonly string m_branch; readonly CancellationToken m_token; readonly Dictionary<string, Submodule> m_submodules; readonly Logger Log; string m_lastBuildCommitId; TimeSpan m_retryDelay; bool m_updatingSubmodulesFailed; } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>AdGroupAdAssetView</c> resource.</summary> public sealed partial class AdGroupAdAssetViewName : gax::IResourceName, sys::IEquatable<AdGroupAdAssetViewName> { /// <summary>The possible contents of <see cref="AdGroupAdAssetViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c>. /// </summary> CustomerAdGroupAdAssetFieldType = 1, } private static gax::PathTemplate s_customerAdGroupAdAssetFieldType = new gax::PathTemplate("customers/{customer_id}/adGroupAdAssetViews/{ad_group_id_ad_id_asset_id_field_type}"); /// <summary>Creates a <see cref="AdGroupAdAssetViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AdGroupAdAssetViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AdGroupAdAssetViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AdGroupAdAssetViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AdGroupAdAssetViewName"/> with the pattern /// <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AdGroupAdAssetViewName"/> constructed from the provided ids.</returns> public static AdGroupAdAssetViewName FromCustomerAdGroupAdAssetFieldType(string customerId, string adGroupId, string adId, string assetId, string fieldTypeId) => new AdGroupAdAssetViewName(ResourceNameType.CustomerAdGroupAdAssetFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupAdAssetViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupAdAssetViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string adId, string assetId, string fieldTypeId) => FormatCustomerAdGroupAdAssetFieldType(customerId, adGroupId, adId, assetId, fieldTypeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupAdAssetViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupAdAssetViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c>. /// </returns> public static string FormatCustomerAdGroupAdAssetFieldType(string customerId, string adGroupId, string adId, string assetId, string fieldTypeId) => s_customerAdGroupAdAssetFieldType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupAdAssetViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="adGroupAdAssetViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AdGroupAdAssetViewName"/> if successful.</returns> public static AdGroupAdAssetViewName Parse(string adGroupAdAssetViewName) => Parse(adGroupAdAssetViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupAdAssetViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupAdAssetViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AdGroupAdAssetViewName"/> if successful.</returns> public static AdGroupAdAssetViewName Parse(string adGroupAdAssetViewName, bool allowUnparsed) => TryParse(adGroupAdAssetViewName, allowUnparsed, out AdGroupAdAssetViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupAdAssetViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="adGroupAdAssetViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupAdAssetViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string adGroupAdAssetViewName, out AdGroupAdAssetViewName result) => TryParse(adGroupAdAssetViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupAdAssetViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupAdAssetViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupAdAssetViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string adGroupAdAssetViewName, bool allowUnparsed, out AdGroupAdAssetViewName result) { gax::GaxPreconditions.CheckNotNull(adGroupAdAssetViewName, nameof(adGroupAdAssetViewName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupAdAssetFieldType.TryParseName(adGroupAdAssetViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupAdAssetFieldType(resourceName[0], split1[0], split1[1], split1[2], split1[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(adGroupAdAssetViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AdGroupAdAssetViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adId = null, string adGroupId = null, string assetId = null, string customerId = null, string fieldTypeId = null) { Type = type; UnparsedResource = unparsedResourceName; AdId = adId; AdGroupId = adGroupId; AssetId = assetId; CustomerId = customerId; FieldTypeId = fieldTypeId; } /// <summary> /// Constructs a new instance of a <see cref="AdGroupAdAssetViewName"/> class from the component parts of /// pattern <c>customers/{customer_id}/adGroupAdAssetViews/{ad_group_id}~{ad_id}~{asset_id}~{field_type}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> public AdGroupAdAssetViewName(string customerId, string adGroupId, string adId, string assetId, string fieldTypeId) : this(ResourceNameType.CustomerAdGroupAdAssetFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Ad</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdId { get; } /// <summary> /// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Asset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AssetId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>FieldType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FieldTypeId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAdGroupAdAssetFieldType: return s_customerAdGroupAdAssetFieldType.Expand(CustomerId, $"{AdGroupId}~{AdId}~{AssetId}~{FieldTypeId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AdGroupAdAssetViewName); /// <inheritdoc/> public bool Equals(AdGroupAdAssetViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AdGroupAdAssetViewName a, AdGroupAdAssetViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AdGroupAdAssetViewName a, AdGroupAdAssetViewName b) => !(a == b); } public partial class AdGroupAdAssetView { /// <summary> /// <see cref="AdGroupAdAssetViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AdGroupAdAssetViewName ResourceNameAsAdGroupAdAssetViewName { get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupAdAssetViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupAdName"/>-typed view over the <see cref="AdGroupAd"/> resource name property. /// </summary> internal AdGroupAdName AdGroupAdAsAdGroupAdName { get => string.IsNullOrEmpty(AdGroupAd) ? null : AdGroupAdName.Parse(AdGroupAd, allowUnparsed: true); set => AdGroupAd = value?.ToString() ?? ""; } /// <summary><see cref="AssetName"/>-typed view over the <see cref="Asset"/> resource name property.</summary> internal AssetName AssetAsAssetName { get => string.IsNullOrEmpty(Asset) ? null : AssetName.Parse(Asset, allowUnparsed: true); set => Asset = value?.ToString() ?? ""; } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !MONO namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security.Principal; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class ImpersonatingTargetWrapperTests : NLogTestBase { private const string NLogTestUser = "NLogTestUser"; private const string NLogTestUserPassword = "BC@57acasd123"; [Fact] public void ImpersonatingWrapperTest() { var wrapped = new MyTarget() { ExpectedUser = Environment.MachineName + "\\" + NLogTestUser, }; var wrapper = new ImpersonatingTargetWrapper() { UserName = NLogTestUser, Password = NLogTestUserPassword, Domain = Environment.MachineName, WrappedTarget = wrapped, }; // wrapped.Initialize(null); wrapper.Initialize(null); var exceptions = new List<Exception>(); wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(1, exceptions.Count); wrapper.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(4, exceptions.Count); wrapper.Flush(exceptions.Add); Assert.Equal(5, exceptions.Count); foreach (var ex in exceptions) { Assert.Null(ex); } wrapper.Close(); } [Fact] public void RevertToSelfTest() { var wrapped = new MyTarget() { ExpectedUser = Environment.UserDomainName + "\\" + Environment.UserName, }; WindowsIdentity originalIdentity = WindowsIdentity.GetCurrent(); try { var id = this.CreateWindowsIdentity(NLogTestUser, Environment.MachineName, NLogTestUserPassword, SecurityLogOnType.Interactive, LogOnProviderType.Default, SecurityImpersonationLevel.Identification); id.Impersonate(); WindowsIdentity changedIdentity = WindowsIdentity.GetCurrent(); Assert.Contains(NLogTestUser.ToLowerInvariant(), changedIdentity.Name.ToLowerInvariant(), StringComparison.InvariantCulture); var wrapper = new ImpersonatingTargetWrapper() { WrappedTarget = wrapped, RevertToSelf = true, }; // wrapped.Initialize(null); wrapper.Initialize(null); var exceptions = new List<Exception>(); wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(1, exceptions.Count); wrapper.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(4, exceptions.Count); wrapper.Flush(exceptions.Add); Assert.Equal(5, exceptions.Count); foreach (var ex in exceptions) { Assert.Null(ex); } wrapper.Close(); } finally { // revert to self NativeMethods.RevertToSelf(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); Assert.Equal(originalIdentity.Name.ToLowerInvariant(), currentIdentity.Name.ToLowerInvariant()); } } [Fact] public void ImpersonatingWrapperNegativeTest() { var wrapped = new MyTarget() { ExpectedUser = NLogTestUser, }; LogManager.ThrowExceptions = true; var wrapper = new ImpersonatingTargetWrapper() { UserName = NLogTestUser, Password = Guid.NewGuid().ToString("N"), // wrong password Domain = Environment.MachineName, WrappedTarget = wrapped, }; Assert.Throws<COMException>(() => { wrapper.Initialize(null); }); wrapper.Close(); // will not fail because Initialize() failed } [Fact] public void ImpersonatingWrapperNegativeTest2() { var wrapped = new MyTarget() { ExpectedUser = NLogTestUser, }; LogManager.ThrowExceptions = true; var wrapper = new ImpersonatingTargetWrapper() { UserName = NLogTestUser, Password = NLogTestUserPassword, // wrong password Domain = Environment.MachineName, ImpersonationLevel = (SecurityImpersonationLevel)1234, WrappedTarget = wrapped, }; Assert.Throws<COMException>(() => { wrapper.Initialize(null); }); wrapper.Close(); // will not fail because Initialize() failed } private WindowsIdentity CreateWindowsIdentity(string username, string domain, string password, SecurityLogOnType logonType, LogOnProviderType logonProviderType, SecurityImpersonationLevel impersonationLevel) { // initialize tokens var existingTokenHandle = IntPtr.Zero; var duplicateTokenHandle = IntPtr.Zero; if (!NativeMethods.LogonUser( username, domain, password, (int)logonType, (int)logonProviderType, out existingTokenHandle)) { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } if (!NativeMethods.DuplicateToken(existingTokenHandle, (int)impersonationLevel, out duplicateTokenHandle)) { NativeMethods.CloseHandle(existingTokenHandle); throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } // create new identity using new primary token return new WindowsIdentity(duplicateTokenHandle); } private static class NativeMethods { // obtains user token [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken); // closes open handles returned by LogonUser [DllImport("kernel32.dll", CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr handle); // creates duplicate token handle [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DuplicateToken(IntPtr existingTokenHandle, int impersonationLevel, out IntPtr duplicateTokenHandle); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool RevertToSelf(); } public class MyTarget : Target { public MyTarget() { this.Events = new List<LogEventInfo>(); } public List<LogEventInfo> Events { get; set; } public string ExpectedUser { get; set; } protected override void InitializeTarget() { base.InitializeTarget(); this.AssertExpectedUser(); } protected override void CloseTarget() { base.CloseTarget(); this.AssertExpectedUser(); } protected override void Write(LogEventInfo logEvent) { this.AssertExpectedUser(); this.Events.Add(logEvent); } protected override void Write(AsyncLogEventInfo[] logEvents) { this.AssertExpectedUser(); base.Write(logEvents); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.AssertExpectedUser(); base.FlushAsync(asyncContinuation); } private void AssertExpectedUser() { if (this.ExpectedUser != null) { var windowsIdentity = WindowsIdentity.GetCurrent(); Assert.True(windowsIdentity.IsAuthenticated); Assert.Equal(Environment.MachineName + "\\" + ExpectedUser, windowsIdentity.Name); } } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Net.Security; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Threading.Tasks; using Microsoft.DotNet.XUnitExtensions; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "SslProtocols not supported on UAP")] public abstract partial class HttpClientHandler_SslProtocols_Test : HttpClientHandlerTestBase { public HttpClientHandler_SslProtocols_Test(ITestOutputHelper output) : base(output) { } [Fact] public void DefaultProtocols_MatchesExpected() { using (HttpClientHandler handler = CreateHttpClientHandler()) { Assert.Equal(SslProtocols.None, handler.SslProtocols); } } [Theory] [InlineData(SslProtocols.None)] [InlineData(SslProtocols.Tls)] [InlineData(SslProtocols.Tls11)] [InlineData(SslProtocols.Tls12)] [InlineData(SslProtocols.Tls | SslProtocols.Tls11)] [InlineData(SslProtocols.Tls11 | SslProtocols.Tls12)] [InlineData(SslProtocols.Tls | SslProtocols.Tls12)] [InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)] [InlineData(SslProtocols.Tls13)] [InlineData(SslProtocols.Tls11 | SslProtocols.Tls13)] [InlineData(SslProtocols.Tls12 | SslProtocols.Tls13)] [InlineData(SslProtocols.Tls | SslProtocols.Tls13)] [InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13)] public void SetGetProtocols_Roundtrips(SslProtocols protocols) { using (HttpClientHandler handler = CreateHttpClientHandler()) { handler.SslProtocols = protocols; Assert.Equal(protocols, handler.SslProtocols); } } [Fact] public async Task SetProtocols_AfterRequest_ThrowsException() { if (!BackendSupportsSslConfiguration) { return; } using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( server.AcceptConnectionSendResponseAndCloseAsync(), client.GetAsync(url)); }); Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12); } } public static IEnumerable<object[]> GetAsync_AllowedSSLVersion_Succeeds_MemberData() { // These protocols are all enabled by default, so we can connect with them both when // explicitly specifying it in the client and when not. foreach (SslProtocols protocol in new[] { SslProtocols.Tls, SslProtocols.Tls11, SslProtocols.Tls12 }) { yield return new object[] { protocol, false }; yield return new object[] { protocol, true }; } // These protocols are disabled by default, so we can only connect with them explicitly. // On certain platforms these are completely disabled and cannot be used at all. #pragma warning disable 0618 if (PlatformDetection.SupportsSsl3) { yield return new object[] { SslProtocols.Ssl3, true }; } if (PlatformDetection.IsWindows && !PlatformDetection.IsWindows10Version1607OrGreater) { yield return new object[] { SslProtocols.Ssl2, true }; } #pragma warning restore 0618 // These protocols are new, and might not be enabled everywhere yet if (PlatformDetection.IsUbuntu1810OrHigher) { yield return new object[] { SslProtocols.Tls13, false }; yield return new object[] { SslProtocols.Tls13, true }; } } [ConditionalTheory] [MemberData(nameof(GetAsync_AllowedSSLVersion_Succeeds_MemberData))] public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol) { if (!BackendSupportsSslConfiguration) { return; } #pragma warning disable 0618 if (IsCurlHandler && PlatformDetection.IsRedHatFamily6 && acceptedProtocol == SslProtocols.Ssl3) { // Issue: #28790: SSLv3 is supported on RHEL 6, but it fails with curl. throw new SkipTestException("CurlHandler (libCurl) has problems with SSL3 on RH6"); } #pragma warning restore 0618 using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; if (requestOnlyThisProtocol) { handler.SslProtocols = acceptedProtocol; } else { // Explicitly setting protocols clears implementation default // restrictions on minimum TLS/SSL version // We currently know that some platforms like Debian 10 OpenSSL // will by default block < TLS 1.2 handler.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13; } var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( server.AcceptConnectionSendResponseAndCloseAsync(), client.GetAsync(url)); }, options); } } public static IEnumerable<object[]> SupportedSSLVersionServers() { #pragma warning disable 0618 // SSL2/3 are deprecated if (PlatformDetection.IsWindows || PlatformDetection.IsOSX || (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && PlatformDetection.OpenSslVersion < new Version(1, 0, 2) && !PlatformDetection.IsDebian)) { yield return new object[] { SslProtocols.Ssl3, Configuration.Http.SSLv3RemoteServer }; } #pragma warning restore 0618 yield return new object[] { SslProtocols.Tls, Configuration.Http.TLSv10RemoteServer }; yield return new object[] { SslProtocols.Tls11, Configuration.Http.TLSv11RemoteServer }; yield return new object[] { SslProtocols.Tls12, Configuration.Http.TLSv12RemoteServer }; } // We have tests that validate with SslStream, but that's limited by what the current OS supports. // This tests provides additional validation against an external server. [ActiveIssue(26186)] [OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")] [Theory] [MemberData(nameof(SupportedSSLVersionServers))] public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url) { if (UseSocketsHttpHandler) { // TODO #26186: SocketsHttpHandler is failing on some OSes. return; } using (HttpClientHandler handler = CreateHttpClientHandler()) { handler.SslProtocols = sslProtocols; using (HttpClient client = CreateHttpClient(handler)) { (await RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url)).Dispose(); } } } public Func<Exception, bool> remoteServerExceptionWrapper = (exception) => { Type exceptionType = exception.GetType(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { // On linux, taskcanceledexception is thrown. return exceptionType.Equals(typeof(TaskCanceledException)); } else { // The internal exceptions return operation timed out. return exceptionType.Equals(typeof(HttpRequestException)) && exception.InnerException.Message.Contains("timed out"); } }; public static IEnumerable<object[]> NotSupportedSSLVersionServers() { #pragma warning disable 0618 if (PlatformDetection.IsWindows10Version1607OrGreater) { yield return new object[] { SslProtocols.Ssl2, Configuration.Http.SSLv2RemoteServer }; } #pragma warning restore 0618 } // We have tests that validate with SslStream, but that's limited by what the current OS supports. // This tests provides additional validation against an external server. [OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")] [Theory] [MemberData(nameof(NotSupportedSSLVersionServers))] public async Task GetAsync_UnsupportedSSLVersion_Throws(SslProtocols sslProtocols, string url) { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.SslProtocols = sslProtocols; await Assert.ThrowsAsync<HttpRequestException>(() => RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url)); } } [Fact] public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12() { if (!BackendSupportsSslConfiguration) { return; } using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = SslProtocols.Tls12 }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( client.GetAsync(url), server.AcceptConnectionAsync(async connection => { Assert.Equal(SslProtocols.Tls12, Assert.IsType<SslStream>(connection.Stream).SslProtocol); await connection.ReadRequestHeaderAndSendResponseAsync(); })); }, options); } } [Theory] #pragma warning disable 0618 // SSL2/3 are deprecated [InlineData(SslProtocols.Ssl2, SslProtocols.Tls12)] [InlineData(SslProtocols.Ssl3, SslProtocols.Tls12)] #pragma warning restore 0618 [InlineData(SslProtocols.Tls11, SslProtocols.Tls)] [InlineData(SslProtocols.Tls11 | SslProtocols.Tls12, SslProtocols.Tls)] // Skip this on WinHttpHandler. [InlineData(SslProtocols.Tls12, SslProtocols.Tls11)] [InlineData(SslProtocols.Tls, SslProtocols.Tls12)] public async Task GetAsync_AllowedClientSslVersionDiffersFromServer_ThrowsException( SslProtocols allowedClientProtocols, SslProtocols acceptedServerProtocols) { if (!BackendSupportsSslConfiguration) { return; } if (IsWinHttpHandler && allowedClientProtocols == (SslProtocols.Tls11 | SslProtocols.Tls12) && acceptedServerProtocols == SslProtocols.Tls) { // Native WinHTTP sometimes uses multiple TCP connections to try other TLS protocols when // getting TLS protocol failures as part of its TLS fallback algorithm. The loopback server // doesn't expect this and stops listening for more connections. This causes unexpected test // failures. See dotnet/corefx #8538. return; } using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.SslProtocols = allowedClientProtocols; handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedServerProtocols }; await LoopbackServer.CreateServerAsync(async (server, url) => { Task serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); try { await serverTask; } catch (Exception e) when (e is IOException || e is AuthenticationException) { // Some SSL implementations simply close or reset connection after protocol mismatch. // Newer OpenSSL sends Fatal Alert message before closing. return; } // We expect negotiation to fail so one or the other expected exception should be thrown. Assert.True(false, "Expected exception did not happen."); }, options); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal partial class CSharpCodeModelService { public override string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags) { Debug.Assert(symbol != null); if (node == null) { switch (symbol.Kind) { case SymbolKind.Field: return GetVariablePrototype((IFieldSymbol)symbol, flags); case SymbolKind.Method: return GetFunctionPrototype((IMethodSymbol)symbol, flags); case SymbolKind.Property: return GetPropertyPrototype((IPropertySymbol)symbol, flags); case SymbolKind.Event: return GetEventPrototype((IEventSymbol)symbol, flags); case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)symbol; if (namedType.TypeKind == TypeKind.Delegate) { return GetDelegatePrototype((INamedTypeSymbol)symbol, flags); } break; } Debug.Fail("Invalid symbol kind: " + symbol.Kind); throw Exceptions.ThrowEUnexpected(); } else { var methodDeclaration = node as BaseMethodDeclarationSyntax; if (methodDeclaration != null) { return GetFunctionPrototype(methodDeclaration, (IMethodSymbol)symbol, flags); } var propertyDeclaration = node as BasePropertyDeclarationSyntax; if (propertyDeclaration != null) { return GetPropertyPrototype(propertyDeclaration, (IPropertySymbol)symbol, flags); } var variableDeclarator = node as VariableDeclaratorSyntax; if (variableDeclarator != null && symbol.Kind == SymbolKind.Field) { return GetVariablePrototype(variableDeclarator, (IFieldSymbol)symbol, flags); } var enumMember = node as EnumMemberDeclarationSyntax; if (enumMember != null) { return GetVariablePrototype(enumMember, (IFieldSymbol)symbol, flags); } var delegateDeclaration = node as DelegateDeclarationSyntax; if (delegateDeclaration != null) { return GetDelegatePrototype(delegateDeclaration, (INamedTypeSymbol)symbol, flags); } // Crazily, events for source are not implemented by the legacy C# // code model implementation, but they are for metadata events. Debug.Fail(string.Format("Invalid node/symbol kind: {0}/{1}", node.Kind(), symbol.Kind)); throw Exceptions.ThrowENotImpl(); } } private string GetDelegatePrototype(INamedTypeSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. // Note that we only throw E_FAIL in this case. All others throw E_INVALIDARG. throw Exceptions.ThrowEFail(); } // The unique signature is simply the node key. return GetFullName(symbol); } var builder = new StringBuilder(); AppendDelegatePrototype(builder, symbol, flags, symbol.Name); return builder.ToString(); } private string GetDelegatePrototype(DelegateDeclarationSyntax node, INamedTypeSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. return GetNodeKey(node).Name; } var builder = new StringBuilder(); AppendDelegatePrototype(builder, symbol, flags, GetName(node)); return builder.ToString(); } private string GetEventPrototype(IEventSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. flags = PrototypeFlags.FullName | PrototypeFlags.Type; } var builder = new StringBuilder(); AppendEventPrototype(builder, symbol, flags, symbol.Name); return builder.ToString(); } private string GetFunctionPrototype(IMethodSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. flags = PrototypeFlags.FullName | PrototypeFlags.Type | PrototypeFlags.ParameterTypes; } var builder = new StringBuilder(); AppendFunctionPrototype(builder, symbol, flags, symbol.Name); return builder.ToString(); } private string GetFunctionPrototype(BaseMethodDeclarationSyntax node, IMethodSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. return GetNodeKey(node).Name; } var builder = new StringBuilder(); AppendFunctionPrototype(builder, symbol, flags, GetName(node)); return builder.ToString(); } private string GetPropertyPrototype(IPropertySymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. flags = PrototypeFlags.FullName | PrototypeFlags.Type; } var builder = new StringBuilder(); AppendPropertyPrototype(builder, symbol, flags, symbol.Name); return builder.ToString(); } private string GetPropertyPrototype(BasePropertyDeclarationSyntax node, IPropertySymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. return GetNodeKey(node).Name; } var builder = new StringBuilder(); AppendPropertyPrototype(builder, symbol, flags, GetName(node)); return builder.ToString(); } private string GetVariablePrototype(IFieldSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. flags = PrototypeFlags.FullName | PrototypeFlags.Type; } var builder = new StringBuilder(); AppendVariablePrototype(builder, symbol, flags, symbol.Name); return builder.ToString(); } private string GetVariablePrototype(VariableDeclaratorSyntax node, IFieldSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. return GetNodeKey(node).Name; } var builder = new StringBuilder(); AppendVariablePrototype(builder, symbol, flags, GetName(node)); if ((flags & PrototypeFlags.Initializer) != 0 && node.Initializer != null && node.Initializer.Value != null && !node.Initializer.Value.IsMissing) { builder.Append(" = "); builder.Append(node.Initializer.Value); } return builder.ToString(); } private string GetVariablePrototype(EnumMemberDeclarationSyntax node, IFieldSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. return GetNodeKey(node).Name; } var builder = new StringBuilder(); AppendVariablePrototype(builder, symbol, flags, GetName(node)); if ((flags & PrototypeFlags.Initializer) != 0 && node.EqualsValue != null && node.EqualsValue.Value != null && !node.EqualsValue.Value.IsMissing) { builder.Append(" = "); builder.Append(node.EqualsValue.Value); } return builder.ToString(); } private void AppendDelegatePrototype(StringBuilder builder, INamedTypeSymbol symbol, PrototypeFlags flags, string baseName) { builder.Append("delegate "); if ((flags & PrototypeFlags.Type) != 0) { builder.Append(GetAsStringForCodeTypeRef(symbol.DelegateInvokeMethod.ReturnType)); if (((flags & PrototypeFlags.NameMask) != PrototypeFlags.NoName) || ((flags & (PrototypeFlags.ParameterNames | PrototypeFlags.ParameterTypes)) != 0)) { builder.Append(' '); } } var addSpace = true; switch (flags & PrototypeFlags.NameMask) { case PrototypeFlags.FullName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: false, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.TypeName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: true, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.BaseName: builder.Append(baseName); break; case PrototypeFlags.NoName: addSpace = false; break; } if ((flags & (PrototypeFlags.ParameterNames | PrototypeFlags.ParameterTypes)) != 0) { if (addSpace) { builder.Append(' '); } builder.Append('('); AppendParametersPrototype(builder, symbol.DelegateInvokeMethod.Parameters, flags); builder.Append(')'); } } private void AppendEventPrototype(StringBuilder builder, IEventSymbol symbol, PrototypeFlags flags, string baseName) { if ((flags & PrototypeFlags.Type) != 0) { builder.Append(GetAsStringForCodeTypeRef(symbol.Type)); if ((flags & PrototypeFlags.NameMask) != PrototypeFlags.NoName) { builder.Append(' '); } } switch (flags & PrototypeFlags.NameMask) { case PrototypeFlags.FullName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: false, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.TypeName: AppendTypeNamePrototype(builder, includeNamespaces: false, includeGenerics: true, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.BaseName: builder.Append(baseName); break; } } private void AppendFunctionPrototype(StringBuilder builder, IMethodSymbol symbol, PrototypeFlags flags, string baseName) { if ((flags & PrototypeFlags.Type) != 0) { builder.Append(GetAsStringForCodeTypeRef(symbol.ReturnType)); if ((flags & PrototypeFlags.NameMask) != PrototypeFlags.NoName) { builder.Append(' '); } } var addSpace = true; switch (flags & PrototypeFlags.NameMask) { case PrototypeFlags.FullName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: false, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.TypeName: AppendTypeNamePrototype(builder, includeNamespaces: false, includeGenerics: true, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.BaseName: builder.Append(baseName); break; case PrototypeFlags.NoName: addSpace = false; break; } if ((flags & (PrototypeFlags.ParameterNames | PrototypeFlags.ParameterTypes)) != 0) { if (addSpace) { builder.Append(' '); } builder.Append('('); AppendParametersPrototype(builder, symbol.Parameters, flags); builder.Append(')'); } } private void AppendPropertyPrototype(StringBuilder builder, IPropertySymbol symbol, PrototypeFlags flags, string baseName) { if ((flags & PrototypeFlags.Type) != 0) { builder.Append(GetAsStringForCodeTypeRef(symbol.Type)); if ((flags & PrototypeFlags.NameMask) != PrototypeFlags.NoName) { builder.Append(' '); } } switch (flags & PrototypeFlags.NameMask) { case PrototypeFlags.FullName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: false, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.TypeName: AppendTypeNamePrototype(builder, includeNamespaces: false, includeGenerics: true, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.BaseName: if (symbol.IsIndexer) { builder.Append("this["); AppendParametersPrototype(builder, symbol.Parameters, PrototypeFlags.ParameterTypes | PrototypeFlags.ParameterNames); builder.Append("]"); } else { builder.Append(baseName); } break; } } private void AppendVariablePrototype(StringBuilder builder, IFieldSymbol symbol, PrototypeFlags flags, string baseName) { if ((flags & PrototypeFlags.Type) != 0) { builder.Append(GetAsStringForCodeTypeRef(symbol.Type)); if ((flags & PrototypeFlags.NameMask) != PrototypeFlags.NoName) { builder.Append(' '); } } switch (flags & PrototypeFlags.NameMask) { case PrototypeFlags.FullName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: false, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.TypeName: AppendTypeNamePrototype(builder, includeNamespaces: false, includeGenerics: true, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.BaseName: builder.Append(baseName); break; } } private void AppendParametersPrototype(StringBuilder builder, ImmutableArray<IParameterSymbol> parameters, PrototypeFlags flags) { var first = true; foreach (var parameter in parameters) { if (!first) { builder.Append(", "); } AppendParameterPrototype(builder, flags, parameter); first = false; } } private void AppendParameterPrototype(StringBuilder builder, PrototypeFlags flags, IParameterSymbol parameter) { var addSpace = false; if ((flags & PrototypeFlags.ParameterTypes) != 0) { if (parameter.RefKind == RefKind.Ref) { builder.Append("ref "); } else if (parameter.RefKind == RefKind.Out) { builder.Append("out "); } else if (parameter.IsParams) { builder.Append("params "); } builder.Append(GetAsStringForCodeTypeRef(parameter.Type)); addSpace = true; } if ((flags & PrototypeFlags.ParameterNames) != 0) { if (addSpace) { builder.Append(' '); } builder.Append(parameter.Name); } } private static void AppendTypeNamePrototype(StringBuilder builder, bool includeNamespaces, bool includeGenerics, ISymbol symbol) { var symbols = new Stack<ISymbol>(); while (symbol != null) { if (symbol.Kind == SymbolKind.Namespace) { if (!includeNamespaces || ((INamespaceSymbol)symbol).IsGlobalNamespace) { break; } } symbols.Push(symbol); symbol = symbol.ContainingSymbol; } var first = true; while (symbols.Count > 0) { var current = symbols.Pop(); if (!first) { builder.Append('.'); } builder.Append(current.Name); if (current.Kind == SymbolKind.NamedType) { var namedType = (INamedTypeSymbol)current; if (includeGenerics && namedType.Arity > 0) { builder.Append('<'); builder.Append(',', namedType.Arity - 1); builder.Append('>'); } } first = false; } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.AccessApproval.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedAccessApprovalServiceClientSnippets { /// <summary>Snippet for ListApprovalRequests</summary> public void ListApprovalRequestsRequestObject() { // Snippet: ListApprovalRequests(ListApprovalRequestsMessage, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) ListApprovalRequestsMessage request = new ListApprovalRequestsMessage { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Filter = "", }; // Make the request PagedEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequests(request); // Iterate over all response items, lazily performing RPCs as required foreach (ApprovalRequest item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListApprovalRequestsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ApprovalRequest item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ApprovalRequest> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ApprovalRequest item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListApprovalRequestsAsync</summary> public async Task ListApprovalRequestsRequestObjectAsync() { // Snippet: ListApprovalRequestsAsync(ListApprovalRequestsMessage, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) ListApprovalRequestsMessage request = new ListApprovalRequestsMessage { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Filter = "", }; // Make the request PagedAsyncEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequestsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ApprovalRequest item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListApprovalRequestsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ApprovalRequest item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ApprovalRequest> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ApprovalRequest item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListApprovalRequests</summary> public void ListApprovalRequests() { // Snippet: ListApprovalRequests(string, string, int?, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; // Make the request PagedEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequests(parent); // Iterate over all response items, lazily performing RPCs as required foreach (ApprovalRequest item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListApprovalRequestsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ApprovalRequest item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ApprovalRequest> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ApprovalRequest item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListApprovalRequestsAsync</summary> public async Task ListApprovalRequestsAsync() { // Snippet: ListApprovalRequestsAsync(string, string, int?, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; // Make the request PagedAsyncEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequestsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ApprovalRequest item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListApprovalRequestsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ApprovalRequest item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ApprovalRequest> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ApprovalRequest item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListApprovalRequests</summary> public void ListApprovalRequestsResourceNames1() { // Snippet: ListApprovalRequests(ProjectName, string, int?, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); // Make the request PagedEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequests(parent); // Iterate over all response items, lazily performing RPCs as required foreach (ApprovalRequest item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListApprovalRequestsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ApprovalRequest item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ApprovalRequest> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ApprovalRequest item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListApprovalRequestsAsync</summary> public async Task ListApprovalRequestsResourceNames1Async() { // Snippet: ListApprovalRequestsAsync(ProjectName, string, int?, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequestsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ApprovalRequest item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListApprovalRequestsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ApprovalRequest item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ApprovalRequest> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ApprovalRequest item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListApprovalRequests</summary> public void ListApprovalRequestsResourceNames2() { // Snippet: ListApprovalRequests(FolderName, string, int?, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) FolderName parent = FolderName.FromFolder("[FOLDER]"); // Make the request PagedEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequests(parent); // Iterate over all response items, lazily performing RPCs as required foreach (ApprovalRequest item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListApprovalRequestsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ApprovalRequest item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ApprovalRequest> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ApprovalRequest item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListApprovalRequestsAsync</summary> public async Task ListApprovalRequestsResourceNames2Async() { // Snippet: ListApprovalRequestsAsync(FolderName, string, int?, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) FolderName parent = FolderName.FromFolder("[FOLDER]"); // Make the request PagedAsyncEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequestsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ApprovalRequest item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListApprovalRequestsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ApprovalRequest item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ApprovalRequest> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ApprovalRequest item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListApprovalRequests</summary> public void ListApprovalRequestsResourceNames3() { // Snippet: ListApprovalRequests(OrganizationName, string, int?, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) OrganizationName parent = OrganizationName.FromOrganization("[ORGANIZATION]"); // Make the request PagedEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequests(parent); // Iterate over all response items, lazily performing RPCs as required foreach (ApprovalRequest item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListApprovalRequestsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ApprovalRequest item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ApprovalRequest> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ApprovalRequest item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListApprovalRequestsAsync</summary> public async Task ListApprovalRequestsResourceNames3Async() { // Snippet: ListApprovalRequestsAsync(OrganizationName, string, int?, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) OrganizationName parent = OrganizationName.FromOrganization("[ORGANIZATION]"); // Make the request PagedAsyncEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequestsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ApprovalRequest item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListApprovalRequestsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ApprovalRequest item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ApprovalRequest> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ApprovalRequest item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetApprovalRequest</summary> public void GetApprovalRequestRequestObject() { // Snippet: GetApprovalRequest(GetApprovalRequestMessage, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) GetApprovalRequestMessage request = new GetApprovalRequestMessage { ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"), }; // Make the request ApprovalRequest response = accessApprovalServiceClient.GetApprovalRequest(request); // End snippet } /// <summary>Snippet for GetApprovalRequestAsync</summary> public async Task GetApprovalRequestRequestObjectAsync() { // Snippet: GetApprovalRequestAsync(GetApprovalRequestMessage, CallSettings) // Additional: GetApprovalRequestAsync(GetApprovalRequestMessage, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) GetApprovalRequestMessage request = new GetApprovalRequestMessage { ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"), }; // Make the request ApprovalRequest response = await accessApprovalServiceClient.GetApprovalRequestAsync(request); // End snippet } /// <summary>Snippet for GetApprovalRequest</summary> public void GetApprovalRequest() { // Snippet: GetApprovalRequest(string, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/approvalRequests/[APPROVAL_REQUEST]"; // Make the request ApprovalRequest response = accessApprovalServiceClient.GetApprovalRequest(name); // End snippet } /// <summary>Snippet for GetApprovalRequestAsync</summary> public async Task GetApprovalRequestAsync() { // Snippet: GetApprovalRequestAsync(string, CallSettings) // Additional: GetApprovalRequestAsync(string, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/approvalRequests/[APPROVAL_REQUEST]"; // Make the request ApprovalRequest response = await accessApprovalServiceClient.GetApprovalRequestAsync(name); // End snippet } /// <summary>Snippet for GetApprovalRequest</summary> public void GetApprovalRequestResourceNames() { // Snippet: GetApprovalRequest(ApprovalRequestName, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) ApprovalRequestName name = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"); // Make the request ApprovalRequest response = accessApprovalServiceClient.GetApprovalRequest(name); // End snippet } /// <summary>Snippet for GetApprovalRequestAsync</summary> public async Task GetApprovalRequestResourceNamesAsync() { // Snippet: GetApprovalRequestAsync(ApprovalRequestName, CallSettings) // Additional: GetApprovalRequestAsync(ApprovalRequestName, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) ApprovalRequestName name = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"); // Make the request ApprovalRequest response = await accessApprovalServiceClient.GetApprovalRequestAsync(name); // End snippet } /// <summary>Snippet for ApproveApprovalRequest</summary> public void ApproveApprovalRequestRequestObject() { // Snippet: ApproveApprovalRequest(ApproveApprovalRequestMessage, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) ApproveApprovalRequestMessage request = new ApproveApprovalRequestMessage { ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"), ExpireTime = new Timestamp(), }; // Make the request ApprovalRequest response = accessApprovalServiceClient.ApproveApprovalRequest(request); // End snippet } /// <summary>Snippet for ApproveApprovalRequestAsync</summary> public async Task ApproveApprovalRequestRequestObjectAsync() { // Snippet: ApproveApprovalRequestAsync(ApproveApprovalRequestMessage, CallSettings) // Additional: ApproveApprovalRequestAsync(ApproveApprovalRequestMessage, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) ApproveApprovalRequestMessage request = new ApproveApprovalRequestMessage { ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"), ExpireTime = new Timestamp(), }; // Make the request ApprovalRequest response = await accessApprovalServiceClient.ApproveApprovalRequestAsync(request); // End snippet } /// <summary>Snippet for DismissApprovalRequest</summary> public void DismissApprovalRequestRequestObject() { // Snippet: DismissApprovalRequest(DismissApprovalRequestMessage, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) DismissApprovalRequestMessage request = new DismissApprovalRequestMessage { ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"), }; // Make the request ApprovalRequest response = accessApprovalServiceClient.DismissApprovalRequest(request); // End snippet } /// <summary>Snippet for DismissApprovalRequestAsync</summary> public async Task DismissApprovalRequestRequestObjectAsync() { // Snippet: DismissApprovalRequestAsync(DismissApprovalRequestMessage, CallSettings) // Additional: DismissApprovalRequestAsync(DismissApprovalRequestMessage, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) DismissApprovalRequestMessage request = new DismissApprovalRequestMessage { ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"), }; // Make the request ApprovalRequest response = await accessApprovalServiceClient.DismissApprovalRequestAsync(request); // End snippet } /// <summary>Snippet for GetAccessApprovalSettings</summary> public void GetAccessApprovalSettingsRequestObject() { // Snippet: GetAccessApprovalSettings(GetAccessApprovalSettingsMessage, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) GetAccessApprovalSettingsMessage request = new GetAccessApprovalSettingsMessage { AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"), }; // Make the request AccessApprovalSettings response = accessApprovalServiceClient.GetAccessApprovalSettings(request); // End snippet } /// <summary>Snippet for GetAccessApprovalSettingsAsync</summary> public async Task GetAccessApprovalSettingsRequestObjectAsync() { // Snippet: GetAccessApprovalSettingsAsync(GetAccessApprovalSettingsMessage, CallSettings) // Additional: GetAccessApprovalSettingsAsync(GetAccessApprovalSettingsMessage, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) GetAccessApprovalSettingsMessage request = new GetAccessApprovalSettingsMessage { AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"), }; // Make the request AccessApprovalSettings response = await accessApprovalServiceClient.GetAccessApprovalSettingsAsync(request); // End snippet } /// <summary>Snippet for GetAccessApprovalSettings</summary> public void GetAccessApprovalSettings() { // Snippet: GetAccessApprovalSettings(string, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/accessApprovalSettings"; // Make the request AccessApprovalSettings response = accessApprovalServiceClient.GetAccessApprovalSettings(name); // End snippet } /// <summary>Snippet for GetAccessApprovalSettingsAsync</summary> public async Task GetAccessApprovalSettingsAsync() { // Snippet: GetAccessApprovalSettingsAsync(string, CallSettings) // Additional: GetAccessApprovalSettingsAsync(string, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/accessApprovalSettings"; // Make the request AccessApprovalSettings response = await accessApprovalServiceClient.GetAccessApprovalSettingsAsync(name); // End snippet } /// <summary>Snippet for GetAccessApprovalSettings</summary> public void GetAccessApprovalSettingsResourceNames() { // Snippet: GetAccessApprovalSettings(AccessApprovalSettingsName, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) AccessApprovalSettingsName name = AccessApprovalSettingsName.FromProject("[PROJECT]"); // Make the request AccessApprovalSettings response = accessApprovalServiceClient.GetAccessApprovalSettings(name); // End snippet } /// <summary>Snippet for GetAccessApprovalSettingsAsync</summary> public async Task GetAccessApprovalSettingsResourceNamesAsync() { // Snippet: GetAccessApprovalSettingsAsync(AccessApprovalSettingsName, CallSettings) // Additional: GetAccessApprovalSettingsAsync(AccessApprovalSettingsName, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) AccessApprovalSettingsName name = AccessApprovalSettingsName.FromProject("[PROJECT]"); // Make the request AccessApprovalSettings response = await accessApprovalServiceClient.GetAccessApprovalSettingsAsync(name); // End snippet } /// <summary>Snippet for UpdateAccessApprovalSettings</summary> public void UpdateAccessApprovalSettingsRequestObject() { // Snippet: UpdateAccessApprovalSettings(UpdateAccessApprovalSettingsMessage, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) UpdateAccessApprovalSettingsMessage request = new UpdateAccessApprovalSettingsMessage { Settings = new AccessApprovalSettings(), UpdateMask = new FieldMask(), }; // Make the request AccessApprovalSettings response = accessApprovalServiceClient.UpdateAccessApprovalSettings(request); // End snippet } /// <summary>Snippet for UpdateAccessApprovalSettingsAsync</summary> public async Task UpdateAccessApprovalSettingsRequestObjectAsync() { // Snippet: UpdateAccessApprovalSettingsAsync(UpdateAccessApprovalSettingsMessage, CallSettings) // Additional: UpdateAccessApprovalSettingsAsync(UpdateAccessApprovalSettingsMessage, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) UpdateAccessApprovalSettingsMessage request = new UpdateAccessApprovalSettingsMessage { Settings = new AccessApprovalSettings(), UpdateMask = new FieldMask(), }; // Make the request AccessApprovalSettings response = await accessApprovalServiceClient.UpdateAccessApprovalSettingsAsync(request); // End snippet } /// <summary>Snippet for UpdateAccessApprovalSettings</summary> public void UpdateAccessApprovalSettings() { // Snippet: UpdateAccessApprovalSettings(AccessApprovalSettings, FieldMask, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) AccessApprovalSettings settings = new AccessApprovalSettings(); FieldMask updateMask = new FieldMask(); // Make the request AccessApprovalSettings response = accessApprovalServiceClient.UpdateAccessApprovalSettings(settings, updateMask); // End snippet } /// <summary>Snippet for UpdateAccessApprovalSettingsAsync</summary> public async Task UpdateAccessApprovalSettingsAsync() { // Snippet: UpdateAccessApprovalSettingsAsync(AccessApprovalSettings, FieldMask, CallSettings) // Additional: UpdateAccessApprovalSettingsAsync(AccessApprovalSettings, FieldMask, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) AccessApprovalSettings settings = new AccessApprovalSettings(); FieldMask updateMask = new FieldMask(); // Make the request AccessApprovalSettings response = await accessApprovalServiceClient.UpdateAccessApprovalSettingsAsync(settings, updateMask); // End snippet } /// <summary>Snippet for DeleteAccessApprovalSettings</summary> public void DeleteAccessApprovalSettingsRequestObject() { // Snippet: DeleteAccessApprovalSettings(DeleteAccessApprovalSettingsMessage, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) DeleteAccessApprovalSettingsMessage request = new DeleteAccessApprovalSettingsMessage { AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"), }; // Make the request accessApprovalServiceClient.DeleteAccessApprovalSettings(request); // End snippet } /// <summary>Snippet for DeleteAccessApprovalSettingsAsync</summary> public async Task DeleteAccessApprovalSettingsRequestObjectAsync() { // Snippet: DeleteAccessApprovalSettingsAsync(DeleteAccessApprovalSettingsMessage, CallSettings) // Additional: DeleteAccessApprovalSettingsAsync(DeleteAccessApprovalSettingsMessage, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) DeleteAccessApprovalSettingsMessage request = new DeleteAccessApprovalSettingsMessage { AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"), }; // Make the request await accessApprovalServiceClient.DeleteAccessApprovalSettingsAsync(request); // End snippet } /// <summary>Snippet for DeleteAccessApprovalSettings</summary> public void DeleteAccessApprovalSettings() { // Snippet: DeleteAccessApprovalSettings(string, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/accessApprovalSettings"; // Make the request accessApprovalServiceClient.DeleteAccessApprovalSettings(name); // End snippet } /// <summary>Snippet for DeleteAccessApprovalSettingsAsync</summary> public async Task DeleteAccessApprovalSettingsAsync() { // Snippet: DeleteAccessApprovalSettingsAsync(string, CallSettings) // Additional: DeleteAccessApprovalSettingsAsync(string, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/accessApprovalSettings"; // Make the request await accessApprovalServiceClient.DeleteAccessApprovalSettingsAsync(name); // End snippet } /// <summary>Snippet for DeleteAccessApprovalSettings</summary> public void DeleteAccessApprovalSettingsResourceNames() { // Snippet: DeleteAccessApprovalSettings(AccessApprovalSettingsName, CallSettings) // Create client AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create(); // Initialize request argument(s) AccessApprovalSettingsName name = AccessApprovalSettingsName.FromProject("[PROJECT]"); // Make the request accessApprovalServiceClient.DeleteAccessApprovalSettings(name); // End snippet } /// <summary>Snippet for DeleteAccessApprovalSettingsAsync</summary> public async Task DeleteAccessApprovalSettingsResourceNamesAsync() { // Snippet: DeleteAccessApprovalSettingsAsync(AccessApprovalSettingsName, CallSettings) // Additional: DeleteAccessApprovalSettingsAsync(AccessApprovalSettingsName, CancellationToken) // Create client AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync(); // Initialize request argument(s) AccessApprovalSettingsName name = AccessApprovalSettingsName.FromProject("[PROJECT]"); // Make the request await accessApprovalServiceClient.DeleteAccessApprovalSettingsAsync(name); // End snippet } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace RestOfUs.Api.WebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Linq; using CppSharp.AST; using CppSharp.AST.Extensions; using CppSharp.Generators.CSharp; using CppSharp.Passes; using NUnit.Framework; namespace CppSharp.Generator.Tests.AST { [TestFixture] public class TestAST : ASTTestFixture { [OneTimeSetUp] public void Init() { CppSharp.AST.Type.TypePrinterDelegate = type => { PrimitiveType primitiveType; return type.IsPrimitiveType(out primitiveType) ? primitiveType.ToString() : string.Empty; }; ParseLibrary("AST.h", "ASTExtensions.h"); } [OneTimeTearDown] public void CleanUp() { ParserOptions.Dispose(); } [Test] public void TestASTParameter() { var func = AstContext.FindFunction("TestParameterProperties").FirstOrDefault(); Assert.IsNotNull(func); var paramNames = new[] { "a", "b", "c" }; var paramTypes = new[] { new QualifiedType(new BuiltinType(PrimitiveType.Bool)), new QualifiedType( new PointerType() { Modifier = PointerType.TypeModifier.LVReference, QualifiedPointee = new QualifiedType( new BuiltinType(PrimitiveType.Short), new TypeQualifiers { IsConst = true }) }), new QualifiedType( new PointerType { Modifier = PointerType.TypeModifier.Pointer, QualifiedPointee = new QualifiedType(new BuiltinType(PrimitiveType.Int)) }) }; for (int i = 0; i < func.Parameters.Count; i++) { var param = func.Parameters[i]; Assert.AreEqual(paramNames[i], param.Name, "Parameter.Name"); Assert.AreEqual(paramTypes[i], param.QualifiedType, "Parameter.QualifiedType"); Assert.AreEqual(i, param.Index, "Parameter.Index"); } Assert.IsTrue(func.Parameters[2].HasDefaultValue, "Parameter.HasDefaultValue"); } [Test] public void TestASTHelperMethods() { var @class = AstContext.FindClass("Math::Complex").FirstOrDefault(); Assert.IsNotNull(@class, "Couldn't find Math::Complex class."); var plusOperator = @class.FindOperator(CXXOperatorKind.Plus).FirstOrDefault(); Assert.IsNotNull(plusOperator, "Couldn't find operator+ in Math::Complex class."); var typedef = AstContext.FindTypedef("Math::Single").FirstOrDefault(); Assert.IsNotNull(typedef); } #region TestVisitor class TestVisitor : IDeclVisitor<bool> { public bool VisitDeclaration(Declaration decl) { throw new System.NotImplementedException(); } public bool VisitTranslationUnit(TranslationUnit unit) { throw new System.NotImplementedException(); } public bool VisitClassDecl(Class @class) { throw new System.NotImplementedException(); } public bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecialization specialization) { throw new NotImplementedException(); } public bool VisitFieldDecl(Field field) { throw new System.NotImplementedException(); } public bool VisitFunctionDecl(Function function) { throw new System.NotImplementedException(); } public bool VisitMethodDecl(Method method) { return true; } public bool VisitParameterDecl(Parameter parameter) { throw new System.NotImplementedException(); } public bool VisitTypedefDecl(TypedefDecl typedef) { throw new System.NotImplementedException(); } public bool VisitTypeAliasDecl(TypeAlias typeAlias) { throw new NotImplementedException(); } public bool VisitEnumDecl(Enumeration @enum) { throw new System.NotImplementedException(); } public bool VisitEnumItemDecl(Enumeration.Item item) { throw new NotImplementedException(); } public bool VisitVariableDecl(Variable variable) { throw new System.NotImplementedException(); } public bool VisitClassTemplateDecl(ClassTemplate template) { throw new System.NotImplementedException(); } public bool VisitFunctionTemplateDecl(FunctionTemplate template) { throw new System.NotImplementedException(); } public bool VisitMacroDefinition(MacroDefinition macro) { throw new System.NotImplementedException(); } public bool VisitNamespace(Namespace @namespace) { throw new System.NotImplementedException(); } public bool VisitEvent(Event @event) { throw new System.NotImplementedException(); } public bool VisitProperty(Property property) { throw new System.NotImplementedException(); } public bool VisitFriend(Friend friend) { throw new System.NotImplementedException(); } public bool VisitTemplateParameterDecl(TypeTemplateParameter templateParameter) { throw new NotImplementedException(); } public bool VisitNonTypeTemplateParameterDecl(NonTypeTemplateParameter nonTypeTemplateParameter) { throw new NotImplementedException(); } public bool VisitTemplateTemplateParameterDecl(TemplateTemplateParameter templateTemplateParameter) { throw new NotImplementedException(); } public bool VisitTypeAliasTemplateDecl(TypeAliasTemplate typeAliasTemplate) { throw new NotImplementedException(); } public bool VisitFunctionTemplateSpecializationDecl(FunctionTemplateSpecialization specialization) { throw new NotImplementedException(); } public bool VisitVarTemplateDecl(VarTemplate template) { throw new NotImplementedException(); } public bool VisitVarTemplateSpecializationDecl(VarTemplateSpecialization template) { throw new NotImplementedException(); } public bool VisitTypedefNameDecl(TypedefNameDecl typedef) { throw new NotImplementedException(); } } #endregion [Test] public void TestASTVisitor() { var testVisitor = new TestVisitor(); var plusOperator = AstContext.TranslationUnits .SelectMany(u => u.Namespaces.Where(n => n.Name == "Math")) .SelectMany(n => n.Classes.Where(c => c.Name == "Complex")) .SelectMany(c => c.Methods.Where(m => m.OperatorKind == CXXOperatorKind.Plus)) .First(); Assert.IsTrue(plusOperator.Visit(testVisitor)); } [Test] public void TestASTEnumItemByName() { var @enum = AstContext.FindEnum("TestASTEnumItemByName").Single(); Assert.NotNull(@enum); Assert.IsTrue(@enum.ItemsByName.ContainsKey("TestItemByName")); } [Test] public void TestASTFunctionTemplates() { var @class = AstContext.FindClass("TestTemplateFunctions").FirstOrDefault(); Assert.IsNotNull(@class, "Couldn't find TestTemplateFunctions class."); Assert.AreEqual(6, @class.Templates.Count); var twoParamMethodTemplate = @class.Templates.OfType<FunctionTemplate>() .FirstOrDefault(t => t.Name == "MethodTemplateWithTwoTypeParameter"); Assert.IsNotNull(twoParamMethodTemplate); Assert.AreEqual(2, twoParamMethodTemplate.Parameters.Count); Assert.AreEqual("T", twoParamMethodTemplate.Parameters[0].Name); Assert.AreEqual("S", twoParamMethodTemplate.Parameters[1].Name); var twoParamMethod = twoParamMethodTemplate.TemplatedFunction as Method; Assert.IsNotNull(twoParamMethod); Assert.IsInstanceOf<TemplateParameterType>(twoParamMethod.Parameters[0].Type); Assert.IsInstanceOf<TemplateParameterType>(twoParamMethod.Parameters[1].Type); Assert.AreEqual(twoParamMethodTemplate.Parameters[0], ((TemplateParameterType) twoParamMethod.Parameters[0].Type).Parameter); Assert.AreEqual(twoParamMethodTemplate.Parameters[1], ((TemplateParameterType) twoParamMethod.Parameters[1].Type).Parameter); Assert.AreEqual(0, ((TemplateParameterType) twoParamMethod.Parameters[0].Type).Index); Assert.AreEqual(1, ((TemplateParameterType) twoParamMethod.Parameters[1].Type).Index); } [Test] public void TestASTClassTemplates() { var template = AstContext.TranslationUnits .SelectMany(u => u.Templates.OfType<ClassTemplate>()) .FirstOrDefault(t => t.Name == "TestTemplateClass"); Assert.IsNotNull(template, "Couldn't find TestTemplateClass class."); Assert.AreEqual(1, template.Parameters.Count); var templateTypeParameter = template.Parameters[0]; Assert.AreEqual("T", templateTypeParameter.Name); var ctor = template.TemplatedClass.Constructors .FirstOrDefault(c => c.Parameters.Count == 1 && c.Parameters[0].Name == "v"); Assert.IsNotNull(ctor); var paramType = ctor.Parameters[0].Type as TemplateParameterType; Assert.IsNotNull(paramType); Assert.AreEqual(templateTypeParameter, paramType.Parameter); Assert.AreEqual(5, template.Specializations.Count); Assert.AreEqual(TemplateSpecializationKind.ExplicitInstantiationDefinition, template.Specializations[0].SpecializationKind); Assert.AreEqual(TemplateSpecializationKind.ExplicitInstantiationDefinition, template.Specializations[3].SpecializationKind); Assert.AreEqual(TemplateSpecializationKind.Undeclared, template.Specializations[4].SpecializationKind); var typeDef = AstContext.FindTypedef("TestTemplateClassInt").FirstOrDefault(); Assert.IsNotNull(typeDef, "Couldn't find TestTemplateClassInt typedef."); var integerInst = typeDef.Type as TemplateSpecializationType; Assert.AreEqual(1, integerInst.Arguments.Count); var intArgument = integerInst.Arguments[0]; Assert.AreEqual(new BuiltinType(PrimitiveType.Int), intArgument.Type.Type); ClassTemplateSpecialization classTemplateSpecialization; Assert.IsTrue(typeDef.Type.TryGetDeclaration(out classTemplateSpecialization)); Assert.AreSame(classTemplateSpecialization.TemplatedDecl.TemplatedClass, template.TemplatedClass); } [Test] public void TestFindClassInNamespace() { Assert.IsNotNull(AstContext.FindClass("HiddenInNamespace").FirstOrDefault()); } [Test] public void TestLineNumber() { Assert.AreEqual(70, AstContext.FindClass("HiddenInNamespace").First().LineNumberStart); } [Test] public void TestLineNumberOfFriend() { Assert.AreEqual(93, AstContext.FindFunction("operator+").First().LineNumberStart); } static string StripWindowsNewLines(string text) { return text.ReplaceLineBreaks(string.Empty); } [Test] public void TestSignature() { Assert.AreEqual("void testSignature()", AstContext.FindFunction("testSignature").Single().Signature); Assert.AreEqual("void testImpl(){}", StripWindowsNewLines(AstContext.FindFunction("testImpl").Single().Signature)); Assert.AreEqual("void testConstSignature() const", AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstSignature").Signature); Assert.AreEqual("void testConstSignatureWithTrailingMacro() const", AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstSignatureWithTrailingMacro").Signature); // TODO: restore when the const of a return type is fixed properly //Assert.AreEqual("const int& testConstRefSignature()", AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstRefSignature").Signature); //Assert.AreEqual("const int& testStaticConstRefSignature()", AstContext.FindClass("HasConstFunction").Single().FindMethod("testStaticConstRefSignature").Signature); } [Test] public void TestAmbiguity() { new CheckAmbiguousFunctions { Context = Driver.Context }.VisitASTContext(AstContext); Assert.IsTrue(AstContext.FindClass("HasAmbiguousFunctions").Single().FindMethod("ambiguous").IsAmbiguous); } [Test] public void TestAtomics() { var type = AstContext.FindClass("Atomics").Single().Fields .Find(f => f.Name == "AtomicInt").Type as BuiltinType; Assert.IsTrue(type != null && type.IsPrimitiveType(PrimitiveType.Int)); } [Test] public void TestMacroLineNumber() { Assert.AreEqual(103, AstContext.FindClass("HasAmbiguousFunctions").First().Specifiers.Last().LineNumberStart); } [Test] public void TestImplicitDeclaration() { Assert.IsTrue(AstContext.FindClass("ImplicitCtor").First().Constructors.First( c => c.Parameters.Count == 0).IsImplicit); } [Test] public void TestSpecializationArguments() { var classTemplate = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").FirstOrDefault(); Assert.IsTrue(classTemplate.Specializations[0].Arguments[0].Type.Type.IsPrimitiveType(PrimitiveType.Int)); } [Test] public void TestFunctionInstantiatedFrom() { var classTemplate = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").FirstOrDefault(); Assert.AreEqual(classTemplate.Specializations[0].Constructors.First( c => !c.IsCopyConstructor && !c.IsMoveConstructor).InstantiatedFrom, classTemplate.TemplatedClass.Constructors.First(c => !c.IsCopyConstructor && !c.IsMoveConstructor)); } [Test] public void TestComments() { var @class = AstContext.FindCompleteClass("TestComments"); var commentClass = @class.Comment.FullComment.CommentToString(CommentKind.BCPLSlash); Assert.AreEqual(@"/// <summary> /// <para>Hash set/map base class.</para> /// <para>Note that to prevent extra memory use due to vtable pointer, %HashBase intentionally does not declare a virtual destructor</para> /// <para>and therefore %HashBase pointers should never be used.</para> /// </summary>".Replace("\r", string.Empty), commentClass.Replace("\r", string.Empty)); var method = @class.Methods.First(m => m.Name == "GetIOHandlerControlSequence"); var commentMethod = method.Comment.FullComment.CommentToString(CommentKind.BCPL); Assert.AreEqual(@"// <summary> // <para>Get the string that needs to be written to the debugger stdin file</para> // <para>handle when a control character is typed.</para> // </summary> // <param name=""ch"">The character that was typed along with the control key</param> // <returns> // <para>The string that should be written into the file handle that is</para> // <para>feeding the input stream for the debugger, or NULL if there is</para> // <para>no string for this control key.</para> // </returns> // <remarks> // <para>Some GUI programs will intercept &quot;control + char&quot; sequences and want</para> // <para>to have them do what normally would happen when using a real</para> // <para>terminal, so this function allows GUI programs to emulate this</para> // <para>functionality.</para> // </remarks>".Replace("\r", string.Empty), commentMethod.Replace("\r", string.Empty)); var methodTestDoxygen = @class.Methods.First(m => m.Name == "SBAttachInfo"); var commentMethodDoxygen = methodTestDoxygen.Comment.FullComment.CommentToString(CommentKind.BCPLSlash); Assert.AreEqual(@"/// <summary>Attach to a process by name.</summary> /// <param name=""path"">A full or partial name for the process to attach to.</param> /// <param name=""wait_for""> /// <para>If <c>false,</c> attach to an existing process whose name matches.</para> /// <para>If <c>true,</c> then wait for the next process whose name matches.</para> /// </param> /// <remarks> /// <para>This function implies that a future call to SBTarget::Attach(...)</para> /// <para>will be synchronous.</para> /// </remarks>".Replace("\r", string.Empty), commentMethodDoxygen.Replace("\r", string.Empty)); var methodDoxygenCustomTags = @class.Methods.First(m => m.Name == "glfwDestroyWindow"); new CleanCommentsPass { }.VisitFull(methodDoxygenCustomTags.Comment.FullComment); var commentMethodDoxygenCustomTag = methodDoxygenCustomTags.Comment.FullComment.CommentToString(CommentKind.BCPLSlash); Assert.AreEqual(@"/// <summary>Destroys the specified window and its context.</summary> /// <param name=""window"">The window to destroy.</param> /// <remarks> /// <para>This function destroys the specified window and its context. On calling</para> /// <para>this function, no further callbacks will be called for that window.</para> /// <para>If the context of the specified window is current on the main thread, it is</para> /// <para>detached before being destroyed.</para> /// <para>The context of the specified window must not be current on any other</para> /// <para>thread when this function is called.</para> /// <para>This function must not be called from a callback.</para> /// <para>This function must only be called from the main thread.</para> /// <para>Added in version 3.0. Replaces `glfwCloseWindow`.</para> /// </remarks>".Replace("\r", string.Empty), commentMethodDoxygenCustomTag.Replace("\r", string.Empty)); } [Test] public void TestCompletionOfClassTemplates() { var templates = AstContext.FindDecl<ClassTemplate>("ForwardedTemplate").ToList(); var template = templates.Single(t => t.DebugText.Replace("\r", string.Empty) == "template <typename T>\r\nclass ForwardedTemplate\r\n{\r\n}".Replace("\r", string.Empty)); Assert.IsFalse(template.IsIncomplete); } [Test] public void TestOriginalNamesOfSpecializations() { var template = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").First(); Assert.That(template.Specializations[0].Constructors.First().QualifiedName, Is.Not.EqualTo(template.Specializations[1].Constructors.First().QualifiedName)); } [Test] public void TestPrintingConstPointerWithConstType() { var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified }; var builtin = new BuiltinType(PrimitiveType.Char); var pointee = new QualifiedType(builtin, new TypeQualifiers { IsConst = true }); var pointer = new QualifiedType(new PointerType(pointee), new TypeQualifiers { IsConst = true }); var type = pointer.Visit(cppTypePrinter); Assert.That(type, Is.EqualTo("const char* const")); } [Test] public void TestPrintingSpecializationWithConstValue() { var template = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").First(); var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified }; Assert.That(template.Specializations.Last().Visit(cppTypePrinter), Is.EqualTo("TestSpecializationArguments<const TestASTEnumItemByName>")); } [Test] public void TestLayoutBase() { var @class = AstContext.FindCompleteClass("TestComments"); Assert.That(@class.Layout.Bases.Count, Is.EqualTo(0)); } [Test] public void TestFunctionSpecifications() { var constExprNoExcept = AstContext.FindFunction("constExprNoExcept").First(); Assert.IsTrue(constExprNoExcept.IsConstExpr); var functionType = (FunctionType) constExprNoExcept.FunctionType.Type; Assert.That(functionType.ExceptionSpecType, Is.EqualTo(ExceptionSpecType.BasicNoexcept)); var regular = AstContext.FindFunction("testSignature").First(); Assert.IsFalse(regular.IsConstExpr); var regularFunctionType = (FunctionType) regular.FunctionType.Type; Assert.That(regularFunctionType.ExceptionSpecType, Is.EqualTo(ExceptionSpecType.None)); } [Test] public void TestFunctionSpecializationInfo() { var functionWithSpecInfo = AstContext.FindFunction( "functionWithSpecInfo").First(f => !f.IsDependent); var @float = new QualifiedType(new BuiltinType(PrimitiveType.Float)); Assert.That(functionWithSpecInfo.SpecializationInfo.Arguments.Count, Is.EqualTo(2)); foreach (var arg in functionWithSpecInfo.SpecializationInfo.Arguments) Assert.That(arg.Type, Is.EqualTo(@float)); } [Test] public void TestVolatile() { var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified }; var builtin = new BuiltinType(PrimitiveType.Char); var pointee = new QualifiedType(builtin, new TypeQualifiers { IsConst = true, IsVolatile = true }); var type = pointee.Visit(cppTypePrinter); Assert.That(type, Is.EqualTo("const volatile char")); } [Test] public void TestFindFunctionInNamespace() { var function = AstContext.FindFunction("Math::function").FirstOrDefault(); Assert.That(function, Is.Not.Null); } [Test] public void TestPrintNestedInSpecialization() { var template = AstContext.FindDecl<ClassTemplate>("TestTemplateClass").First(); var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified }; Assert.That(template.Specializations[3].Classes[0].Visit(cppTypePrinter), Is.EqualTo("TestTemplateClass<Math::Complex>::NestedInTemplate")); } [Test] public void TestPrintQualifiedSpecialization() { var functionWithSpecializationArg = AstContext.FindFunction("functionWithSpecializationArg").First(); var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified }; Assert.That(functionWithSpecializationArg.Parameters[0].Visit(cppTypePrinter), Is.EqualTo("const TestTemplateClass<int>")); } [Test] public void TestDependentNameType() { var template = AstContext.FindDecl<ClassTemplate>( "TestSpecializationArguments").First(); var type = template.TemplatedClass.Fields[0].Type.Visit( new CSharpTypePrinter(Driver.Context)); Assert.That($"{type}", Is.EqualTo("global::Test.TestTemplateClass<T>.NestedInTemplate")); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ListOperator.cs" company="PropertyTools"> // Copyright (c) 2014 PropertyTools contributors // </copyright> // <summary> // Represents an operator for DataGrid when its ItemsSource is of IList. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace PropertyTools.Wpf { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Data; /// <summary> /// Represents an operator for <see cref="DataGrid" /> when its ItemsSource is of type <see cref="IList" />. /// </summary> public class ListOperator : DataGridOperator { /// <summary> /// Initializes a new instance of the <see cref="ListOperator"/> class. /// </summary> /// <param name="owner">The owner.</param> public ListOperator(DataGrid owner) : base(owner) { } /// <summary> /// Generate column definitions based on a list of items. /// </summary> /// <param name="list">The list of items.</param> /// <returns>A sequence of column definitions.</returns> /// <remarks>The constraint is that all the items in the ItemsSource's should be of the same type. /// For non built in type, a /// <code>public static T Parse(string s, IFormatProvider formatProvider)</code> and /// <code>public string ToString(string format, IFormatProvider formatProvider)</code> should be defined. /// interface type is not acceptable for no object instance can be created based on it.</remarks> protected override IEnumerable<ColumnDefinition> GenerateColumnDefinitions(IList list) { if (list == null) { yield break; } // Strategy 1: get properties from IItemProperties var view = CollectionViewSource.GetDefaultView(list); var itemPropertiesView = view as IItemProperties; if (itemPropertiesView?.ItemProperties != null && itemPropertiesView.ItemProperties.Count > 0) { foreach (var info in itemPropertiesView.ItemProperties) { var descriptor = info.Descriptor as PropertyDescriptor; if (descriptor == null || !descriptor.IsBrowsable) { continue; } var cd = new ColumnDefinition { PropertyName = descriptor.Name, Header = info.Name, HorizontalAlignment = this.DefaultHorizontalAlignment, Width = this.DefaultColumnWidth }; yield return cd; } yield break; } // Strategy 2: get properties from type descriptor var itemType = this.GetItemType(list); var properties = TypeDescriptor.GetProperties(itemType); if (properties.Count == 0) { // Otherwise try to get the property descriptors from an instance properties = GetPropertiesFromInstance(list, itemType); } if (properties.Count > 0) { foreach (PropertyDescriptor descriptor in properties) { if (!descriptor.IsBrowsable) { continue; } var cd = new ColumnDefinition { PropertyName = descriptor.Name, Header = descriptor.Name, HorizontalAlignment = this.DefaultHorizontalAlignment, Width = this.DefaultColumnWidth }; yield return cd; } yield break; } // Strategy 3: create a single column var itemsType = this.GetItemType(list); yield return new ColumnDefinition { Header = itemsType.Name, HorizontalAlignment = this.DefaultHorizontalAlignment, Width = this.DefaultColumnWidth }; } /// <summary> /// Gets the item in cell. /// </summary> /// <param name="cell">The cell reference.</param> /// <returns> /// The item <see cref="object" />. /// </returns> public override object GetItem(CellRef cell) { var list = this.Owner.ItemsSource; if (list == null) { return null; } var index = this.GetItemIndex(cell); if (index >= 0 && index < list.Count) { return list[index]; } return null; } /// <summary> /// Inserts item to <see cref="DataGrid" />. /// </summary> /// <param name="index">The index.</param> /// <returns> /// The index of the inserted item if insertion is successful, <c>-1</c> otherwise. /// </returns> public override int InsertItem(int index) { var list = this.Owner.ItemsSource; if (list == null) { return -1; } var itemType = this.GetItemType(list); try { var newItem = this.CreateItem(itemType); if (index < 0) { index = list.Add(newItem); } else { list.Insert(index, newItem); } return index; } catch { return -1; } } /// <summary> /// Sets value to item in cell. /// </summary> /// <param name="cell">The cell reference.</param> /// <param name="value">The value.</param> public override void SetValue(CellRef cell, object value) { var list = this.Owner.ItemsSource; if (list == null || cell.Column < 0 || cell.Row < 0) { return; } var index = this.GetItemIndex(cell); list[index] = value; } /// <summary> /// Gets the item index for the specified cell. /// </summary> /// <param name="cell">The cell.</param> /// <returns> /// The get item index. /// </returns> protected virtual int GetItemIndex(CellRef cell) { var index = this.Owner.ItemsInRows ? cell.Row : cell.Column; return this.GetItemsSourceIndex(index); } /// <summary> /// Gets the binding path for the specified cell. /// </summary> /// <param name="cell">The cell.</param> /// <returns> /// The binding path /// </returns> public override string GetBindingPath(CellRef cell) { var pd = this.GetPropertyDefinition(cell); if (pd?.PropertyName != null) { return pd.PropertyName; } var index = this.GetItemIndex(cell); return $"[{index}]"; } /// <summary> /// Gets property descriptors from one instance. /// </summary> /// <param name="items">The items.</param> /// <param name="itemType">The target item type.</param> /// <returns> /// The <see cref="PropertyDescriptorCollection" />. /// </returns> private static PropertyDescriptorCollection GetPropertiesFromInstance(IList items, Type itemType) { foreach (var item in items) { if (item != null && item.GetType() == itemType) { return TypeDescriptor.GetProperties(item); } } return new PropertyDescriptorCollection(new PropertyDescriptor[0]); } } }
using Harvest.Net.Models; using System; using System.Threading.Tasks; using RestSharp; namespace Harvest.Net { public partial class HarvestRestClient { // https://github.com/harvesthq/api/blob/master/Sections/Time%20Tracking.md /// <summary> /// List all time entries logged by the current user for a given day of the year. Makes a GET request to the Daily resource. /// </summary> /// <param name="dayOfTheYear">The day of the year to list (1-366). If null, lists today.</param> /// <param name="year">The year to list. If null, lists today.</param> /// <param name="ofUser">The user the day entry belongs to</param> public Daily Daily(short? dayOfTheYear = null, short? year = null, long? ofUser = null) { var request = DailyRequest(dayOfTheYear, year, ofUser); return Execute<Daily>(request); } /// <summary> /// List all time entries logged by the current user for a given day of the year. Makes a GET request to the Daily resource. /// </summary> /// <param name="dayOfTheYear">The day of the year to list (1-366). If null, lists today.</param> /// <param name="year">The year to list. If null, lists today.</param> /// <param name="ofUser">The user the day entry belongs to</param> public Task<Daily> DailyAsync(short? dayOfTheYear = null, short? year = null, long? ofUser = null) { var request = DailyRequest(dayOfTheYear, year, ofUser); return ExecuteAsync<Daily>(request); } /// <summary> /// Retrieve a single day entry by ID. Makes a GET request to the Daily/Show resource. /// </summary> /// <param name="dayEntryId">The ID of the day entry to retrieve</param> /// <param name="ofUser">The user the day entry belongs to</param> public Timer Daily(long dayEntryId, long? ofUser = null) { var request = DailyRequest(dayEntryId, ofUser); return Execute<Timer>(request); } /// <summary> /// Retrieve a single day entry by ID. Makes a GET request to the Daily/Show resource. /// </summary> /// <param name="dayEntryId">The ID of the day entry to retrieve</param> /// <param name="ofUser">The user the day entry belongs to</param> public Task<Timer> DailyAsync(long dayEntryId, long? ofUser = null) { var request = DailyRequest(dayEntryId, ofUser); return ExecuteAsync<Timer>(request); } /// <summary> /// Toggles a single day entry timer by ID. Makes a GET request to the Daily/Timer resource. /// </summary> /// <param name="dayEntryId">The ID of the day entry to retrieve</param> /// <param name="ofUser">The user the day entry belongs to</param> public Timer ToggleDaily(long dayEntryId, long? ofUser = null) { var request = ToggleDailyRequest(dayEntryId, ofUser); return Execute<Timer>(request); } /// <summary> /// Toggles a single day entry timer by ID. Makes a GET request to the Daily/Timer resource. /// </summary> /// <param name="dayEntryId">The ID of the day entry to retrieve</param> /// <param name="ofUser">The user the day entry belongs to</param> public Task<Timer> ToggleDailyAsync(long dayEntryId, long? ofUser = null) { var request = ToggleDailyRequest(dayEntryId, ofUser); return ExecuteAsync<Timer>(request); } /// <summary> /// Create a new time entry for the logged in user. Makes a POST request to the Daily/Add resource. /// </summary> /// <param name="spentAt">The date of the entry</param> /// <param name="projectId">The project ID for the entry</param> /// <param name="taskId">The task ID for the entry</param> /// <param name="hours">The hours on the entry</param> /// <param name="notes">The notes on the entry</param> /// <param name="ofUser">The user the day entry belongs to</param> public Timer CreateDaily(DateTime spentAt, long projectId, long taskId, decimal hours, string notes = null, long? ofUser = null) { var options = GetCreateDailyOptions(spentAt, projectId, taskId, hours, notes); return CreateDaily(options, ofUser); } /// <summary> /// Create a new time entry for the logged in user. Makes a POST request to the Daily/Add resource. /// </summary> /// <param name="spentAt">The date of the entry</param> /// <param name="projectId">The project ID for the entry</param> /// <param name="taskId">The task ID for the entry</param> /// <param name="hours">The hours on the entry</param> /// <param name="notes">The notes on the entry</param> /// <param name="ofUser">The user the day entry belongs to</param> public Task<Timer> CreateDailyAsync(DateTime spentAt, long projectId, long taskId, decimal hours, string notes = null, long? ofUser = null) { var options = GetCreateDailyOptions(spentAt, projectId, taskId, hours, notes); return CreateDailyAsync(options, ofUser); } /// <summary> /// Create a new time entry for the logged in user. Makes a POST request to the Daily/Add resource. /// </summary> /// <param name="spentAt">The date of the entry</param> /// <param name="projectId">The project ID for the entry</param> /// <param name="taskId">The task ID for the entry</param> /// <param name="startedAt">The start timestamp of the entry</param> /// <param name="endedAt">The end timestamp of the entry</param> /// <param name="notes">The notes on the entry</param> /// <param name="ofUser">The user the day entry belongs to</param> public Timer CreateDaily(DateTime spentAt, long projectId, long taskId, TimeSpan startedAt, TimeSpan endedAt, string notes = null, long? ofUser = null) { var options = GetCreateDailyOptions(spentAt, projectId, taskId, startedAt, endedAt, notes); return CreateDaily(options, ofUser); } /// <summary> /// Create a new time entry for the logged in user. Makes a POST request to the Daily/Add resource. /// </summary> /// <param name="spentAt">The date of the entry</param> /// <param name="projectId">The project ID for the entry</param> /// <param name="taskId">The task ID for the entry</param> /// <param name="startedAt">The start timestamp of the entry</param> /// <param name="endedAt">The end timestamp of the entry</param> /// <param name="notes">The notes on the entry</param> /// <param name="ofUser">The user the day entry belongs to</param> public Task<Timer> CreateDailyAsync(DateTime spentAt, long projectId, long taskId, TimeSpan startedAt, TimeSpan endedAt, string notes = null, long? ofUser = null) { var options = GetCreateDailyOptions(spentAt, projectId, taskId, startedAt, endedAt, notes); return CreateDailyAsync(options, ofUser); } /// <summary> /// Starts a new timer for the logged in user. Makes a POST request to the Daily/Add resource. /// </summary> /// <param name="spentAt">The date of the entry</param> /// <param name="projectId">The project ID for the entry</param> /// <param name="taskId">The task ID for the entry</param> /// <param name="notes">The notes on the entry</param> /// <param name="ofUser">The user the day entry belongs to</param> public Timer StartTimer(DateTime spentAt, long projectId, long taskId, string notes = null, long? ofUser = null) { var options = GetStartTimerOptions(spentAt, projectId, taskId, notes); return CreateDaily(options, ofUser); } /// <summary> /// Starts a new timer for the logged in user. Makes a POST request to the Daily/Add resource. /// </summary> /// <param name="spentAt">The date of the entry</param> /// <param name="projectId">The project ID for the entry</param> /// <param name="taskId">The task ID for the entry</param> /// <param name="notes">The notes on the entry</param> /// <param name="ofUser">The user the day entry belongs to</param> public Task<Timer> StartTimerAsync(DateTime spentAt, long projectId, long taskId, string notes = null, long? ofUser = null) { var options = GetStartTimerOptions(spentAt, projectId, taskId, notes); return CreateDailyAsync(options, ofUser); } /// <summary> /// Create a new time entry for the logged in user. Makes a POST request to the Daily/Add resource. /// </summary> /// <param name="options">The options for the time entry</param> /// <param name="ofUser">The user the day entry belongs to</param> internal Timer CreateDaily(DailyOptions options, long? ofUser) { var request = CreateDailyRequest(options, ofUser); return Execute<Timer>(request); } /// <summary> /// Create a new time entry for the logged in user. Makes a POST request to the Daily/Add resource. /// </summary> /// <param name="options">The options for the time entry</param> /// <param name="ofUser">The user the day entry belongs to</param> internal Task<Timer> CreateDailyAsync(DailyOptions options, long? ofUser) { var request = CreateDailyRequest(options, ofUser); return ExecuteAsync<Timer>(request); } /// <summary> /// Delete a day entry for the logged in user. Makes a DELETE request tot he Daily/Delete resource. /// </summary> /// <param name="dayEntryId">The ID of the day entry to delete</param> /// <param name="ofUser">The user the day entry belongs to</param> public bool DeleteDaily(long dayEntryId, long? ofUser = null) { var request = DeleteDailyRequest(dayEntryId, ofUser); var result = Execute(request); return result.StatusCode == System.Net.HttpStatusCode.OK; } /// <summary> /// Delete a day entry for the logged in user. Makes a DELETE request tot he Daily/Delete resource. /// </summary> /// <param name="dayEntryId">The ID of the day entry to delete</param> /// <param name="ofUser">The user the day entry belongs to</param> public async Task<bool> DeleteDailyAsync(long dayEntryId, long? ofUser = null) { var request = DeleteDailyRequest(dayEntryId, ofUser); var result = await ExecuteAsync(request).ConfigureAwait(false); return result.StatusCode == System.Net.HttpStatusCode.OK; } /// <summary> /// Update a time entry for the logged in user. Makes a POST request to the Daily/Update resource. /// </summary> /// <param name="dayEntryId">The ID of the time entry to update</param> /// <param name="spentAt">The new date of the entry</param> /// <param name="projectId">The new project ID of the entry</param> /// <param name="taskId">The new task ID of the entry</param> /// <param name="hours">The new hours for the entry</param> /// <param name="startedAt">The new start timestamp for the entry</param> /// <param name="endedAt">The new end timestamp for the entry</param> /// <param name="notes">The new notes for the entry</param> /// <param name="ofUser">The user the entry belongs to</param> public Timer UpdateDaily(long dayEntryId, DateTime? spentAt = null, long? projectId = null, long? taskId = null, decimal? hours = null, TimeSpan? startedAt = null, TimeSpan? endedAt = null, string notes = null, long? ofUser = null) { var options = GetUpdateDailyOptions(spentAt, projectId, taskId, hours, startedAt, endedAt, notes); return UpdateDaily(dayEntryId, options, ofUser); } /// <summary> /// Update a time entry for the logged in user. Makes a POST request to the Daily/Update resource. /// </summary> /// <param name="dayEntryId">The ID of the time entry to update</param> /// <param name="spentAt">The new date of the entry</param> /// <param name="projectId">The new project ID of the entry</param> /// <param name="taskId">The new task ID of the entry</param> /// <param name="hours">The new hours for the entry</param> /// <param name="startedAt">The new start timestamp for the entry</param> /// <param name="endedAt">The new end timestamp for the entry</param> /// <param name="notes">The new notes for the entry</param> /// <param name="ofUser">The user the entry belongs to</param> public Task<Timer> UpdateDailyAsync(long dayEntryId, DateTime? spentAt = null, long? projectId = null, long? taskId = null, decimal? hours = null, TimeSpan? startedAt = null, TimeSpan? endedAt = null, string notes = null, long? ofUser = null) { var options = GetUpdateDailyOptions(spentAt, projectId, taskId, hours, startedAt, endedAt, notes); return UpdateDailyAsync(dayEntryId, options, ofUser); } /// <summary> /// Update a time entry for the logged in user. Makes a POST request to the Daily/Update resource. /// </summary> /// <param name="dayEntryId">The ID of the entry to update</param> /// <param name="options">The options to update</param> /// <param name="ofUser">The user the entry belongs to</param> internal Timer UpdateDaily(long dayEntryId, DailyOptions options, long? ofUser) { var request = Request("daily/update/" + dayEntryId, Method.POST); if (ofUser != null) request.AddParameter("of_user", ofUser.Value); request.AddBody(options); return Execute<Timer>(request); } /// <summary> /// Update a time entry for the logged in user. Makes a POST request to the Daily/Update resource. /// </summary> /// <param name="dayEntryId">The ID of the entry to update</param> /// <param name="options">The options to update</param> /// <param name="ofUser">The user the entry belongs to</param> internal Task<Timer> UpdateDailyAsync(long dayEntryId, DailyOptions options, long? ofUser) { var request = Request("daily/update/" + dayEntryId, Method.POST); if (ofUser != null) request.AddParameter("of_user", ofUser.Value); request.AddBody(options); return ExecuteAsync<Timer>(request); } private IRestRequest DailyRequest(short? dayOfTheYear, short? year, long? ofUser) { if (year == null && dayOfTheYear != null) throw new ArgumentNullException(nameof(year), "You must provide both dayOfTheYear and year or neither."); if (year != null && dayOfTheYear == null) throw new ArgumentNullException(nameof(dayOfTheYear), "You must provide both dayOfYear and year or neither."); var request = Request("daily" + (dayOfTheYear != null ? "/" + dayOfTheYear + "/" + year : string.Empty)); if (ofUser != null) request.AddParameter("of_user", ofUser.Value); return request; } private IRestRequest DailyRequest(long dayEntryId, long? ofUser) { var request = Request("daily/show/" + dayEntryId); if (ofUser != null) request.AddParameter("of_user", ofUser.Value); return request; } private IRestRequest ToggleDailyRequest(long dayEntryId, long? ofUser) { var request = Request("daily/timer/" + dayEntryId); if (ofUser != null) request.AddParameter("of_user", ofUser.Value); return request; } private static DailyOptions GetCreateDailyOptions(DateTime spentAt, long projectId, long taskId, decimal hours, string notes) { return new DailyOptions { Notes = notes, SpentAt = spentAt, ProjectId = projectId, TaskId = taskId, Hours = hours.ToString("f2") }; } private static DailyOptions GetCreateDailyOptions(DateTime spentAt, long projectId, long taskId, TimeSpan startedAt, TimeSpan endedAt, string notes) { return new DailyOptions { Notes = notes, SpentAt = spentAt, ProjectId = projectId, TaskId = taskId, StartedAt = new DateTime(2000, 1, 1).Add(startedAt).ToString("h:mmtt").ToLower(), EndedAt = new DateTime(2000, 1, 1).Add(endedAt).ToString("h:mmtt").ToLower() }; } private static DailyOptions GetStartTimerOptions(DateTime spentAt, long projectId, long taskId, string notes) { return new DailyOptions { Notes = notes, SpentAt = spentAt, ProjectId = projectId, TaskId = taskId, Hours = " " }; } private IRestRequest CreateDailyRequest(DailyOptions options, long? ofUser) { var request = Request(ofUser != null ? $"daily/add?of_user={ofUser}" : "daily/add", Method.POST); request.AddBody(options); return request; } private IRestRequest DeleteDailyRequest(long dayEntryId, long? ofUser) { var request = Request("daily/delete/" + dayEntryId, Method.DELETE); if (ofUser != null) request.AddParameter("of_user", ofUser.Value); return request; } private static DailyOptions GetUpdateDailyOptions(DateTime? spentAt, long? projectId, long? taskId, decimal? hours, TimeSpan? startedAt, TimeSpan? endedAt, string notes) { var options = new DailyOptions { SpentAt = spentAt, ProjectId = projectId, TaskId = taskId, Notes = notes }; if (hours != null) options.Hours = hours.Value.ToString("f2"); if (startedAt != null) options.StartedAt = new DateTime(2000, 1, 1).Add(startedAt.Value).ToString("h:mmtt").ToLower(); if (endedAt != null) options.EndedAt = new DateTime(2000, 1, 1).Add(endedAt.Value).ToString("h:mmtt").ToLower(); return options; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using bv.common.Core; using bv.model.BLToolkit; using bv.model.Model.Core; using bv.winclient.BasePanel; using bv.winclient.Core; using bv.winclient.Layout; using eidss.model.Core; using eidss.model.Reports.Common; using eidss.model.Reports.OperationContext; using eidss.model.Reports.TH; using EIDSS.Reports.BaseControls.Filters; using EIDSS.Reports.BaseControls.Keeper; using EIDSS.Reports.BaseControls.Report; using EIDSS.Reports.Parameterized.Human.TH.Reports; namespace EIDSS.Reports.Parameterized.Human.TH.Keepers { public sealed partial class ComparativeSeveralYearsTHReportKeeper : BaseReportKeeper { private readonly ComponentResourceManager m_Resources = new ComponentResourceManager(typeof (ComparativeSeveralYearsTHReportKeeper)); private int m_YearFrom; private int m_YearTo; private bool m_IsThaiCulture; private string[] m_Diagnoses; private List<ItemWrapper> m_CounterCollection; public ComparativeSeveralYearsTHReportKeeper() : base(new Dictionary<string, string>()) { ReportType = typeof (ComparativeSeveralYearsTHReport); InitializeComponent(); using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting)) { SetMandatory(); DistrictFilter.DistrictVisibility = DistrictFilter.Visibility.ParentDistrictsOnly; m_YearFrom = DateTime.Now.Year - 1; m_YearTo = DateTime.Now.Year; ApplyYearResources(); CounterLookUp.EditValue = CounterCollection[0]; LayoutCorrector.SetStyleController(CounterLookUp, LayoutCorrector.MandatoryStyleController); } m_HasLoad = true; } #region Properties private int DeltaYear { get { return m_IsThaiCulture ? 543 : 0; } } private long? ProvinceIdParam { get { return ProvinceFilter.RegionId > 0 ? (long?) ProvinceFilter.RegionId : null; } } private long? DistrictIdParam { get { return DistrictFilter.DistrictId > 0 ? (long?) DistrictFilter.DistrictId : null; } } [Browsable(false)] private int CounterParam { get { return (CounterLookUp.EditValue == null) ? -1 : ((ItemWrapper)CounterLookUp.EditValue).Number; } } private List<ItemWrapper> CounterCollection { get { return m_CounterCollection ?? (m_CounterCollection = FilterHelper.GetWinCounterThaiList()); } } #endregion protected override BaseReport GenerateReport(DbManagerProxy manager, DbManagerProxy archiveManager) { if (WinUtils.IsComponentInDesignMode(this)) { return new BaseReport(); } var model = new ComparativeSeveralYearsTHSurrogateModel(CurrentCulture.ShortName, m_YearFrom, m_YearTo, m_Diagnoses,CounterParam, ProvinceIdParam, DistrictIdParam, ProvinceFilter.SelectedText, DistrictFilter.SelectedText, Convert.ToInt64(EidssUserContext.User.OrganizationID), EidssUserContext.User.ForbiddenPersonalDataGroups, UseArchive); var reportTh = (ComparativeSeveralYearsTHReport) CreateReportObject(); reportTh.SetParameters( model,manager,archiveManager); return reportTh; } protected internal override void ApplyResources(DbManagerProxy manager) { try { IsResourceLoading = true; m_HasLoad = false; base.ApplyResources(manager); m_Resources.ApplyResources(FromLabel, "FromLabel"); m_Resources.ApplyResources(ToLabel, "ToLabel"); ApplyYearResources(); DiagnosesFilter.DefineBinding(); ProvinceFilter.DefineBinding(); DistrictFilter.DefineBinding(); ProvinceFilter.Caption = m_Resources.GetString("ProvinceLabel.Text"); ApplyLookupResources(CounterLookUp, CounterCollection, CounterParam, CounterLabel.Text); if (ContextKeeper.ContainsContext(ContextValue.ReportKeeperFirstLoading)) { LocationHelper.SetDefaultFilters(manager, ContextKeeper, ProvinceFilter, DistrictFilter); } } finally { m_HasLoad = true; IsResourceLoading = false; } } private void ApplyYearResources() { using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting)) { m_IsThaiCulture = ModelUserContext.CurrentLanguage == Localizer.lngThai; YearFromSpinEdit.Properties.MaxValue = DeltaYear + DateTime.Now.Year - 1; YearFromSpinEdit.Properties.MinValue = m_IsThaiCulture ? 2550 : 2000; YearFromSpinEdit.Value = m_YearFrom + DeltaYear; YearToSpinEdit.Properties.MaxValue = DeltaYear + DateTime.Now.Year; YearToSpinEdit.Properties.MinValue = m_IsThaiCulture ? 2551 : 2001; YearToSpinEdit.Value = m_YearTo + DeltaYear; } } private void SetMandatory() { LayoutCorrector.SetStyleController(YearFromSpinEdit, LayoutCorrector.MandatoryStyleController); LayoutCorrector.SetStyleController(YearToSpinEdit, LayoutCorrector.MandatoryStyleController); } private void diagnosisFilter_ValueChanged(object sender, MultiFilterEventArgs e) { m_Diagnoses = e.KeyArray; } private void regionFilter_ValueChanged(object sender, SingleFilterEventArgs e) { using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting)) { LocationHelper.RegionFilterValueChanged(ProvinceFilter, DistrictFilter, e); } } private void rayonFilter_ValueChanged(object sender, SingleFilterEventArgs e) { using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting)) { LocationHelper.RayonFilterValueChanged(ProvinceFilter, DistrictFilter, e); } } private void seYear1_EditValueChanged(object sender, EventArgs e) { CorrectYearRange(); } private void seYear2_EditValueChanged(object sender, EventArgs e) { CorrectYearRange(); } private void CorrectYearRange() { if (!ContextKeeper.ContainsContext(ContextValue.ReportFilterResetting)) { if (YearToSpinEdit.Value <= YearFromSpinEdit.Value) { if (!BaseFormManager.IsReportsServiceRunning && !BaseFormManager.IsAvrServiceRunning) { ErrorForm.ShowWarning("msgComparativeReportTHCorrectYear", @"The Year selected in the ""To"" filter shall be greater than the Year selected in the ""From"" filter"); } YearFromSpinEdit.Value = m_YearFrom + DeltaYear; YearToSpinEdit.Value = m_YearTo + DeltaYear; } m_YearFrom = (int) YearFromSpinEdit.Value - DeltaYear; m_YearTo = (int) YearToSpinEdit.Value - DeltaYear; } } } }
//--------------------------------------------------------------------------- // // <copyright file="WindowsTitleBar.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Spinner Proxy // // History: // preid Created // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Text; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.ComponentModel; using MS.Win32; namespace MS.Internal.AutomationProxies { // the title bar contains the system menu, the context help, minimize, maximize and close buttons. // there is a win32 title bar contant for the ime button. There really is no such thing as an ims button // it's bogus. So when this code apears to by using 1 for the item for the system menu it will never // conflict because the ime button does not exist. class WindowsTitleBar: ProxyFragment { // ------------------------------------------------------ // // Constructors // // ------------------------------------------------------ #region Constructors public WindowsTitleBar (IntPtr hwnd, ProxyFragment parent, int item) : base( hwnd, parent, item ) { // Set the strings to return properly the properties. _cControlType = ControlType.TitleBar; _sAutomationId = "TitleBar"; // This string is a non-localizable string // _cControlType = ControlType.TitleBar; _fNonClientAreaElement = true; _fIsContent = false; } #endregion Constructors //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxySimple Interface /// Gets the bounding rectangle for this element internal override Rect BoundingRectangle { get { return Misc.GetTitleBarRect(_hwnd); } } /// Returns the Run Time Id. /// returns an array of ints as the concatenation of IDs internal override int [] GetRuntimeId () { return new int [] { 4, unchecked((int)(long)_hwnd), _item }; } //Gets the localized name internal override string LocalizedName { get { return Misc.ProxyGetText(_hwnd); } } #endregion #region ProxyFragment Interface /// Returns the next sibling element in the raw hierarchy. /// Peripheral controls have always negative values. /// Returns null if no next child. internal override ProxySimple GetNextSibling (ProxySimple child) { return ReturnNextTitleBarChild (true, child._item + 1); } /// Returns the previous sibling element in the raw hierarchy. /// Peripheral controls have always negative values. /// Returns null is no previous. internal override ProxySimple GetPreviousSibling (ProxySimple child) { return ReturnNextTitleBarChild (false, child._item - 1); } /// Returns the first child element in the raw hierarchy. internal override ProxySimple GetFirstChild () { return ReturnNextTitleBarChild (true, NativeMethods.INDEX_TITLEBAR_MIC); } /// Returns the last child element in the raw hierarchy. internal override ProxySimple GetLastChild () { return ReturnNextTitleBarChild (true, NativeMethods.INDEX_TITLEBAR_MAC); } /// Returns a Proxy element corresponding to the specified screen coordinates. internal override ProxySimple ElementProviderFromPoint (int x, int y) { int hit = Misc.ProxySendMessageInt(_hwnd, NativeMethods.WM_NCHITTEST, IntPtr.Zero, (IntPtr)NativeMethods.Util.MAKELONG(x, y)); switch (hit) { case NativeMethods.HTCAPTION: return this; case NativeMethods.HTMINBUTTON: return CreateTitleBarChild(NativeMethods.INDEX_TITLEBAR_MINBUTTON); case NativeMethods.HTMAXBUTTON : return CreateTitleBarChild(NativeMethods.INDEX_TITLEBAR_MAXBUTTON); case NativeMethods.HTHELP : return CreateTitleBarChild(NativeMethods.INDEX_TITLEBAR_HELPBUTTON); case NativeMethods.HTCLOSE : return CreateTitleBarChild(NativeMethods.INDEX_TITLEBAR_CLOSEBUTTON); case NativeMethods.HTSYSMENU : { // this gets us the system menu bar... WindowsMenu sysmenu = WindowsMenu.CreateSystemMenu(_hwnd, this); // now drill into the menu item... return sysmenu.CreateMenuItem(0); } } return null; } #endregion //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal static bool HasTitleBar (IntPtr hwnd) { return IsTitleBarVisible (hwnd); } internal ProxySimple CreateTitleBarChild (int item) { switch (item) { case _systemMenu: return WindowsMenu.CreateSystemMenu (_hwnd, this); case NativeMethods.INDEX_TITLEBAR_HELPBUTTON : case NativeMethods.INDEX_TITLEBAR_MINBUTTON : case NativeMethods.INDEX_TITLEBAR_MAXBUTTON : case NativeMethods.INDEX_TITLEBAR_CLOSEBUTTON : return new TitleBarButton (_hwnd, this, item); } return null; } #endregion Internal Methods //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal const int _systemMenu = 1; #endregion //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // Not all the titlebar children exist for every titlebar so this get the next one that exists private ProxySimple ReturnNextTitleBarChild (bool next, int start) { UnsafeNativeMethods.TITLEBARINFO ti; Misc.ProxyGetTitleBarInfo(_hwnd, out ti); ProxySimple el; for (int i = start; i >= NativeMethods.INDEX_TITLEBAR_MIC && i <= NativeMethods.INDEX_TITLEBAR_MAC; i += next ? 1 : -1) { // the system menu is taking the slot in the bogus IME button so it will allway be invisible // therefore make an exception for the system menu. if (!Misc.IsBitSet(ti.rgstate[i], NativeMethods.STATE_SYSTEM_INVISIBLE) || i == _systemMenu) { el = CreateTitleBarChild (i); if (el != null) return el; } } return null; } private static bool IsTitleBarVisible (IntPtr hwnd) { UnsafeNativeMethods.TITLEBARINFO ti; if (Misc.ProxyGetTitleBarInfo(hwnd, out ti)) { return !Misc.IsBitSet(ti.rgstate[0], NativeMethods.STATE_SYSTEM_INVISIBLE); } return false; } #endregion Private Methods //------------------------------------------------------ // // TitleBarButton Private Class // //------------------------------------------------------ #region TitleBarButton class TitleBarButton: ProxySimple, IInvokeProvider { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors public TitleBarButton (IntPtr hwnd, ProxyFragment parent, int item) : base( hwnd, parent, item) { _fNonClientAreaElement = true; _cControlType = ControlType.Button; _fIsContent = false; } #endregion //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxySimple Interface /// Returns a pattern interface if supported. internal override object GetPatternProvider (AutomationPattern iid) { if (iid == InvokePattern.Pattern) { return this; } return null; } /// Process all the Logical and Raw Element Properties internal override object GetElementProperty (AutomationProperty idProp) { if (idProp == AutomationElement.AutomationIdProperty) { switch (_item) { case NativeMethods.INDEX_TITLEBAR_HELPBUTTON: return "Help"; // This string is a non-localizable string case NativeMethods.INDEX_TITLEBAR_MINBUTTON: if (Misc.IsBitSet(WindowStyle, NativeMethods.WS_MINIMIZE)) { return "Restore"; // This string is a non-localizable string } else { return "Minimize"; // This string is a non-localizable string } case NativeMethods.INDEX_TITLEBAR_MAXBUTTON: if (Misc.IsBitSet(WindowStyle, NativeMethods.WS_MAXIMIZE)) { return "Restore"; // This string is a non-localizable string } else { return "Maximize"; // This string is a non-localizable string } case NativeMethods.INDEX_TITLEBAR_CLOSEBUTTON: return "Close"; // This string is a non-localizable string default: break; } } else if (idProp == AutomationElement.IsEnabledProperty) { switch (_item) { case NativeMethods.INDEX_TITLEBAR_HELPBUTTON: if (Misc.IsBitSet(WindowStyle, NativeMethods.WS_DISABLED)) { return false; } return Misc.IsBitSet(WindowExStyle, NativeMethods.WS_EX_CONTEXTHELP); case NativeMethods.INDEX_TITLEBAR_MINBUTTON: { int style = WindowStyle; if (Misc.IsBitSet(style, NativeMethods.WS_DISABLED)) { return false; } return Misc.IsBitSet(style, NativeMethods.WS_MINIMIZEBOX); } case NativeMethods.INDEX_TITLEBAR_MAXBUTTON: { int style = WindowStyle; if (Misc.IsBitSet(style, NativeMethods.WS_DISABLED)) { return false; } return Misc.IsBitSet(style, NativeMethods.WS_MAXIMIZEBOX); } } } return base.GetElementProperty (idProp); } // Gets the bounding rectangle for this element internal override Rect BoundingRectangle { get { Rect[] rects = Misc.GetTitlebarRects(_hwnd); return rects[_item]; } } //Gets the localized name internal override string LocalizedName { get { switch (_item) { case NativeMethods.INDEX_TITLEBAR_MINBUTTON: if (Misc.IsBitSet(WindowStyle, NativeMethods.WS_MINIMIZE)) return ST.Get(STID.LocalizedNameWindowsTitleBarButtonRestore); else return ST.Get(STID.LocalizedNameWindowsTitleBarButtonMinimize); case NativeMethods.INDEX_TITLEBAR_HELPBUTTON: return ST.Get(STID.LocalizedNameWindowsTitleBarButtonContextHelp); case NativeMethods.INDEX_TITLEBAR_MAXBUTTON: if (Misc.IsBitSet(WindowStyle, NativeMethods.WS_MAXIMIZE)) return ST.Get(STID.LocalizedNameWindowsTitleBarButtonRestore); else return ST.Get(STID.LocalizedNameWindowsTitleBarButtonMaximize); case NativeMethods.INDEX_TITLEBAR_CLOSEBUTTON: return ST.Get(STID.LocalizedNameWindowsTitleBarButtonClose); default: return ST.Get(STID.LocalizedNameWindowsTitleBarButtonUnknown); } } } #endregion #region Invoke Pattern /// Same effect as a click on one of the title bar button void IInvokeProvider.Invoke () { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } int command; switch (_item) { case NativeMethods.INDEX_TITLEBAR_MINBUTTON : if ((WindowStyle & NativeMethods.WS_MINIMIZE) != 0) command = NativeMethods.SC_RESTORE; else command = NativeMethods.SC_MINIMIZE; break; case NativeMethods.INDEX_TITLEBAR_HELPBUTTON : command = NativeMethods.SC_CONTEXTHELP; break; case NativeMethods.INDEX_TITLEBAR_MAXBUTTON : if ((WindowStyle & NativeMethods.WS_MAXIMIZE) != 0) command = NativeMethods.SC_RESTORE; else command = NativeMethods.SC_MAXIMIZE; break; case NativeMethods.INDEX_TITLEBAR_CLOSEBUTTON : if ((WindowStyle & NativeMethods.WS_MINIMIZE) != 0) { Misc.PostMessage(_hwnd, NativeMethods.WM_SYSCOMMAND, (IntPtr)NativeMethods.SC_RESTORE, IntPtr.Zero); } command = NativeMethods.SC_CLOSE; break; default : return; } // leave menu-mode if we're in it Misc.ClearMenuMode(); // push the right button Misc.PostMessage(_hwnd, NativeMethods.WM_SYSCOMMAND, (IntPtr)command, IntPtr.Zero); } #endregion } #endregion } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Asset Key Holders Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class AKKDataSet : EduHubDataSet<AKK> { /// <inheritdoc /> public override string Name { get { return "AKK"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal AKKDataSet(EduHubContext Context) : base(Context) { Index_CODE = new Lazy<Dictionary<string, IReadOnlyList<AKK>>>(() => this.ToGroupedDictionary(i => i.CODE)); Index_STAFF = new Lazy<NullDictionary<string, IReadOnlyList<AKK>>>(() => this.ToGroupedNullDictionary(i => i.STAFF)); Index_TID = new Lazy<Dictionary<int, AKK>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="AKK" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="AKK" /> fields for each CSV column header</returns> internal override Action<AKK, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<AKK, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "CODE": mapper[i] = (e, v) => e.CODE = v; break; case "STAFF": mapper[i] = (e, v) => e.STAFF = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="AKK" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="AKK" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="AKK" /> entities</param> /// <returns>A merged <see cref="IEnumerable{AKK}"/> of entities</returns> internal override IEnumerable<AKK> ApplyDeltaEntities(IEnumerable<AKK> Entities, List<AKK> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.CODE; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.CODE.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<AKK>>> Index_CODE; private Lazy<NullDictionary<string, IReadOnlyList<AKK>>> Index_STAFF; private Lazy<Dictionary<int, AKK>> Index_TID; #endregion #region Index Methods /// <summary> /// Find AKK by CODE field /// </summary> /// <param name="CODE">CODE value used to find AKK</param> /// <returns>List of related AKK entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<AKK> FindByCODE(string CODE) { return Index_CODE.Value[CODE]; } /// <summary> /// Attempt to find AKK by CODE field /// </summary> /// <param name="CODE">CODE value used to find AKK</param> /// <param name="Value">List of related AKK entities</param> /// <returns>True if the list of related AKK entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCODE(string CODE, out IReadOnlyList<AKK> Value) { return Index_CODE.Value.TryGetValue(CODE, out Value); } /// <summary> /// Attempt to find AKK by CODE field /// </summary> /// <param name="CODE">CODE value used to find AKK</param> /// <returns>List of related AKK entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<AKK> TryFindByCODE(string CODE) { IReadOnlyList<AKK> value; if (Index_CODE.Value.TryGetValue(CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find AKK by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find AKK</param> /// <returns>List of related AKK entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<AKK> FindBySTAFF(string STAFF) { return Index_STAFF.Value[STAFF]; } /// <summary> /// Attempt to find AKK by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find AKK</param> /// <param name="Value">List of related AKK entities</param> /// <returns>True if the list of related AKK entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySTAFF(string STAFF, out IReadOnlyList<AKK> Value) { return Index_STAFF.Value.TryGetValue(STAFF, out Value); } /// <summary> /// Attempt to find AKK by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find AKK</param> /// <returns>List of related AKK entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<AKK> TryFindBySTAFF(string STAFF) { IReadOnlyList<AKK> value; if (Index_STAFF.Value.TryGetValue(STAFF, out value)) { return value; } else { return null; } } /// <summary> /// Find AKK by TID field /// </summary> /// <param name="TID">TID value used to find AKK</param> /// <returns>Related AKK entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public AKK FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find AKK by TID field /// </summary> /// <param name="TID">TID value used to find AKK</param> /// <param name="Value">Related AKK entity</param> /// <returns>True if the related AKK entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out AKK Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find AKK by TID field /// </summary> /// <param name="TID">TID value used to find AKK</param> /// <returns>Related AKK entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public AKK TryFindByTID(int TID) { AKK value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a AKK table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[AKK]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[AKK]( [TID] int IDENTITY NOT NULL, [CODE] varchar(10) NOT NULL, [STAFF] varchar(4) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [AKK_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [AKK_Index_CODE] ON [dbo].[AKK] ( [CODE] ASC ); CREATE NONCLUSTERED INDEX [AKK_Index_STAFF] ON [dbo].[AKK] ( [STAFF] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AKK]') AND name = N'AKK_Index_STAFF') ALTER INDEX [AKK_Index_STAFF] ON [dbo].[AKK] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AKK]') AND name = N'AKK_Index_TID') ALTER INDEX [AKK_Index_TID] ON [dbo].[AKK] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AKK]') AND name = N'AKK_Index_STAFF') ALTER INDEX [AKK_Index_STAFF] ON [dbo].[AKK] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AKK]') AND name = N'AKK_Index_TID') ALTER INDEX [AKK_Index_TID] ON [dbo].[AKK] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="AKK"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="AKK"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<AKK> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[AKK] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the AKK data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the AKK data set</returns> public override EduHubDataSetDataReader<AKK> GetDataSetDataReader() { return new AKKDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the AKK data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the AKK data set</returns> public override EduHubDataSetDataReader<AKK> GetDataSetDataReader(List<AKK> Entities) { return new AKKDataReader(new EduHubDataSetLoadedReader<AKK>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class AKKDataReader : EduHubDataSetDataReader<AKK> { public AKKDataReader(IEduHubDataSetReader<AKK> Reader) : base (Reader) { } public override int FieldCount { get { return 6; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // CODE return Current.CODE; case 2: // STAFF return Current.STAFF; case 3: // LW_DATE return Current.LW_DATE; case 4: // LW_TIME return Current.LW_TIME; case 5: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // STAFF return Current.STAFF == null; case 3: // LW_DATE return Current.LW_DATE == null; case 4: // LW_TIME return Current.LW_TIME == null; case 5: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // CODE return "CODE"; case 2: // STAFF return "STAFF"; case 3: // LW_DATE return "LW_DATE"; case 4: // LW_TIME return "LW_TIME"; case 5: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "CODE": return 1; case "STAFF": return 2; case "LW_DATE": return 3; case "LW_TIME": return 4; case "LW_USER": return 5; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
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 SP.Cmd.Deploy { /// <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(10.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. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <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; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { 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. using System.Threading.Tasks; using System; using System.IO; using System.Text; using System.Xml.Schema; using System.Diagnostics; using System.Collections.Generic; using System.Globalization; using System.Runtime.Versioning; namespace System.Xml { // Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents // that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification. public abstract partial class XmlWriter : IDisposable { // Write methods // Writes out the XML declaration with the version "1.0". public virtual Task WriteStartDocumentAsync() { throw NotImplemented.ByDesign; } //Writes out the XML declaration with the version "1.0" and the speficied standalone attribute. public virtual Task WriteStartDocumentAsync(bool standalone) { throw NotImplemented.ByDesign; } //Closes any open elements or attributes and puts the writer back in the Start state. public virtual Task WriteEndDocumentAsync() { throw NotImplemented.ByDesign; } // Writes out the DOCTYPE declaration with the specified name and optional attributes. public virtual Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { throw NotImplemented.ByDesign; } // Writes out the specified start tag and associates it with the given namespace and prefix. public virtual Task WriteStartElementAsync(string prefix, string localName, string ns) { throw NotImplemented.ByDesign; } // Closes one element and pops the corresponding namespace scope. public virtual Task WriteEndElementAsync() { throw NotImplemented.ByDesign; } // Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>. public virtual Task WriteFullEndElementAsync() { throw NotImplemented.ByDesign; } // Writes out the attribute with the specified LocalName, value, and NamespaceURI. // Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value. public Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value) { Task task = WriteStartAttributeAsync(prefix, localName, ns); if (task.IsSuccess()) { return WriteStringAsync(value).CallTaskFuncWhenFinishAsync(thisRef => thisRef.WriteEndAttributeAsync(), this); } else { return WriteAttributeStringAsyncHelper(task, value); } } private async Task WriteAttributeStringAsyncHelper(Task task, string value) { await task.ConfigureAwait(false); await WriteStringAsync(value).ConfigureAwait(false); await WriteEndAttributeAsync().ConfigureAwait(false); } // Writes the start of an attribute. protected internal virtual Task WriteStartAttributeAsync(string prefix, string localName, string ns) { throw NotImplemented.ByDesign; } // Closes the attribute opened by WriteStartAttribute call. protected internal virtual Task WriteEndAttributeAsync() { throw NotImplemented.ByDesign; } // Writes out a <![CDATA[...]]>; block containing the specified text. public virtual Task WriteCDataAsync(string text) { throw NotImplemented.ByDesign; } // Writes out a comment <!--...-->; containing the specified text. public virtual Task WriteCommentAsync(string text) { throw NotImplemented.ByDesign; } // Writes out a processing instruction with a space between the name and text as follows: <?name text?> public virtual Task WriteProcessingInstructionAsync(string name, string text) { throw NotImplemented.ByDesign; } // Writes out an entity reference as follows: "&"+name+";". public virtual Task WriteEntityRefAsync(string name) { throw NotImplemented.ByDesign; } // Forces the generation of a character entity for the specified Unicode character value. public virtual Task WriteCharEntityAsync(char ch) { throw NotImplemented.ByDesign; } // Writes out the given whitespace. public virtual Task WriteWhitespaceAsync(string ws) { throw NotImplemented.ByDesign; } // Writes out the specified text content. public virtual Task WriteStringAsync(string text) { throw NotImplemented.ByDesign; } // Write out the given surrogate pair as an entity reference. public virtual Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { throw NotImplemented.ByDesign; } // Writes out the specified text content. public virtual Task WriteCharsAsync(char[] buffer, int index, int count) { throw NotImplemented.ByDesign; } // Writes raw markup from the given character buffer. public virtual Task WriteRawAsync(char[] buffer, int index, int count) { throw NotImplemented.ByDesign; } // Writes raw markup from the given string. public virtual Task WriteRawAsync(string data) { throw NotImplemented.ByDesign; } // Encodes the specified binary bytes as base64 and writes out the resulting text. public virtual Task WriteBase64Async(byte[] buffer, int index, int count) { throw NotImplemented.ByDesign; } // Encodes the specified binary bytes as binhex and writes out the resulting text. public virtual Task WriteBinHexAsync(byte[] buffer, int index, int count) { return BinHexEncoder.EncodeAsync(buffer, index, count, this); } // Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader. public virtual Task FlushAsync() { throw NotImplemented.ByDesign; } // Scalar Value Methods // Writes out the specified name, ensuring it is a valid NmToken according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual Task WriteNmTokenAsync(string name) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } return WriteStringAsync(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException)); } // Writes out the specified name, ensuring it is a valid Name according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual Task WriteNameAsync(string name) { return WriteStringAsync(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException)); } // Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace. public virtual async Task WriteQualifiedNameAsync(string localName, string ns) { if (ns != null && ns.Length > 0) { string prefix = LookupPrefix(ns); if (prefix == null) { throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns)); } await WriteStringAsync(prefix).ConfigureAwait(false); await WriteStringAsync(":").ConfigureAwait(false); } await WriteStringAsync(localName).ConfigureAwait(false); } // XmlReader Helper Methods // Writes out all the attributes found at the current position in the specified XmlReader. public virtual async Task WriteAttributesAsync(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException(nameof(reader)); } if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration) { if (reader.MoveToFirstAttribute()) { await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); reader.MoveToElement(); } } else if (reader.NodeType != XmlNodeType.Attribute) { throw new XmlException(SR.Xml_InvalidPosition, string.Empty); } else { do { // we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault. // If either of these is true and defattr=false, we should not write the attribute out if (defattr || !reader.IsDefaultInternal) { await WriteStartAttributeAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); while (reader.ReadAttributeValue()) { if (reader.NodeType == XmlNodeType.EntityReference) { await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); } else { await WriteStringAsync(reader.Value).ConfigureAwait(false); } } await WriteEndAttributeAsync().ConfigureAwait(false); } } while (reader.MoveToNextAttribute()); } } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. public virtual Task WriteNodeAsync(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException(nameof(reader)); } if (reader.Settings != null && reader.Settings.Async) { return WriteNodeAsync_CallAsyncReader(reader, defattr); } else { return WriteNodeAsync_CallSyncReader(reader, defattr); } } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. //use sync methods on the reader internal async Task WriteNodeAsync_CallSyncReader(XmlReader reader, bool defattr) { bool canReadChunk = reader.CanReadValueChunk; int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth; do { switch (reader.NodeType) { case XmlNodeType.Element: await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); if (reader.IsEmptyElement) { await WriteEndElementAsync().ConfigureAwait(false); break; } break; case XmlNodeType.Text: if (canReadChunk) { if (_writeNodeBuffer == null) { _writeNodeBuffer = new char[WriteNodeBufferSize]; } int read; while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0) { await this.WriteCharsAsync(_writeNodeBuffer, 0, read).ConfigureAwait(false); } } else { await WriteStringAsync(reader.Value).ConfigureAwait(false); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: await WriteWhitespaceAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.CDATA: await WriteCDataAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EntityReference: await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false); break; case XmlNodeType.DocumentType: await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false); break; case XmlNodeType.Comment: await WriteCommentAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EndElement: await WriteFullEndElementAsync().ConfigureAwait(false); break; } } while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement))); } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. //use async methods on the reader internal async Task WriteNodeAsync_CallAsyncReader(XmlReader reader, bool defattr) { bool canReadChunk = reader.CanReadValueChunk; int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth; do { switch (reader.NodeType) { case XmlNodeType.Element: await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); if (reader.IsEmptyElement) { await WriteEndElementAsync().ConfigureAwait(false); break; } break; case XmlNodeType.Text: if (canReadChunk) { if (_writeNodeBuffer == null) { _writeNodeBuffer = new char[WriteNodeBufferSize]; } int read; while ((read = await reader.ReadValueChunkAsync(_writeNodeBuffer, 0, WriteNodeBufferSize).ConfigureAwait(false)) > 0) { await this.WriteCharsAsync(_writeNodeBuffer, 0, read).ConfigureAwait(false); } } else { //reader.Value may block on Text or WhiteSpace node, use GetValueAsync await WriteStringAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: await WriteWhitespaceAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false); break; case XmlNodeType.CDATA: await WriteCDataAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EntityReference: await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false); break; case XmlNodeType.DocumentType: await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false); break; case XmlNodeType.Comment: await WriteCommentAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EndElement: await WriteFullEndElementAsync().ConfigureAwait(false); break; } } while (await reader.ReadAsync().ConfigureAwait(false) && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement))); } // Element Helper Methods // Writes out an attribute with the specified name, namespace URI, and string value. public async Task WriteElementStringAsync(string prefix, String localName, String ns, String value) { await WriteStartElementAsync(prefix, localName, ns).ConfigureAwait(false); if (null != value && 0 != value.Length) { await WriteStringAsync(value).ConfigureAwait(false); } await WriteEndElementAsync().ConfigureAwait(false); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Candles.Compression.Algo File: StorageCandleBuilderSource.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Candles.Compression { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Ecng.Collections; using Ecng.Common; using Ecng.ComponentModel; using MoreLinq; using StockSharp.Algo.Storages; using StockSharp.BusinessEntities; using StockSharp.Localization; /// <summary> /// The base data source for <see cref="ICandleBuilder"/>, which receives data from the external storage. /// </summary> /// <typeparam name="TSourceValue">The source data type (for example, <see cref="Trade"/>).</typeparam> public abstract class StorageCandleBuilderSource<TSourceValue> : BaseCandleBuilderSource, IStorageCandleSource { [DebuggerDisplay("{Series} {Reader}")] private sealed class SeriesInfo { public SeriesInfo(CandleSeries series, IEnumerator<TSourceValue> reader) { if (series == null) throw new ArgumentNullException(nameof(series)); if (reader == null) throw new ArgumentNullException(nameof(reader)); Series = series; Reader = reader; } public CandleSeries Series { get; } public IEnumerator<TSourceValue> Reader { get; } public bool IsStopping { get; set; } } private readonly CachedSynchronizedDictionary<CandleSeries, SeriesInfo> _series = new CachedSynchronizedDictionary<CandleSeries, SeriesInfo>(); /// <summary> /// Initialize <see cref="StorageCandleBuilderSource{T}"/>. /// </summary> protected StorageCandleBuilderSource() { ThreadingHelper .Thread(OnLoading) .Background(true) .Name(GetType().Name) .Launch(); } /// <summary> /// The source priority by speed (0 - the best). /// </summary> public override int SpeedPriority => 1; /// <summary> /// Market data storage. /// </summary> public IStorageRegistry StorageRegistry { get; set; } private IMarketDataDrive _drive; /// <summary> /// The storage which is used by default. By default, <see cref="IStorageRegistry.DefaultDrive"/> is used. /// </summary> public IMarketDataDrive Drive { get { if (_drive == null) { if (StorageRegistry != null) return StorageRegistry.DefaultDrive; } return _drive; } set { _drive = value; } } /// <summary> /// To get the data storage <typeparamref name="TSourceValue" />. /// </summary> /// <param name="security">Security.</param> /// <returns>Market data storage.</returns> protected abstract IMarketDataStorage<TSourceValue> GetStorage(Security security); /// <summary> /// To get time ranges for which this source of passed candles series has data. /// </summary> /// <param name="series">Candles series.</param> /// <returns>Time ranges.</returns> public override IEnumerable<Range<DateTimeOffset>> GetSupportedRanges(CandleSeries series) { if (series == null) throw new ArgumentNullException(nameof(series)); if (StorageRegistry == null) return Enumerable.Empty<Range<DateTimeOffset>>(); return GetStorage(series.Security).GetRanges(); } /// <summary> /// To get data. /// </summary> /// <param name="series">Candles series.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <returns>Data. If data does not exist for the specified range then <see langword="null" /> will be returned.</returns> protected virtual IEnumerable<TSourceValue> GetValues(CandleSeries series, DateTimeOffset from, DateTimeOffset to) { var storage = GetStorage(series.Security); var range = storage.GetRange(from, to); if (range == null) return null; return storage.Load(range.Min, range.Max); } /// <summary> /// To send data request. /// </summary> /// <param name="series">The candles series for which data receiving should be started.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> public override void Start(CandleSeries series, DateTimeOffset from, DateTimeOffset to) { if (series == null) throw new ArgumentNullException(nameof(series)); var values = GetValues(series, from, to); if (values == null) return; lock (_series.SyncRoot) { if (_series.ContainsKey(series)) throw new ArgumentException(LocalizedStrings.Str650Params.Put(series), nameof(series)); _series.Add(series, new SeriesInfo(series, values.GetEnumerator())); if (_series.Count == 1) Monitor.Pulse(_series.SyncRoot); } } /// <summary> /// To stop data receiving starting through <see cref="Start"/>. /// </summary> /// <param name="series">Candles series.</param> public override void Stop(CandleSeries series) { lock (_series.SyncRoot) { var info = _series.TryGetValue(series); if (info != null) info.IsStopping = true; } } /// <summary> /// To convert <typeparam ref="TSourceValue"/> to <see cref="ICandleBuilderSourceValue"/>. /// </summary> /// <param name="value">New source data.</param> /// <returns>Data in format <see cref="ICandleBuilder"/>.</returns> protected abstract ICandleBuilderSourceValue Convert(TSourceValue value); private void OnLoading() { try { while (!IsDisposed) { var removingSeries = new List<CandleSeries>(); foreach (var info in _series.CachedValues) { if (info.IsStopping) removingSeries.Add(info.Series); else { var values = new List<TSourceValue>(100); for (var i = 0; i < 100; i++) { if (!info.Reader.MoveNext()) { removingSeries.Add(info.Series); break; } values.Add(info.Reader.Current); } if (values.Count > 0) RaiseProcessing(info.Series, values.Select(Convert)); } } if (removingSeries.Count > 0) { lock (_series.SyncRoot) removingSeries.ForEach(s => _series.Remove(s)); removingSeries.ForEach(RaiseStopped); } lock (_series.SyncRoot) { if (_series.IsEmpty()) Monitor.Wait(_series.SyncRoot); } } } catch (Exception ex) { RaiseError(ex); _series.CopyAndClear().ForEach(p => RaiseStopped(p.Key)); } } /// <summary> /// Release resources. /// </summary> public override void Dispose() { base.Dispose(); lock (_series.SyncRoot) { _series.ForEach(p => p.Value.IsStopping = true); Monitor.Pulse(_series.SyncRoot); } } } /// <summary> /// The data source for <see cref="CandleBuilder{T}"/> getting tick trades from the external storage <see cref="IStorageRegistry"/>. /// </summary> public class TradeStorageCandleBuilderSource : StorageCandleBuilderSource<Trade> { /// <summary> /// Initializes a new instance of the <see cref="TradeStorageCandleBuilderSource"/>. /// </summary> public TradeStorageCandleBuilderSource() { } /// <summary> /// To get the storage of tick trades. /// </summary> /// <param name="security">Security.</param> /// <returns>The storage of tick trades.</returns> protected override IMarketDataStorage<Trade> GetStorage(Security security) { return StorageRegistry.GetTradeStorage(security, Drive); } /// <summary> /// To convert <typeparam ref="TSourceValue"/> to <see cref="ICandleBuilderSourceValue"/>. /// </summary> /// <param name="value">New source data.</param> /// <returns>Data in format <see cref="ICandleBuilder"/>.</returns> protected override ICandleBuilderSourceValue Convert(Trade value) { return new TradeCandleBuilderSourceValue(value); } } /// <summary> /// The data source for <see cref="CandleBuilder{T}"/> getting tick trades from the external storage <see cref="IStorageRegistry"/>. /// </summary> public class MarketDepthStorageCandleBuilderSource : StorageCandleBuilderSource<MarketDepth> { private readonly DepthCandleSourceTypes _type; /// <summary> /// Initializes a new instance of the <see cref="MarketDepthStorageCandleBuilderSource"/>. /// </summary> /// <param name="type">Type of candle depth based data.</param> public MarketDepthStorageCandleBuilderSource(DepthCandleSourceTypes type) { _type = type; } /// <summary> /// To get the order books storage. /// </summary> /// <param name="security">Security.</param> /// <returns>The order books storage.</returns> protected override IMarketDataStorage<MarketDepth> GetStorage(Security security) { return StorageRegistry.GetMarketDepthStorage(security, Drive); } /// <summary> /// To convert <typeparam ref="TSourceValue"/> to <see cref="ICandleBuilderSourceValue"/>. /// </summary> /// <param name="value">New source data.</param> /// <returns>Data in format <see cref="ICandleBuilder"/>.</returns> protected override ICandleBuilderSourceValue Convert(MarketDepth value) { return new DepthCandleBuilderSourceValue(value, _type); } } /// <summary> /// The data source for <see cref="CandleBuilder{T}"/> getting tick trades from the external storage <see cref="IStorageRegistry"/>. /// </summary> public class OrderLogStorageCandleBuilderSource : StorageCandleBuilderSource<Trade> { /// <summary> /// Initializes a new instance of the <see cref="OrderLogStorageCandleBuilderSource"/>. /// </summary> public OrderLogStorageCandleBuilderSource() { } /// <summary> /// The source priority by speed (0 - the best). /// </summary> public override int SpeedPriority => 2; /// <summary> /// To get the data storage. /// </summary> /// <param name="security">Security.</param> /// <returns>Market data storage.</returns> protected override IMarketDataStorage<Trade> GetStorage(Security security) { throw new NotSupportedException(); } /// <summary> /// To get time ranges for which this source of passed candles series has data. /// </summary> /// <param name="series">Candles series.</param> /// <returns>Time ranges.</returns> public override IEnumerable<Range<DateTimeOffset>> GetSupportedRanges(CandleSeries series) { if (series == null) throw new ArgumentNullException(nameof(series)); if (StorageRegistry == null) return Enumerable.Empty<Range<DateTimeOffset>>(); return StorageRegistry.GetOrderLogStorage(series.Security, Drive).GetRanges(); } /// <summary> /// To convert <typeparam ref="TSourceValue"/> to <see cref="ICandleBuilderSourceValue"/>. /// </summary> /// <param name="value">New source data.</param> /// <returns>Data in format <see cref="ICandleBuilder"/>.</returns> protected override ICandleBuilderSourceValue Convert(Trade value) { return new TradeCandleBuilderSourceValue(value); } /// <summary> /// To get data. /// </summary> /// <param name="series">Candles series.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <returns>Data. If data does not exist for the specified range then <see langword="null" /> will be returned.</returns> protected override IEnumerable<Trade> GetValues(CandleSeries series, DateTimeOffset from, DateTimeOffset to) { var storage = StorageRegistry.GetOrderLogStorage(series.Security, Drive); var range = storage.GetRange(from, to); if (range == null) return null; return storage.Load(range.Min, range.Max).ToTrades(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using Microsoft.Build.Shared; using Xunit; using System.Collections.Generic; using System.Linq; using MSBuildConstants = Microsoft.Build.Tasks.MSBuildConstants; namespace Microsoft.Build.UnitTests { /// <summary> /// Tests for write code fragment task /// </summary> public class WriteCodeFragment_Tests { /// <summary> /// Need an available language /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void InvalidLanguage() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "xx"; task.OutputFile = new TaskItem("foo"); bool result = task.Execute(); Assert.False(result); engine.AssertLogContains("MSB3712"); } /// <summary> /// Need a language /// </summary> [Fact] public void NoLanguage() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.OutputFile = new TaskItem("foo"); bool result = task.Execute(); Assert.False(result); engine.AssertLogContains("MSB3098"); } /// <summary> /// Need a location /// </summary> [Fact] public void NoFileOrDirectory() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "c#"; bool result = task.Execute(); Assert.False(result); engine.AssertLogContains("MSB3711"); } /// <summary> /// Combine file and directory /// </summary> [Fact] public void CombineFileDirectory() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "c#"; task.AssemblyAttributes = new TaskItem[] { new TaskItem("aa") }; task.OutputFile = new TaskItem("CombineFileDirectory.tmp"); task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); string file = Path.Combine(Path.GetTempPath(), "CombineFileDirectory.tmp"); Assert.Equal(file, task.OutputFile.ItemSpec); Assert.True(File.Exists(file)); } /// <summary> /// Ignore directory if file is rooted /// </summary> [Fact] public void DirectoryAndRootedFile() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "c#"; task.AssemblyAttributes = new TaskItem[] { new TaskItem("aa") }; string folder = Path.Combine(Path.GetTempPath(), "foo" + Path.DirectorySeparatorChar); string file = Path.Combine(folder, "CombineFileDirectory.tmp"); Directory.CreateDirectory(folder); task.OutputFile = new TaskItem(file); task.OutputDirectory = new TaskItem("c:\\"); bool result = task.Execute(); Assert.True(result); Assert.Equal(file, task.OutputFile.ItemSpec); Assert.True(File.Exists(file)); FileUtilities.DeleteWithoutTrailingBackslash(folder, true); } /// <summary> /// Given nothing to write, should succeed but /// produce no output file /// </summary> [Fact] public void NoAttributesShouldEmitNoFile() { string file = Path.Combine(Path.GetTempPath(), "NoAttributesShouldEmitNoFile.tmp"); if (File.Exists(file)) { File.Delete(file); } WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "c#"; task.AssemblyAttributes = new TaskItem[] { }; // MSBuild sets an empty array task.OutputFile = new TaskItem(file); bool result = task.Execute(); Assert.True(result); Assert.False(File.Exists(file)); Assert.Null(task.OutputFile); } /// <summary> /// Given nothing to write, should succeed but /// produce no output file /// </summary> [Fact] public void NoAttributesShouldEmitNoFile2() { string file = Path.Combine(Path.GetTempPath(), "NoAttributesShouldEmitNoFile.tmp"); if (File.Exists(file)) { File.Delete(file); } WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "c#"; task.AssemblyAttributes = null; // null this time task.OutputFile = new TaskItem(file); bool result = task.Execute(); Assert.True(result); Assert.False(File.Exists(file)); Assert.Null(task.OutputFile); } /// <summary> /// Bad file path /// </summary> [Fact] public void InvalidFilePath() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "c#"; task.AssemblyAttributes = new TaskItem[] { new TaskItem("aa") }; task.OutputFile = new TaskItem("||//invalid||"); bool result = task.Execute(); Assert.False(result); engine.AssertLogContains("MSB3713"); } /// <summary> /// Bad directory path /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] // "No invalid characters on Unix" public void InvalidDirectoryPath() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "c#"; task.AssemblyAttributes = new TaskItem[] { new TaskItem("aa") }; task.OutputDirectory = new TaskItem("||invalid||"); bool result = task.Execute(); Assert.False(result); engine.AssertLogContains("MSB3713"); } /// <summary> /// Parameterless attribute /// </summary> [Fact] public void OneAttributeNoParams() { string file = Path.Combine(Path.GetTempPath(), "OneAttribute.tmp"); try { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("System.AssemblyTrademarkAttribute"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputFile = new TaskItem(file); bool result = task.Execute(); Assert.True(result); Assert.True(File.Exists(file)); string content = File.ReadAllText(file); Console.WriteLine(content); CheckContentCSharp(content, "[assembly: System.AssemblyTrademarkAttribute()]"); } finally { File.Delete(file); } } /// <summary> /// Test with the VB language /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void OneAttributeNoParamsVb() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("System.AssemblyTrademarkAttribute"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "visualbasic"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); string content = File.ReadAllText(task.OutputFile.ItemSpec); Console.WriteLine(content); CheckContentVB(content, "<Assembly: System.AssemblyTrademarkAttribute()>"); } /// <summary> /// More than one attribute /// </summary> [Fact] public void TwoAttributes() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute1 = new TaskItem("AssemblyTrademarkAttribute"); attribute1.SetMetadata("Name", "Microsoft"); TaskItem attribute2 = new TaskItem("System.AssemblyCultureAttribute"); attribute2.SetMetadata("Culture", "en-US"); task.AssemblyAttributes = new TaskItem[] { attribute1, attribute2 }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); string content = File.ReadAllText(task.OutputFile.ItemSpec); Console.WriteLine(content); CheckContentCSharp( content, @"[assembly: AssemblyTrademarkAttribute(Name=""Microsoft"")]", @"[assembly: System.AssemblyCultureAttribute(Culture=""en-US"")]"); } /// <summary> /// Specify directory instead /// </summary> [Fact] public void ToDirectory() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("System.AssemblyTrademarkAttribute"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); Assert.True(File.Exists(task.OutputFile.ItemSpec)); Assert.Equal(Path.GetTempPath(), task.OutputFile.ItemSpec.Substring(0, Path.GetTempPath().Length)); Assert.Equal(".cs", task.OutputFile.ItemSpec.Substring(task.OutputFile.ItemSpec.Length - 3)); File.Delete(task.OutputFile.ItemSpec); } /// <summary> /// Regular case /// </summary> [Fact] public void OneAttributeTwoParams() { string file = Path.Combine(Path.GetTempPath(), "OneAttribute.tmp"); try { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("Company", "Microsoft"); attribute.SetMetadata("Year", "2009"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputFile = new TaskItem(file); bool result = task.Execute(); Assert.True(result); Assert.True(File.Exists(file)); string content = File.ReadAllText(file); Console.WriteLine(content); CheckContentCSharp(content, @"[assembly: AssemblyTrademarkAttribute(Company=""Microsoft"", Year=""2009"")]"); } finally { File.Delete(file); } } /// <summary> /// This produces invalid code, but the task works /// </summary> [Fact] public void OneAttributeTwoParamsSameName() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("Company", "Microsoft"); attribute.SetMetadata("Company", "2009"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); File.Delete(task.OutputFile.ItemSpec); } /// <summary> /// Some attributes only allow positional constructor arguments. /// To set those, use metadata names like "_Parameter1", "_Parameter2" etc. /// </summary> [Fact] public void OneAttributePositionalParamInvalidSuffix() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("_ParameterXXXXXXXXXX", "Microsoft"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.False(result); engine.AssertLogContains("MSB3098"); } /// <summary> /// Some attributes only allow positional constructor arguments. /// To set those, use metadata names like "_Parameter1", "_Parameter2" etc. /// </summary> [Fact] public void OneAttributeTwoPositionalParams() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("_Parameter1", "Microsoft"); attribute.SetMetadata("_Parameter2", "2009"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); string content = File.ReadAllText(task.OutputFile.ItemSpec); Console.WriteLine(content); CheckContentCSharp(content, @"[assembly: AssemblyTrademarkAttribute(""Microsoft"", ""2009"")]"); File.Delete(task.OutputFile.ItemSpec); } [Fact] public void OneAttributeTwoPositionalParamsWithSameValue() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyMetadataAttribute"); attribute.SetMetadata("_Parameter1", "TestValue"); attribute.SetMetadata("_Parameter2", "TestValue"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); string content = File.ReadAllText(task.OutputFile.ItemSpec); Console.WriteLine(content); CheckContentCSharp(content, @"[assembly: AssemblyMetadataAttribute(""TestValue"", ""TestValue"")]"); File.Delete(task.OutputFile.ItemSpec); } public static string EscapedLineSeparator => NativeMethodsShared.IsWindows ? "\\r\\n" : "\\n"; /// <summary> /// Multi line argument values should cause a verbatim string to be used /// </summary> [Fact] public void MultilineAttributeCSharp() { var lines = new[] { "line 1", "line 2", "line 3" }; var multilineString = String.Join(Environment.NewLine, lines); WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("System.Reflection.AssemblyDescriptionAttribute"); attribute.SetMetadata("_Parameter1", multilineString); attribute.SetMetadata("Description", multilineString); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); string content = File.ReadAllText(task.OutputFile.ItemSpec); Console.WriteLine(content); var csMultilineString = lines.Aggregate((l1, l2) => l1 + EscapedLineSeparator + l2); CheckContentCSharp(content, $"[assembly: System.Reflection.AssemblyDescriptionAttribute(\"{csMultilineString}\", Description=\"{csMultilineString}\")]"); File.Delete(task.OutputFile.ItemSpec); } private static readonly string VBCarriageReturn = "Global.Microsoft.VisualBasic.ChrW(13)"; private static readonly string VBLineFeed = "Global.Microsoft.VisualBasic.ChrW(10)"; private static readonly string WindowsNewLine = $"{VBCarriageReturn}&{VBLineFeed}"; public static readonly string VBLineSeparator = #if FEATURE_CODEDOM WindowsNewLine; #else NativeMethodsShared.IsWindows ? WindowsNewLine : VBLineFeed; #endif /// <summary> /// Multi line argument values should cause a verbatim string to be used /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void MultilineAttributeVB() { var lines = new []{ "line 1", "line 2", "line 3" }; var multilineString = String.Join(Environment.NewLine, lines); WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("System.Reflection.AssemblyDescriptionAttribute"); attribute.SetMetadata("_Parameter1", multilineString); attribute.SetMetadata("Description", multilineString); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "visualbasic"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); string content = File.ReadAllText(task.OutputFile.ItemSpec); Console.WriteLine(content); var vbMultilineString = lines .Select(l => $"\"{l}\"") .Aggregate((l1, l2) => $"{l1}&{VBLineSeparator}&{l2}"); CheckContentVB(content, $"<Assembly: System.Reflection.AssemblyDescriptionAttribute({vbMultilineString}, Description:={vbMultilineString})>"); File.Delete(task.OutputFile.ItemSpec); } /// <summary> /// Some attributes only allow positional constructor arguments. /// To set those, use metadata names like "_Parameter1", "_Parameter2" etc. /// If a parameter is skipped, it's an error. /// </summary> [Fact] public void OneAttributeSkippedPositionalParams() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("_Parameter2", "2009"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.False(result); engine.AssertLogContains("MSB3714"); } /// <summary> /// Some attributes only allow positional constructor arguments. /// To set those, use metadata names like "_Parameter1", "_Parameter2" etc. /// This test is for "_ParameterX" /// </summary> [Fact] public void InvalidNumber() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("_ParameterX", "2009"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.False(result); engine.AssertLogContains("MSB3098"); } /// <summary> /// Some attributes only allow positional constructor arguments. /// To set those, use metadata names like "_Parameter1", "_Parameter2" etc. /// This test is for "_Parameter" /// </summary> [Fact] public void NoNumber() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("_Parameter", "2009"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.False(result); engine.AssertLogContains("MSB3098"); } /// <summary> /// Some attributes only allow positional constructor arguments. /// To set those, use metadata names like "_Parameter1", "_Parameter2" etc. /// These can also be combined with named params. /// </summary> [Fact] public void OneAttributePositionalAndNamedParams() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("_Parameter1", "Microsoft"); attribute.SetMetadata("Date", "2009"); attribute.SetMetadata("Copyright", "(C)"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); string content = File.ReadAllText(task.OutputFile.ItemSpec); Console.WriteLine(content); CheckContentCSharp(content, @"[assembly: AssemblyTrademarkAttribute(""Microsoft"", Date=""2009"", Copyright=""(C)"")]"); File.Delete(task.OutputFile.ItemSpec); } /// <summary> /// Some attributes only allow positional constructor arguments. /// To set those, use metadata names like "_Parameter1", "_Parameter2" etc. /// These can also be combined with named params. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void OneAttributePositionalAndNamedParamsVisualBasic() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("_Parameter1", "Microsoft"); attribute.SetMetadata("_Parameter2", "2009"); attribute.SetMetadata("Copyright", "(C)"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "visualbasic"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.True(result); string content = File.ReadAllText(task.OutputFile.ItemSpec); Console.WriteLine(content); CheckContentVB(content, @"<Assembly: AssemblyTrademarkAttribute(""Microsoft"", ""2009"", Copyright:=""(C)"")>"); File.Delete(task.OutputFile.ItemSpec); } private static void CheckContentCSharp(string actualContent, params string[] expectedAttributes) { CheckContent( actualContent, expectedAttributes, "//", "using System;", "using System.Reflection;"); } private static void CheckContentVB(string actualContent, params string[] expectedAttributes) { CheckContent( actualContent, expectedAttributes, "'", "Option Strict Off", "Option Explicit On", "Imports System", "Imports System.Reflection"); } private static void CheckContent(string actualContent, string[] expectedAttributes, string commentStart, params string[] expectedHeader) { string expectedContent = string.Join(Environment.NewLine, expectedHeader.Concat(expectedAttributes)); // we tolerate differences in whitespace and comments between platforms string normalizedActualContent = string.Join( Environment.NewLine, actualContent.Split(MSBuildConstants.CrLf) .Select(line => line.Trim()) .Where(line => line.Length > 0 && !line.StartsWith(commentStart))); Assert.Equal(expectedContent, normalizedActualContent); } } }
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct SByte : IComparable, IConvertible, IFormattable, IComparable<SByte>, IEquatable<SByte> { private sbyte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 127. public const sbyte MaxValue = (sbyte)0x7F; // The minimum value that a Byte may represent: -128. public const sbyte MinValue = unchecked((sbyte)0x80); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type SByte, this method throws an ArgumentException. // public int CompareTo(Object obj) { if (obj == null) { return 1; } if (!(obj is SByte)) { throw new ArgumentException(SR.Arg_MustBeSByte); } return m_value - ((SByte)obj).m_value; } public int CompareTo(SByte value) { return m_value - value; } // Determines whether two Byte objects are equal. public override bool Equals(Object obj) { if (!(obj is SByte)) { return false; } return m_value == ((SByte)obj).m_value; } [NonVersionable] public bool Equals(SByte obj) { return m_value == obj; } // Gets a hash code for this instance. public override int GetHashCode() { return ((int)m_value ^ (int)m_value << 8); } // Provides a string representation of a byte. public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return ToString(format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return ToString(format, NumberFormatInfo.GetInstance(provider)); } private String ToString(String format, NumberFormatInfo info) { Contract.Ensures(Contract.Result<String>() != null); if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x000000FF); return Number.FormatUInt32(temp, format, info); } return Number.FormatInt32(m_value, format, info); } [CLSCompliant(false)] public static sbyte Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static sbyte Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsSpan(), style, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static sbyte Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses a signed byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // [CLSCompliant(false)] public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static sbyte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static sbyte Parse(String s, NumberStyles style, NumberFormatInfo info) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsSpan(), style, info); } private static sbyte Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { int i = 0; try { i = Number.ParseInt32(s, style, info); } catch (OverflowException e) { throw new OverflowException(SR.Overflow_SByte, e); } if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || i > Byte.MaxValue) { throw new OverflowException(SR.Overflow_SByte); } return (sbyte)i; } if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_SByte); return (sbyte)i; } [CLSCompliant(false)] public static bool TryParse(String s, out SByte result) { if (s == null) { result = 0; return false; } return TryParse(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } [CLSCompliant(false)] public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider), out result); } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan<char> s, out sbyte result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out SByte result) { result = 0; int i; if (!Number.TryParseInt32(s, style, info, out i)) { return false; } if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || i > Byte.MaxValue) { return false; } result = (sbyte)i; return true; } if (i < MinValue || i > MaxValue) { return false; } result = (sbyte)i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.SByte; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return m_value; } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return m_value; } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "SByte", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Region.CoreModules.Avatar.Chat; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace OpenSim.Region.OptionalModules.Avatar.Concierge { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ConciergeModule")] public class ConciergeModule : ChatModule, ISharedRegionModule { internal bool m_enabled = false; internal object m_syncy = new object(); private const int DEBUG_CHANNEL = 2147483647; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static private Vector3 PosOfGod = new Vector3(128, 128, 9999); private string m_announceEntering = "{0} enters {1} (now {2} visitors in this region)"; private string m_announceLeaving = "{0} leaves {1} (back to {2} visitors in this region)"; private int m_brokerUpdateTimeout = 300; private string m_brokerURI = String.Empty; private int m_conciergeChannel = 42; private List<IScene> m_conciergedScenes = new List<IScene>(); private IConfig m_config; private Regex m_regions = null; private bool m_replacingChatModule = false; private List<IScene> m_scenes = new List<IScene>(); private string m_welcomes = null; private string m_whoami = "conferencier"; private string m_xmlRpcPassword = String.Empty; #region ISharedRegionModule Members public override string Name { get { return "ConciergeModule"; } } new public Type ReplaceableInterface { get { return null; } } public override void AddRegion(Scene scene) { if (!m_enabled) return; MainServer.Instance.AddXmlRPCHandler("concierge_update_welcome", XmlRpcUpdateWelcomeMethod, false); lock (m_syncy) { if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); if (m_regions == null || m_regions.IsMatch(scene.RegionInfo.RegionName)) m_conciergedScenes.Add(scene); // subscribe to NewClient events scene.EventManager.OnNewClient += OnNewClient; // subscribe to *Chat events scene.EventManager.OnChatFromWorld += OnChatFromWorld; if (!m_replacingChatModule) scene.EventManager.OnChatFromClient += OnChatFromClient; scene.EventManager.OnChatBroadcast += OnChatBroadcast; // subscribe to agent change events scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; } } m_log.InfoFormat("[Concierge]: initialized for {0}", scene.RegionInfo.RegionName); } public override void Close() { } public override void Initialise(IConfigSource config) { m_config = config.Configs["Concierge"]; if (null == m_config) return; if (!m_config.GetBoolean("enabled", false)) return; m_enabled = true; // check whether ChatModule has been disabled: if yes, // then we'll "stand in" try { if (config.Configs["Chat"] == null) { // if Chat module has not been configured it's // enabled by default, so we are not going to // replace it. m_replacingChatModule = false; } else { m_replacingChatModule = !config.Configs["Chat"].GetBoolean("enabled", true); } } catch (Exception) { m_replacingChatModule = false; } m_log.InfoFormat("[Concierge] {0} ChatModule", m_replacingChatModule ? "replacing" : "not replacing"); // take note of concierge channel and of identity m_conciergeChannel = config.Configs["Concierge"].GetInt("concierge_channel", m_conciergeChannel); m_whoami = m_config.GetString("whoami", "conferencier"); m_welcomes = m_config.GetString("welcomes", m_welcomes); m_announceEntering = m_config.GetString("announce_entering", m_announceEntering); m_announceLeaving = m_config.GetString("announce_leaving", m_announceLeaving); m_xmlRpcPassword = m_config.GetString("password", m_xmlRpcPassword); m_brokerURI = m_config.GetString("broker", m_brokerURI); m_brokerUpdateTimeout = m_config.GetInt("broker_timeout", m_brokerUpdateTimeout); m_log.InfoFormat("[Concierge] reporting as \"{0}\" to our users", m_whoami); // calculate regions Regex if (m_regions == null) { string regions = m_config.GetString("regions", String.Empty); if (!String.IsNullOrEmpty(regions)) { m_regions = new Regex(@regions, RegexOptions.Compiled | RegexOptions.IgnoreCase); } } } public override void PostInitialise() { } public override void RemoveRegion(Scene scene) { if (!m_enabled) return; MainServer.Instance.RemoveXmlRPCHandler("concierge_update_welcome"); lock (m_syncy) { // unsubscribe from NewClient events scene.EventManager.OnNewClient -= OnNewClient; // unsubscribe from *Chat events scene.EventManager.OnChatFromWorld -= OnChatFromWorld; if (!m_replacingChatModule) scene.EventManager.OnChatFromClient -= OnChatFromClient; scene.EventManager.OnChatBroadcast -= OnChatBroadcast; // unsubscribe from agent change events scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent; scene.EventManager.OnMakeChildAgent -= OnMakeChildAgent; if (m_scenes.Contains(scene)) { m_scenes.Remove(scene); } if (m_conciergedScenes.Contains(scene)) { m_conciergedScenes.Remove(scene); } } m_log.InfoFormat("[Concierge]: removed {0}", scene.RegionInfo.RegionName); } #endregion ISharedRegionModule Members #region ISimChat Members public override void OnChatBroadcast(Object sender, OSChatMessage c) { if (m_replacingChatModule) { // distribute chat message to each and every avatar in // the region base.OnChatBroadcast(sender, c); } // TODO: capture logic return; } public override void OnChatFromClient(Object sender, OSChatMessage c) { if (m_replacingChatModule) { // replacing ChatModule: need to redistribute // ChatFromClient to interested subscribers c = FixPositionOfChatMessage(c); Scene scene = (Scene)c.Scene; scene.EventManager.TriggerOnChatFromClient(sender, c); if (m_conciergedScenes.Contains(c.Scene)) { // when we are replacing ChatModule, we treat // OnChatFromClient like OnChatBroadcast for // concierged regions, effectively extending the // range of chat to cover the whole // region. however, we don't do this for whisper // (got to have some privacy) if (c.Type != ChatTypeEnum.Whisper) { base.OnChatBroadcast(sender, c); return; } } // redistribution will be done by base class base.OnChatFromClient(sender, c); } // TODO: capture chat return; } public override void OnChatFromWorld(Object sender, OSChatMessage c) { if (m_replacingChatModule) { if (m_conciergedScenes.Contains(c.Scene)) { // when we are replacing ChatModule, we treat // OnChatFromClient like OnChatBroadcast for // concierged regions, effectively extending the // range of chat to cover the whole // region. however, we don't do this for whisper // (got to have some privacy) if (c.Type != ChatTypeEnum.Whisper) { base.OnChatBroadcast(sender, c); return; } } base.OnChatFromWorld(sender, c); } return; } #endregion ISimChat Members public void OnClientLoggedOut(IClientAPI client) { client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; if (m_conciergedScenes.Contains(client.Scene)) { Scene scene = client.Scene as Scene; m_log.DebugFormat("[Concierge]: {0} logs off from {1}", client.Name, scene.RegionInfo.RegionName); AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, client.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } public void OnMakeChildAgent(ScenePresence agent) { if (m_conciergedScenes.Contains(agent.Scene)) { Scene scene = agent.Scene; m_log.DebugFormat("[Concierge]: {0} leaves {1}", agent.Name, scene.RegionInfo.RegionName); AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, agent.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } public void OnMakeRootAgent(ScenePresence agent) { if (m_conciergedScenes.Contains(agent.Scene)) { Scene scene = agent.Scene; m_log.DebugFormat("[Concierge]: {0} enters {1}", agent.Name, scene.RegionInfo.RegionName); WelcomeAvatar(agent, scene); AnnounceToAgentsRegion(scene, String.Format(m_announceEntering, agent.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } public override void OnNewClient(IClientAPI client) { client.OnLogout += OnClientLoggedOut; if (m_replacingChatModule) client.OnChatFromClient += OnChatFromClient; } public XmlRpcResponse XmlRpcUpdateWelcomeMethod(XmlRpcRequest request, IPEndPoint remoteClient) { m_log.Info("[Concierge]: processing UpdateWelcome request"); XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); try { Hashtable requestData = (Hashtable)request.Params[0]; checkStringParameters(request, new string[] { "password", "region", "welcome" }); // check password if (!String.IsNullOrEmpty(m_xmlRpcPassword) && (string)requestData["password"] != m_xmlRpcPassword) throw new Exception("wrong password"); if (String.IsNullOrEmpty(m_welcomes)) throw new Exception("welcome templates are not enabled, ask your OpenSim operator to set the \"welcomes\" option in the [Concierge] section of OpenSim.ini"); string msg = (string)requestData["welcome"]; if (String.IsNullOrEmpty(msg)) throw new Exception("empty parameter \"welcome\""); string regionName = (string)requestData["region"]; IScene scene = m_scenes.Find(delegate(IScene s) { return s.RegionInfo.RegionName == regionName; }); if (scene == null) throw new Exception(String.Format("unknown region \"{0}\"", regionName)); if (!m_conciergedScenes.Contains(scene)) throw new Exception(String.Format("region \"{0}\" is not a concierged region.", regionName)); string welcome = Path.Combine(m_welcomes, regionName); if (File.Exists(welcome)) { m_log.InfoFormat("[Concierge]: UpdateWelcome: updating existing template \"{0}\"", welcome); string welcomeBackup = String.Format("{0}~", welcome); if (File.Exists(welcomeBackup)) File.Delete(welcomeBackup); File.Move(welcome, welcomeBackup); } File.WriteAllText(welcome, msg); responseData["success"] = "true"; response.Value = responseData; } catch (Exception e) { m_log.InfoFormat("[Concierge]: UpdateWelcome failed: {0}", e.Message); responseData["success"] = "false"; responseData["error"] = e.Message; response.Value = responseData; } m_log.Debug("[Concierge]: done processing UpdateWelcome request"); return response; } protected void AnnounceToAgent(ScenePresence agent, string msg) { OSChatMessage c = new OSChatMessage(); c.Message = msg; c.Type = ChatTypeEnum.Say; c.Channel = 0; c.Position = PosOfGod; c.From = m_whoami; c.Sender = null; c.SenderUUID = UUID.Zero; c.Scene = agent.Scene; agent.ControllingClient.SendChatMessage( msg, (byte)ChatTypeEnum.Say, PosOfGod, m_whoami, UUID.Zero, UUID.Zero, (byte)ChatSourceType.Object, (byte)ChatAudibleLevel.Fully); } protected void AnnounceToAgentsRegion(IScene scene, string msg) { OSChatMessage c = new OSChatMessage(); c.Message = msg; c.Type = ChatTypeEnum.Say; c.Channel = 0; c.Position = PosOfGod; c.From = m_whoami; c.Sender = null; c.SenderUUID = UUID.Zero; c.Scene = scene; if (scene is Scene) (scene as Scene).EventManager.TriggerOnChatBroadcast(this, c); } protected void UpdateBroker(Scene scene) { if (String.IsNullOrEmpty(m_brokerURI)) return; string uri = String.Format(m_brokerURI, scene.RegionInfo.RegionName, scene.RegionInfo.RegionID); // create XML sniplet StringBuilder list = new StringBuilder(); list.Append(String.Format("<avatars count=\"{0}\" region_name=\"{1}\" region_uuid=\"{2}\" timestamp=\"{3}\">\n", scene.GetRootAgentCount(), scene.RegionInfo.RegionName, scene.RegionInfo.RegionID, DateTime.UtcNow.ToString("s"))); scene.ForEachRootScenePresence(delegate(ScenePresence sp) { list.Append(String.Format(" <avatar name=\"{0}\" uuid=\"{1}\" />\n", sp.Name, sp.UUID)); }); list.Append("</avatars>"); string payload = list.ToString(); // post via REST to broker HttpWebRequest updatePost = WebRequest.Create(uri) as HttpWebRequest; updatePost.Method = "POST"; updatePost.ContentType = "text/xml"; updatePost.ContentLength = payload.Length; updatePost.UserAgent = "OpenSim.Concierge"; BrokerState bs = new BrokerState(uri, payload, updatePost); bs.Timer = new Timer(delegate(object state) { BrokerState b = state as BrokerState; b.Poster.Abort(); b.Timer.Dispose(); m_log.Debug("[Concierge]: async broker POST abort due to timeout"); }, bs, m_brokerUpdateTimeout * 1000, Timeout.Infinite); try { updatePost.BeginGetRequestStream(UpdateBrokerSend, bs); m_log.DebugFormat("[Concierge] async broker POST to {0} started", uri); } catch (WebException we) { m_log.ErrorFormat("[Concierge] async broker POST to {0} failed: {1}", uri, we.Status); } } protected void WelcomeAvatar(ScenePresence agent, Scene scene) { // welcome mechanics: check whether we have a welcomes // directory set and wether there is a region specific // welcome file there: if yes, send it to the agent if (!String.IsNullOrEmpty(m_welcomes)) { string[] welcomes = new string[] { Path.Combine(m_welcomes, agent.Scene.RegionInfo.RegionName), Path.Combine(m_welcomes, "DEFAULT")}; foreach (string welcome in welcomes) { if (File.Exists(welcome)) { try { string[] welcomeLines = File.ReadAllLines(welcome); foreach (string l in welcomeLines) { AnnounceToAgent(agent, String.Format(l, agent.Name, scene.RegionInfo.RegionName, m_whoami)); } } catch (IOException ioe) { m_log.ErrorFormat("[Concierge]: run into trouble reading welcome file {0} for region {1} for avatar {2}: {3}", welcome, scene.RegionInfo.RegionName, agent.Name, ioe); } catch (FormatException fe) { m_log.ErrorFormat("[Concierge]: welcome file {0} is malformed: {1}", welcome, fe); } } return; } m_log.DebugFormat("[Concierge]: no welcome message for region {0}", scene.RegionInfo.RegionName); } } // protected void AnnounceToAgentsRegion(Scene scene, string msg) // { // ScenePresence agent = null; // if ((client.Scene is Scene) && (client.Scene as Scene).TryGetScenePresence(client.AgentId, out agent)) // AnnounceToAgentsRegion(agent, msg); // else // m_log.DebugFormat("[Concierge]: could not find an agent for client {0}", client.Name); // } private static void checkStringParameters(XmlRpcRequest request, string[] param) { Hashtable requestData = (Hashtable)request.Params[0]; foreach (string p in param) { if (!requestData.Contains(p)) throw new Exception(String.Format("missing string parameter {0}", p)); if (String.IsNullOrEmpty((string)requestData[p])) throw new Exception(String.Format("parameter {0} is empty", p)); } } private void UpdateBrokerDone(IAsyncResult result) { BrokerState bs = null; try { bs = result.AsyncState as BrokerState; HttpWebRequest updatePost = bs.Poster; using (HttpWebResponse response = updatePost.EndGetResponse(result) as HttpWebResponse) { m_log.DebugFormat("[Concierge] broker update: status {0}", response.StatusCode); } bs.Timer.Dispose(); } catch (WebException we) { m_log.ErrorFormat("[Concierge] broker update to {0} failed with status {1}", bs.Uri, we.Status); if (null != we.Response) { using (HttpWebResponse resp = we.Response as HttpWebResponse) { m_log.ErrorFormat("[Concierge] response from {0} status code: {1}", bs.Uri, resp.StatusCode); m_log.ErrorFormat("[Concierge] response from {0} status desc: {1}", bs.Uri, resp.StatusDescription); m_log.ErrorFormat("[Concierge] response from {0} server: {1}", bs.Uri, resp.Server); if (resp.ContentLength > 0) { StreamReader content = new StreamReader(resp.GetResponseStream()); m_log.ErrorFormat("[Concierge] response from {0} content: {1}", bs.Uri, content.ReadToEnd()); content.Close(); } } } } } private void UpdateBrokerSend(IAsyncResult result) { BrokerState bs = null; try { bs = result.AsyncState as BrokerState; string payload = bs.Payload; HttpWebRequest updatePost = bs.Poster; using (StreamWriter payloadStream = new StreamWriter(updatePost.EndGetRequestStream(result))) { payloadStream.Write(payload); payloadStream.Close(); } updatePost.BeginGetResponse(UpdateBrokerDone, bs); } catch (WebException we) { m_log.DebugFormat("[Concierge]: async broker POST to {0} failed: {1}", bs.Uri, we.Status); } catch (Exception) { m_log.DebugFormat("[Concierge]: async broker POST to {0} failed", bs.Uri); } } internal class BrokerState { public string Payload; public HttpWebRequest Poster; public Timer Timer; public string Uri; public BrokerState(string uri, string payload, HttpWebRequest poster) { Uri = uri; Payload = payload; Poster = poster; } } } }
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEditor.AnimatedValues; using UnityEditor.Callbacks; using UnityEngine; using UnityEngine.Events; namespace Firebase.Editor { // This class is the outer window for all the tab pages used to configure Firebase extensions. // It handles finding the classes, creating instances, drawing the ui and loading/saving the config. internal class ConfigWindow : EditorWindow { private static CategoryLogger logger = new CategoryLogger("ConfigWindow"); // Redraw event private static UnityAction onRepaint; // Tab icon look up by tab name private static Dictionary<string, string> tabIconNames = new Dictionary<string, string>(); // Icons look up by icon name private static Dictionary<string, Texture2D> icons = new Dictionary<string, Texture2D>(); // Tab Gui callbacks keyed by sub tab name private static Dictionary<string, Dictionary<string, Action<IGUITheme>>> guiCallbacks = new Dictionary<string, Dictionary<string, Action<IGUITheme>>>(); // Config objects instances look up by type private static Dictionary<Type, ScriptableObject> configObjects = new Dictionary<Type, ScriptableObject>(); private static readonly int minWindowWidth = 250; private static readonly int iconOnlyListWidth = 40; private static readonly int iconTextListWidth = 150; private static readonly int widthDeadzone = 50; private GUIMenuSelector selector = new GUIMenuSelector(minWindowWidth, iconOnlyListWidth, iconTextListWidth, widthDeadzone); // Keeps track of the scroll position for the menu segment private Vector2 menuScrollPos = new Vector2(); // Keeps track of the scroll position for the tab segment private Vector2 tabScrollPos = new Vector2(); // Name of the currently selected tab private string selectedTab; // Theme used to render tab pages and sub segments private IGUITheme theme; // TODO: Hide configuration windows until this feature is ready. #if false [MenuItem("Window/Firebase/Configuration")] private static void Init() { GetWindow<ConfigWindow>("Firebase Configuration"); } #endif /// <summary> /// Registers a new tab to display in the configuration window. /// </summary> /// <param name="tabName">Tab display name</param> /// <param name="icon">Icon name in the editor/firebase folder (no ext)</param> /// <param name="onGuiCallback">Callback that is invoked when the tab needs to show UI</param> internal static void RegisterTab<T>(string tabName, string icon, Action<T> onGuiCallback = null) where T : ScriptableObject { logger.LogDebug("Registering tab with name {0} and icon {1} with type {2}.", tabName, icon, typeof(T).FullName); if (tabIconNames.ContainsKey(tabName) == true) { logger.LogWarn("RegisterTab was called twice with the same tab name '{0}'. " + "Skipping registration. Please ensure that RegisterTab is only called once " + "per unique tab name.", tabName); } else { tabIconNames.Add(tabName, icon); } if (onGuiCallback != null) { RegisterSubTab<T>(tabName, "", onGuiCallback); } } /// <summary> /// Registers a new sub tab to display within a main tab in the configuration window. /// </summary> /// <param name="tabName">Tab display name</param> /// <param name="subTabName">Sub tab display name</param> /// <param name="onGuiCallback">Callback that is invoked when the tab needs to show UI</param> internal static void RegisterSubTab<T>(string tabName, string subTabName, Action<T> onGuiCallback) where T : ScriptableObject { logger.LogDebug("Registering sub tab with name {0} on tab {1} with type {2}.", subTabName, tabName, typeof(T).FullName); Dictionary<string, Action<IGUITheme>> callbacks = null; if (guiCallbacks.TryGetValue(tabName, out callbacks) == false) { callbacks = new Dictionary<string, Action<IGUITheme>>(); guiCallbacks.Add(tabName, callbacks); } if (callbacks.ContainsKey(subTabName) == true) { logger.LogWarn("RegisterSubTab was called twice with the same sub tab name '{0}' and tab name" + " '{1}'. Skipping registration. Please ensure that RegisterSubTab is only" + " called once per unique sub tab name.", subTabName, tabName); return; } var abool = new AnimBool(true); abool.valueChanged.AddListener(onRepaint); callbacks.Add(subTabName, delegate(IGUITheme theme){ FirebaseGUILayout.SubTab(theme, subTabName, abool, delegate() { var obj = GetConfigObject<T>(); onGuiCallback(obj); }); }); } // Gets a existing config object of type T or creates a new one and loads the config for it // before returning private static T GetConfigObject<T>() where T : ScriptableObject { var type = typeof(T); ScriptableObject obj = null; if (configObjects.TryGetValue(type, out obj) == false) { obj = ConfigApi.LoadConfigAsset(type); configObjects.Add(type, obj); } return obj as T; } // Unity Editor calls this when the window is shown for the first time. // Load the theme and setup any thing required for rendering the GUI private void OnEnable() { if (EditorGUIUtility.isProSkin == true) { theme = new GUIDarkTheme(); } else { theme = new GUILightTheme(); } // Clear icons as theme might of changed icons.Clear(); // Load icons for each tab foreach (var icon in tabIconNames) { icons.Add(icon.Key, theme.LoadImage(icon.Value)); } // Add a null icon for all tab icons.Add("All", null); // Reset config objects configObjects.Clear(); // Reset current tab selectedTab = null; // Reset scroll pos tabScrollPos = new Vector2(); // Add the all tab if (guiCallbacks.ContainsKey("All") == false) { guiCallbacks.Add("All", null); } onRepaint += base.Repaint; } // Unity Editor calls when GUI needs to be drawn private void OnGUI() { Action cleanup = null; var keyList = guiCallbacks.Keys.ToList(); keyList.Sort(); if (string.IsNullOrEmpty(selectedTab) || keyList.Contains(selectedTab) == false) { selectedTab = keyList.First(); } var index = keyList.FindIndex(a => a == selectedTab); var buttons = keyList.Select(a => new GUIContent(" " + a, icons[a])) .ToArray(); var menuOption = selector.GetMenuOption(position.width); if (menuOption == GUIMenuSelector.MenuOption.LeftFull) { EditorGUILayout.BeginHorizontal(); index = FirebaseGUILayout.IconMenu(buttons, index, iconTextListWidth, theme, ref menuScrollPos); cleanup = delegate() { EditorGUILayout.EndHorizontal(); }; } else if (menuOption == GUIMenuSelector.MenuOption.LeftIcon) { Func<GUIContent, GUIContent> getImageButton = delegate(GUIContent content) { if (content.image != null) { return new GUIContent("", content.image, content.text); } return content; }; var imageButtons = buttons.Select(a => getImageButton(a)).ToArray(); EditorGUILayout.BeginHorizontal(); index = FirebaseGUILayout.IconMenu(imageButtons, index, iconOnlyListWidth, theme, ref menuScrollPos); cleanup = delegate() { EditorGUILayout.EndHorizontal(); }; } else { index = FirebaseGUILayout.ComboMenu(buttons, index); } if (selectedTab != keyList[index]) { selectedTab = keyList[index]; tabScrollPos = new Vector2(); } var style = new GUIStyle("scrollview"); style.padding.bottom = 10; EditorGUILayout.BeginVertical(); tabScrollPos = EditorGUILayout.BeginScrollView(tabScrollPos, style); if (selectedTab == "All") { foreach (var key in keyList) { if (key == "All") { continue; } foreach (var cb in guiCallbacks[key]) { cb.Value(theme); } } } else { foreach (var cb in guiCallbacks[selectedTab]) { cb.Value(theme); } } EditorGUILayout.EndScrollView(); var horzStyle = new GUIStyle("scrollview"); horzStyle.padding.bottom = 5; EditorGUILayout.BeginHorizontal(horzStyle); EditorGUILayout.Space(); if (GUILayout.Button("Save") == true) { Save(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); if (cleanup != null) { cleanup(); } } // Unity Editor calls this when the window is being destoryed private void OnDestroy() { Save(); onRepaint -= base.Repaint; } // Save out the configuration internal void Save() { foreach (var obj in configObjects) { ConfigApi.SaveConfigAsset(obj.Value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Security.Permissions; namespace System.DirectoryServices.AccountManagement { #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 [DirectoryRdnPrefix("CN")] public class GroupPrincipal : Principal { // // Public constructors // public GroupPrincipal(PrincipalContext context) { if (context == null) throw new ArgumentException(SR.NullArguments); this.ContextRaw = context; this.unpersisted = true; } public GroupPrincipal(PrincipalContext context, string samAccountName) : this(context) { if (samAccountName == null) throw new ArgumentException(SR.NullArguments); if (Context.ContextType != ContextType.ApplicationDirectory) this.SamAccountName = samAccountName; this.Name = samAccountName; } // // Public properties // // IsSecurityGroup property private bool _isSecurityGroup = false; // the actual property value private LoadState _isSecurityGroupChanged = LoadState.NotSet; // change-tracking public Nullable<bool> IsSecurityGroup { get { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // Different stores have different defaults as to the Enabled setting // (AD: creates disabled by default; SAM: creates enabled by default). // So if the principal is unpersisted (and thus we may not know what store it's // going to end up in), we'll just return null unless they previously // set an explicit value. if (this.unpersisted && (_isSecurityGroupChanged != LoadState.Changed)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "Group", "Enabled: returning null, unpersisted={0}, enabledChanged={1}", this.unpersisted, _isSecurityGroupChanged); return null; } return HandleGet<bool>(ref _isSecurityGroup, PropertyNames.GroupIsSecurityGroup, ref _isSecurityGroupChanged); } set { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // We don't want to let them set a null value. if (!value.HasValue) throw new ArgumentNullException("value"); HandleSet<bool>(ref _isSecurityGroup, value.Value, ref _isSecurityGroupChanged, PropertyNames.GroupIsSecurityGroup); } } // GroupScope property private GroupScope _groupScope = System.DirectoryServices.AccountManagement.GroupScope.Local; // the actual property value private LoadState _groupScopeChanged = LoadState.NotSet; // change-tracking public Nullable<GroupScope> GroupScope { get { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // Different stores have different defaults for the GroupScope setting // (AD: Global; SAM: Local). // So if the principal is unpersisted (and thus we may not know what store it's // going to end up in), we'll just return null unless they previously // set an explicit value. if (this.unpersisted && (_groupScopeChanged != LoadState.Changed)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "Group", "GroupScope: returning null, unpersisted={0}, groupScopeChanged={1}", this.unpersisted, _groupScopeChanged); return null; } return HandleGet<GroupScope>(ref _groupScope, PropertyNames.GroupGroupScope, ref _groupScopeChanged); } set { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // We don't want to let them set a null value. if (!value.HasValue) throw new ArgumentNullException("value"); HandleSet<GroupScope>(ref _groupScope, value.Value, ref _groupScopeChanged, PropertyNames.GroupGroupScope); } } // Members property private PrincipalCollection _members = null; public PrincipalCollection Members { get { // We don't use HandleGet<T> here because we have to load in the PrincipalCollection // using a special procedure. It's not loaded as part of the regular LoadIfNeeded call. // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); // Check that we actually support this propery in our store //CheckSupportedProperty(PropertyNames.GroupMembers); if (_members == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Members: creating fresh PrincipalCollection"); if (!this.unpersisted) { // Retrieve the members from the store. // QueryCtx because when this group was retrieved, it was // assigned a _specific_ context for its store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Members: persisted, querying group membership"); BookmarkableResultSet refs = ContextRaw.QueryCtx.GetGroupMembership(this, false); _members = new PrincipalCollection(refs, this); } else { // unpersisted means there's no values to retrieve from the store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Members: unpersisted, creating empty PrincipalCollection"); _members = new PrincipalCollection(new EmptySet(), this); } } return _members; } } // // Public methods // public static new GroupPrincipal FindByIdentity(PrincipalContext context, string identityValue) { return (GroupPrincipal)FindByIdentityWithType(context, typeof(GroupPrincipal), identityValue); } public static new GroupPrincipal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue) { return (GroupPrincipal)FindByIdentityWithType(context, typeof(GroupPrincipal), identityType, identityValue); } public PrincipalSearchResult<Principal> GetMembers() { return GetMembers(false); } public PrincipalSearchResult<Principal> GetMembers(bool recursive) { // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); if (!this.unpersisted) { // Retrieve the members from the store. // QueryCtx because when this group was retrieved, it was // assigned a _specific_ context for its store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetMembers: persisted, querying for members (recursive={0}", recursive); return new PrincipalSearchResult<Principal>(ContextRaw.QueryCtx.GetGroupMembership(this, recursive)); } else { // unpersisted means there's no values to retrieve from the store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetMembers: unpersisted, creating empty PrincipalSearchResult"); return new PrincipalSearchResult<Principal>(null); } } private bool _disposed = false; public override void Dispose() { try { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Dispose: disposing"); if (_members != null) _members.Dispose(); _disposed = true; GC.SuppressFinalize(this); } } finally { base.Dispose(); } } // // Internal "constructor": Used for constructing Groups returned by a query // static internal GroupPrincipal MakeGroup(PrincipalContext ctx) { GroupPrincipal g = new GroupPrincipal(ctx); g.unpersisted = false; return g; } // // Load/Store implementation // // // Loading with query results // internal override void LoadValueIntoProperty(string propertyName, object value) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value != null ? value.ToString() : "null")); switch (propertyName) { case PropertyNames.GroupIsSecurityGroup: _isSecurityGroup = (bool)value; _isSecurityGroupChanged = LoadState.Loaded; break; case PropertyNames.GroupGroupScope: _groupScope = (GroupScope)value; _groupScopeChanged = LoadState.Loaded; break; case PropertyNames.GroupMembers: Debug.Fail("Group.LoadValueIntoProperty: Trying to load Members, but Members is demand-loaded."); break; default: base.LoadValueIntoProperty(propertyName, value); break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal override bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetChangeStatusForProperty: name=" + propertyName); switch (propertyName) { case PropertyNames.GroupIsSecurityGroup: return _isSecurityGroupChanged == LoadState.Changed; case PropertyNames.GroupGroupScope: return _groupScopeChanged == LoadState.Changed; case PropertyNames.GroupMembers: // If Members was never loaded, it couldn't possibly have changed if (_members != null) return _members.Changed; else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetChangeStatusForProperty: members was never loaded"); return false; } default: return base.GetChangeStatusForProperty(propertyName); } } // Given a property name, returns the current value for the property. internal override object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetValueForProperty: name=" + propertyName); switch (propertyName) { case PropertyNames.GroupIsSecurityGroup: return _isSecurityGroup; case PropertyNames.GroupGroupScope: return _groupScope; case PropertyNames.GroupMembers: return _members; default: return base.GetValueForProperty(propertyName); } } // Reset all change-tracking status for all properties on the object to "unchanged". internal override void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "ResetAllChangeStatus"); _groupScopeChanged = (_groupScopeChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _isSecurityGroupChanged = (_isSecurityGroupChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; if (_members != null) _members.ResetTracking(); base.ResetAllChangeStatus(); } /// <summary> /// if isSmallGroup has a value, it means we already checked if the group is small /// </summary> private bool? _isSmallGroup; /// <summary> /// cache the search result for the member attribute /// it will only be set for small groups! /// </summary> internal SearchResult SmallGroupMemberSearchResult { get; private set; } /// <summary> /// Finds if the group is "small", meaning that it has less than MaxValRange values (usually 1500) /// The property list for the searcher of a group has "member" attribute. if there are more results than MaxValRange, there will also be a "member;range=..." attribute /// we can cache the result and don't fear from changes through Add/Remove/Save because the completed/pending lists are looked up before the actual values are /// </summary> internal bool IsSmallGroup() { if (_isSmallGroup.HasValue) { return _isSmallGroup.Value; } _isSmallGroup = false; DirectoryEntry de = (DirectoryEntry)this.UnderlyingObject; Debug.Assert(de != null); if (de != null) { using (DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=*)", new string[] { "member" }, SearchScope.Base)) { SearchResult sr = ds.FindOne(); if (sr != null) { bool rangePropertyFound = false; foreach (string propName in sr.Properties.PropertyNames) { if (propName.StartsWith("member;range=", StringComparison.OrdinalIgnoreCase)) { rangePropertyFound = true; break; } } // we only consider the group "small" if there is a "member" property but no "member;range..." property if (!rangePropertyFound) { _isSmallGroup = true; SmallGroupMemberSearchResult = sr; } } } } return _isSmallGroup.Value; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Planru.DistributedServices.WebAPI.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
namespace AutoMapper.QueryableExtensions { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Impl; using Internal; /// <summary> /// These extension methods are focused through the <see cref="IMappingEngine"/> interface alone. /// Any references to resources like <see cref="IConfigurationProvider"/> should be done through /// the engine. /// </summary> public static class MappingEngineExtensions { private static readonly IExpressionResultConverter[] ExpressionResultConverters = { new MemberGetterExpressionResultConverter(), new MemberResolverExpressionResultConverter(), new NullSubstitutionExpressionResultConverter() }; private static readonly IExpressionBinder[] Binders = { new NullableExpressionBinder(), new AssignableExpressionBinder(), new EnumerableExpressionBinder(), new MappedTypeExpressionBinder(), new CustomProjectionExpressionBinder(), new StringExpressionBinder() }; /// <summary> /// Create an expression tree representing a mapping from the <typeparamref name="TSource"/> type to <typeparamref name="TDestination"/> type /// Includes flattening and expressions inside MapFrom member configuration /// </summary> /// <typeparam name="TSource">Source Type</typeparam> /// <typeparam name="TDestination">Destination Type</typeparam> /// <param name="mappingEngine">Mapping engine instance</param> /// <param name="parameters">Optional parameter object for parameterized mapping expressions</param> /// <param name="membersToExpand">Expand members explicitly previously marked as members to explicitly expand</param> /// <returns>Expression tree mapping source to destination type</returns> public static Expression<Func<TSource, TDestination>> CreateMapExpression<TSource, TDestination>( this IMappingEngine mappingEngine, System.Collections.Generic.IDictionary<string, object> parameters = null, params string[] membersToExpand) { return (Expression<Func<TSource, TDestination>>) mappingEngine.CreateMapExpression(typeof(TSource), typeof(TDestination), parameters, membersToExpand); } /// <summary> /// Create an expression tree representing a mapping from the source type to destination type /// Includes flattening and expressions inside MapFrom member configuration /// </summary> /// <param name="mappingEngine">Mapping engine instance</param> /// <param name="sourceType">Source Type</param> /// <param name="destinationType">Destination Type</param> /// <param name="parameters">Optional parameter object for parameterized mapping expressions</param> /// <param name="membersToExpand">Expand members explicitly previously marked as members to explicitly expand</param> /// <returns>Expression tree mapping source to destination type</returns> public static Expression CreateMapExpression(this IMappingEngine mappingEngine, Type sourceType, Type destinationType, System.Collections.Generic.IDictionary<string, object> parameters = null, params string[] membersToExpand) { //Expression.const parameters = parameters ?? new Dictionary<string, object>(); var cachedExpression = mappingEngine.ExpressionCache.GetOrAdd( new ExpressionRequest(sourceType, destinationType, membersToExpand), tp => CreateMapExpression(mappingEngine, tp, mappingEngine.GetNewTypePairCount())); if (!parameters.Any()) return cachedExpression; var visitor = new ConstantExpressionReplacementVisitor(parameters); return visitor.Visit(cachedExpression); } /// <summary> /// Extention method to project from a queryable using the static <see cref="Mapper.Engine"/> property. /// Due to generic parameter inference, you need to call Project().To to execute the map /// </summary> /// <remarks>Projections are only calculated once and cached</remarks> /// <typeparam name="TSource">Source type</typeparam> /// <param name="source">Queryable source</param> /// <returns>Expression to project into</returns> public static IProjectionExpression Project<TSource>( this IQueryable<TSource> source) { return source.Project(Mapper.Context.Engine); } /// <summary> /// Extention method to project from a queryable using the provided mapping engine /// Due to generic parameter inference, you need to call Project().To to execute the map /// </summary> /// <remarks>Projections are only calculated once and cached</remarks> /// <typeparam name="TSource">Source type</typeparam> /// <param name="source">Queryable source</param> /// <param name="mappingEngine">Mapping engine instance</param> /// <returns>Expression to project into</returns> public static IProjectionExpression Project<TSource>( this IQueryable<TSource> source, IMappingEngine mappingEngine) { return new ProjectionExpression(source, mappingEngine); } /// <summary> /// Extention method to project from a queryable using the static <see cref="Mapper.Engine"/> property. /// </summary> /// <remarks>Projections are only calculated once and cached</remarks> /// <typeparam name="TDestination">Destination type</typeparam> /// <param name="source">Queryable source</param> /// <returns>Expression to project into</returns> public static IQueryable<TDestination> ProjectTo<TDestination>( this IQueryable source) { return source.ProjectTo<TDestination>(Mapper.Context.Engine); } /// <summary> /// Extention method to project from a queryable using the provided mapping engine /// </summary> /// <remarks>Projections are only calculated once and cached</remarks> /// <typeparam name="TDestination">Destination type</typeparam> /// <param name="source">Queryable source</param> /// <param name="mappingEngine">Mapping engine instance</param> /// <returns>Expression to project into</returns> public static IQueryable<TDestination> ProjectTo<TDestination>( this IQueryable source, IMappingEngine mappingEngine) { return new ProjectionExpression(source, mappingEngine).To<TDestination>(); } internal static LambdaExpression CreateMapExpression(this IMappingEngine mappingEngine, ExpressionRequest request, Internal.IDictionary<ExpressionRequest, int> typePairCount) { // this is the input parameter of this expression with name <variableName> ParameterExpression instanceParameter = Expression.Parameter(request.SourceType, "dto"); var total = mappingEngine.CreateMapExpression(request, instanceParameter, typePairCount); return Expression.Lambda(total, instanceParameter); } internal static Expression CreateMapExpression(this IMappingEngine mappingEngine, ExpressionRequest request, Expression instanceParameter, Internal.IDictionary<ExpressionRequest, int> typePairCount) { var typeMap = mappingEngine.ConfigurationProvider.ResolveTypeMap(request.SourceType, request.DestinationType); if (typeMap == null) { const string MessageFormat = "Missing map from {0} to {1}. Create using Mapper.CreateMap<{0}, {1}>."; var message = string.Format(MessageFormat, request.SourceType.Name, request.DestinationType.Name); throw new InvalidOperationException(message); } var bindings = mappingEngine.CreateMemberBindings(request, typeMap, instanceParameter, typePairCount); var parameterReplacer = new ParameterReplacementVisitor(instanceParameter); var visitor = new NewFinderVisitor(); var ctorExpr = typeMap.ConstructExpression ?? Expression.Lambda(Expression.New(request.DestinationType)); visitor.Visit(parameterReplacer.Visit(ctorExpr)); var expression = Expression.MemberInit( visitor.NewExpression, bindings.ToArray() ); return expression; } private class NewFinderVisitor : ExpressionVisitor { public NewExpression NewExpression { get; private set; } protected override Expression VisitNew(NewExpression node) { NewExpression = node; return base.VisitNew(node); } } private static List<MemberBinding> CreateMemberBindings(this IMappingEngine mappingEngine, ExpressionRequest request, TypeMap typeMap, Expression instanceParameter, Internal.IDictionary<ExpressionRequest, int> typePairCount) { var bindings = new List<MemberBinding>(); var visitCount = typePairCount.AddOrUpdate(request, 0, (tp, i) => i + 1); if (visitCount >= typeMap.MaxDepth) return bindings; var resolvablePropertyMaps = typeMap.GetPropertyMaps().Where(pm => pm.CanResolveValue()).ToArray(); foreach (var propertyMap in resolvablePropertyMaps) { var result = ResolveExpression(propertyMap, request.SourceType, instanceParameter); if (propertyMap.ExplicitExpansion && !request.IncludedMembers.Contains(propertyMap.DestinationProperty.Name)) continue; var propertyTypeMap = mappingEngine.ConfigurationProvider.ResolveTypeMap(result.Type, propertyMap.DestinationPropertyType); var propertyRequest = new ExpressionRequest(result.Type, propertyMap.DestinationPropertyType, request.IncludedMembers); var binder = Binders.FirstOrDefault(b => b.IsMatch(propertyMap, propertyTypeMap, result)); if (binder == null) { var message = $"Unable to create a map expression from {propertyMap.SourceMember.DeclaringType.Name}.{propertyMap.SourceMember.Name} ({result.Type}) to {propertyMap.DestinationProperty.MemberInfo.DeclaringType.Name}.{propertyMap.DestinationProperty.Name} ({propertyMap.DestinationPropertyType})"; throw new AutoMapperMappingException(message); } var bindExpression = binder.Build(mappingEngine, propertyMap, propertyTypeMap, propertyRequest, result, typePairCount); bindings.Add(bindExpression); } return bindings; } private static ExpressionResolutionResult ResolveExpression(PropertyMap propertyMap, Type currentType, Expression instanceParameter) { var result = new ExpressionResolutionResult(instanceParameter, currentType); foreach (var resolver in propertyMap.GetSourceValueResolvers()) { var matchingExpressionConverter = ExpressionResultConverters.FirstOrDefault(c => c.CanGetExpressionResolutionResult(result, resolver)); if (matchingExpressionConverter == null) throw new Exception("Can't resolve this to Queryable Expression"); result = matchingExpressionConverter.GetExpressionResolutionResult(result, propertyMap, resolver); } return result; } private class ConstantExpressionReplacementVisitor : ExpressionVisitor { private readonly System.Collections.Generic.IDictionary<string, object> _paramValues; public ConstantExpressionReplacementVisitor( System.Collections.Generic.IDictionary<string, object> paramValues) { _paramValues = paramValues; } protected override Expression VisitMember(MemberExpression node) { if (!node.Member.DeclaringType.Name.Contains("<>")) return base.VisitMember(node); if (!_paramValues.ContainsKey(node.Member.Name)) return base.VisitMember(node); return Expression.Convert( Expression.Constant(_paramValues[node.Member.Name]), node.Member.GetMemberType()); } } } }
// 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.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Globalization { /*=================================KoreanCalendar========================== ** ** Korean calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar. ** That is, ** Korean year = Gregorian year + 2333. So 2000/01/01 A.D. is Korean 4333/01/01 ** ** 0001/1/1 A.D. is Korean year 2334. ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 0001/01/01 9999/12/31 ** Korean 2334/01/01 12332/12/31 ============================================================================*/ public class KoreanCalendar : Calendar { // // The era value for the current era. // public const int KoreanEra = 1; // Since // Gregorian Year = Era Year + yearOffset // Gregorian Year 1 is Korean year 2334, so that // 1 = 2334 + yearOffset // So yearOffset = -2333 // Gregorian year 2001 is Korean year 4334. //m_EraInfo[0] = new EraInfo(1, new DateTime(1, 1, 1).Ticks, -2333, 2334, GregorianCalendar.MaxYear + 2333); // Initialize our era info. internal static EraInfo[] koreanEraInfo = new EraInfo[] { new EraInfo( 1, 1, 1, 1, -2333, 2334, GregorianCalendar.MaxYear + 2333) // era #, start year/month/day, yearOffset, minEraYear }; internal GregorianCalendarHelper helper; public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } public KoreanCalendar() { try { new CultureInfo("ko-KR"); } catch (ArgumentException e) { throw new TypeInitializationException(this.GetType().ToString(), e); } helper = new GregorianCalendarHelper(this, koreanEraInfo); } internal override CalendarId ID { get { return CalendarId.KOREA; } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } /*=================================GetDaysInMonth========================== **Action: Returns the number of days in the month given by the year and month arguments. **Returns: The number of days in the given month. **Arguments: ** year The year in Korean calendar. ** month The month ** era The Japanese era value. **Exceptions ** ArgumentException If month is less than 1 or greater * than 12. ============================================================================*/ public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } public override int[] Eras { get { return (helper.Eras); } } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 4362; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, helper.MaxYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); return (helper.ToFourDigitYear(year, this.TwoDigitYearMax)); } } }
using UnityEngine; using System.Collections.Generic; using UnitySpriteCutter.Cutters; using UnitySpriteCutter.Tools; using GameObjectCreationMode = UnitySpriteCutter.SpriteCutterInput.GameObjectCreationMode; namespace UnitySpriteCutter { public class SpriteCutterInput { public Vector2 lineStart; public Vector2 lineEnd; /// <summary> /// GameObject to cut. Has to have SpriteRenderer or MeshRenderer or cut wont take place. /// </summary> public GameObject gameObject; /// <summary> /// By default, objects are cut only if their colliders can be cut with given line. /// If set to true, colliders doesn't matter and aren't cut. /// </summary> public bool dontCutColliders; public enum GameObjectCreationMode { /// <summary> /// The original gameObject is converted into the "firstSide" gameObject. /// Use this, if you want to intantiate new "cutted" gameObject from an existing one. Default value. /// </summary> CUT_OFF_NEW = 0, /// <summary> /// Works as CUT_OFF_ONE, but instead of intantiating an entirelynew GameObject, /// it instantiates a "cutted" copy of the original gameObject. /// </summary> CUT_OFF_COPY = 1, /// <summary> /// The original gameObject stays as it was before cutting. /// Instead, SpriteCutter instantiates two new gameObjects with first and second side of the cut. /// </summary> CUT_INTO_TWO = 2, } public GameObjectCreationMode gameObjectCreationMode; } public class SpriteCutterOutput { public GameObject firstSideGameObject; public GameObject secondSideGameObject; } public static class SpriteCutter { struct SideCutData { public Mesh cuttedMesh; public List<PolygonColliderParametersRepresentation> cuttedCollidersRepresentations; } /// <summary> /// Returns null, if cutting didn't took place. /// </summary> public static SpriteCutterOutput Cut( SpriteCutterInput input ) { if ( input.gameObject == null ) { Debug.LogWarning( "SpriteCutter.Cut exceuted with null gameObject!" ); return null; } /* Cutting mesh and collider */ Vector3 localLineStart = input.gameObject.transform.InverseTransformPoint( input.lineStart ); Vector3 localLineEnd = input.gameObject.transform.InverseTransformPoint( input.lineEnd ); SpriteRenderer spriteRenderer = input.gameObject.GetComponent<SpriteRenderer>(); MeshRenderer meshRenderer = input.gameObject.GetComponent<MeshRenderer>(); FlatConvexPolygonMeshCutter.CutResult meshCutResult = CutSpriteOrMeshRenderer( localLineStart, localLineEnd, spriteRenderer, meshRenderer ); if ( meshCutResult.DidNotCut() ) { return null; } FlatConvexCollidersCutter.CutResult collidersCutResults; if ( input.dontCutColliders ) { collidersCutResults = new FlatConvexCollidersCutter.CutResult(); } else { collidersCutResults = CutColliders( localLineStart, localLineEnd, input.gameObject.GetComponents<Collider2D>() ); if ( collidersCutResults.DidNotCut() ) { return null; } } SideCutData firstCutData = new SideCutData() { cuttedMesh = meshCutResult.firstSideMesh, cuttedCollidersRepresentations = collidersCutResults.firstSideColliderRepresentations }; SideCutData secondCutData = new SideCutData() { cuttedMesh = meshCutResult.secondSideMesh, cuttedCollidersRepresentations = collidersCutResults.secondSideColliderRepresentations }; /* Second side result - created as new GameObject or instantiated copy of the original GameObject. */ SpriteCutterGameObject secondSideResult = null; switch ( input.gameObjectCreationMode ) { case GameObjectCreationMode.CUT_OFF_NEW: case GameObjectCreationMode.CUT_INTO_TWO: secondSideResult = SpriteCutterGameObject.CreateNew( input.gameObject, true ); PrepareResultGameObject( secondSideResult, spriteRenderer, meshRenderer, secondCutData ); break; case GameObjectCreationMode.CUT_OFF_COPY: secondSideResult = SpriteCutterGameObject.CreateAsInstantiatedCopyOf( input.gameObject, true ); SpriteRenderer copiedSpriteRenderer = secondSideResult.gameObject.GetComponent<SpriteRenderer>(); MeshRenderer copiedMeshRenderer = secondSideResult.gameObject.GetComponent<MeshRenderer>(); if ( copiedSpriteRenderer != null ) { RendererParametersRepresentation tempParameters = new RendererParametersRepresentation(); tempParameters.CopyFrom( copiedSpriteRenderer ); SafeSpriteRendererRemoverBehaviour.get.RemoveAndWaitOneFrame( copiedSpriteRenderer, onFinish: () => { PrepareResultGameObject( secondSideResult, tempParameters, secondCutData ); } ); } else { PrepareResultGameObject( secondSideResult, copiedSpriteRenderer, copiedMeshRenderer, secondCutData ); } break; } /* First side result */ SpriteCutterGameObject firstSideResult = null; switch ( input.gameObjectCreationMode ) { case GameObjectCreationMode.CUT_OFF_NEW: case GameObjectCreationMode.CUT_OFF_COPY: firstSideResult = SpriteCutterGameObject.CreateAs( input.gameObject ); if ( spriteRenderer != null ) { RendererParametersRepresentation tempParameters = new RendererParametersRepresentation(); tempParameters.CopyFrom( spriteRenderer ); SafeSpriteRendererRemoverBehaviour.get.RemoveAndWaitOneFrame( spriteRenderer, onFinish: () => { PrepareResultGameObject( firstSideResult, tempParameters, firstCutData ); } ); } else { PrepareResultGameObject( firstSideResult, spriteRenderer, meshRenderer, firstCutData ); } break; case GameObjectCreationMode.CUT_INTO_TWO: firstSideResult = SpriteCutterGameObject.CreateNew( input.gameObject, true ); PrepareResultGameObject( firstSideResult, spriteRenderer, meshRenderer, firstCutData ); break; } return new SpriteCutterOutput() { firstSideGameObject = firstSideResult.gameObject, secondSideGameObject = secondSideResult.gameObject, }; } static FlatConvexPolygonMeshCutter.CutResult CutSpriteOrMeshRenderer( Vector2 lineStart, Vector2 lineEnd, SpriteRenderer spriteRenderer, MeshRenderer meshRenderer ) { Mesh originMesh = GetOriginMeshFrom( spriteRenderer, meshRenderer ); return FlatConvexPolygonMeshCutter.Cut( lineStart, lineEnd, originMesh ); } static Mesh GetOriginMeshFrom( SpriteRenderer spriteRenderer, MeshRenderer meshRenderer ) { if ( spriteRenderer != null ) { return SpriteMeshConstructor.ConstructFromRendererBounds( spriteRenderer ); } else { return meshRenderer.GetComponent<MeshFilter>().mesh; } } static FlatConvexCollidersCutter.CutResult CutColliders( Vector2 lineStart, Vector2 lineEnd, Collider2D[] colliders ) { return FlatConvexCollidersCutter.Cut( lineStart, lineEnd, colliders ); } static void PrepareResultGameObject( SpriteCutterGameObject resultGameObject, SpriteRenderer spriteRenderer, MeshRenderer meshRenderer, SideCutData cutData ) { resultGameObject.AssignMeshFilter( cutData.cuttedMesh ); if ( spriteRenderer != null ) { resultGameObject.AssignMeshRendererFrom( spriteRenderer ); } else { resultGameObject.AssignMeshRendererFrom( meshRenderer ); } if ( cutData.cuttedCollidersRepresentations != null ) { resultGameObject.BuildCollidersFrom( cutData.cuttedCollidersRepresentations ); } } static void PrepareResultGameObject( SpriteCutterGameObject resultGameObject, RendererParametersRepresentation tempParameters, SideCutData cutData ) { resultGameObject.AssignMeshFilter( cutData.cuttedMesh ); resultGameObject.AssignMeshRendererFrom( tempParameters ); if ( cutData.cuttedCollidersRepresentations != null ) { resultGameObject.BuildCollidersFrom( cutData.cuttedCollidersRepresentations ); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Web.UI; using System.Web.Services; using System.IO; using System.Threading; using System.Web; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Reflection; using System.Drawing; using System.Collections.Specialized; using System.Web.Script.Services; using LTAF; namespace LTAF.Engine { /// <summary> /// TestDriverPage /// </summary> [GenerateScriptType(typeof(PopupAction))] public class TestDriverPage : Page { private IAspNetPageService _aspNetService = null; private static SystemWebExtensionsWrapper _systemWebExtensionsAbstractions; private static TestCaseManager _testcaseManager; /// <summary>TestcaseTypes</summary> protected static Dictionary<string, Type> _testcaseTypes; private TestcaseExecutor _testcaseExecutor = null; private bool _generateInterface = true; private TreeView _testcasesTreeview; private PlaceHolder _contentPlaceHolder; private Label _errorsLabel; private Label _threadId; #region Constructor /// <summary> /// ctor /// </summary> public TestDriverPage() : this(new AspNetPageService()) { } internal TestDriverPage(IAspNetPageService aspNetService) { _aspNetService = aspNetService; if (_systemWebExtensionsAbstractions == null) { _systemWebExtensionsAbstractions = new SystemWebExtensionsWrapper(aspNetService); } if (_testcaseManager == null) { _testcaseManager = new TestCaseManager(); } } internal TestDriverPage(IAspNetPageService aspNetService, SystemWebExtensionsWrapper sweWrapper): this(aspNetService) { _systemWebExtensionsAbstractions = sweWrapper; } #endregion #region Page Controls /// <summary> /// Checkbox that indicates whether to write the log to disk when test run is finished /// </summary> protected internal CheckBox WriteLogToDiskCheckBox { get; set; } /// <summary> /// Checkbox that indicates whether to show the testcase console /// </summary> protected internal CheckBox ShowConsoleCheckBox { get; set; } /// <summary> /// Panel that represents the middle area of the driver UI /// </summary> protected internal Panel TestsPanel { get; set; } /// <summary> /// Panel that represents the footer area of the driver UI /// </summary> protected internal Panel FooterPanel { get; set; } /// <summary> /// Reference to the place holder used to generate all the page's content /// </summary> protected internal PlaceHolder ContentPlaceHolder { get { if (_contentPlaceHolder == null) { _contentPlaceHolder = _aspNetService.FindControl(this, "DriverPageContentPlaceHolder") as PlaceHolder; } return _contentPlaceHolder; } set { _contentPlaceHolder = value; } } /// <summary> /// Reference to the TreeView containing the test cases /// </summary> protected internal TreeView TestCasesTreeView { get { return _testcasesTreeview; } set { _testcasesTreeview = value; } } /// <summary> /// Reference to the label that displays the ThreadId /// </summary> protected internal Label ThreadIdLabel { get { return _threadId; } set { _threadId = value; } } /// <summary> /// Reference to the label that displays errors /// </summary> protected Label Errors { get { return _errorsLabel; } set { _errorsLabel = value; } } #endregion #region Properties /// <summary> /// Reference to a class that abstract the use of types/methods inside System.Web.Extensions /// </summary> internal static SystemWebExtensionsWrapper SystemWebExtensionsAbstractions { get { return _systemWebExtensionsAbstractions; } set { _systemWebExtensionsAbstractions = value; } } /// <summary> /// Whether the test interface should be generated automatically. /// This must be set before OnInit to take effect. /// </summary> protected internal bool AutoGenerateInterface { get { return _generateInterface; } set { _generateInterface = value; } } /// <summary> /// The testcase executor object to be used by the driver page /// </summary> protected TestcaseExecutor TestcaseExecutor { get { if (_testcaseExecutor == null) { _testcaseExecutor = new TestcaseExecutor(); } return _testcaseExecutor; } set { _testcaseExecutor = value; } } /// <summary> /// Whether logging should be detailed or rudimentary /// </summary> public WebTestLogDetail LogDetail { get { object result = ViewState["LogDetail"]; return result == null ? WebTestLogDetail.Default : (WebTestLogDetail) result; } set { ViewState["LogDetail"] = value; } } #endregion /// <summary> /// OnInit /// </summary> protected override void OnInit(EventArgs e) { base.OnInit(e); OnInitInternal(); } /// <summary> /// Sets up the service locators and the UI /// </summary> internal void OnInitInternal() { SystemWebExtensionsAbstractions.Initialize(this); if (!_aspNetService.GetIsPostBack(this)) { _testcaseTypes = new Dictionary<string, Type>(); SetupServiceLocator(_aspNetService.GetApplicationPath(this)); } if (_generateInterface) { GenerateInterface(); } _testcasesTreeview.Load += new EventHandler(TestcasesTreeview_Load); } /// <summary> /// Sets up the global ServiceLocator /// </summary> private void SetupServiceLocator(string applicationPath) { ServiceLocator.ApplicationPathFinder = new ApplicationPathFinder(applicationPath); ServiceLocator.BrowserCommandExecutorFactory = new BrowserCommandExecutorFactory(); } /// <summary> /// OnLoadComplete /// </summary> protected override void OnLoadComplete(EventArgs e) { base.OnLoadComplete(e); OnLoadCompleteInternal(); } internal void OnLoadCompleteInternal() { // Only auto-select or auto-run on the first request if (!_aspNetService.GetIsPostBack(this)) { // Get query string values QueryStringParameters queryParams = new QueryStringParameters(); queryParams.LoadFromQueryString(_aspNetService.GetQueryString(this)); BrowserVersions browser = BrowserUtility.GetBrowser(_aspNetService.GetBrowserName(this), _aspNetService.GetBrowserMajorVersion(this)); LogDetail = queryParams.LogDetail; this.WriteLogToDiskCheckBox.Checked = queryParams.WriteLog; this.ShowConsoleCheckBox.Checked = queryParams.ShowConsole; // Auto-select tests with a given tag if (!String.IsNullOrEmpty(queryParams.Tag)) { _testcaseManager.SelectTaggedTests(this.TestCasesTreeView, queryParams.Tag, browser); } else if (queryParams.Run) { _testcaseManager.SelectAllTests(this.TestCasesTreeView, browser); } // Optionally remove unselected tests if (queryParams.Filter) { _testcaseManager.FilterIgnoredTests(this.TestCasesTreeView); } // Auto-run the selected tests (or all tests if none are selected) if (queryParams.Run) { RunTestCases(); } } // Change UI depending if showing console or not. if (this.ShowConsoleCheckBox.Checked) { this.TestsPanel.CssClass = "tests"; this.FooterPanel.Visible = true; } else { this.TestsPanel.CssClass = "testsNoConsole"; this.FooterPanel.Visible = false; } } /// <summary> /// Creates the default UI /// </summary> internal void GenerateInterface() { PlaceHolder mainContent = ContentPlaceHolder; //Create Header Panel Panel headerDiv = new Panel(); headerDiv.ID = "Header"; headerDiv.CssClass = "header"; mainContent.Controls.Add(headerDiv); //Create Test Panel this.TestsPanel = new Panel(); this.TestsPanel.ID = "Tests"; this.TestsPanel.CssClass = "tests"; mainContent.Controls.Add(this.TestsPanel); //Create Footer Panel this.FooterPanel = new Panel(); this.FooterPanel.ID = "Footer"; this.FooterPanel.CssClass = "footer"; mainContent.Controls.Add(this.FooterPanel); //Add Title bar to Header Panel titleDiv = new Panel(); titleDiv.ID = "title"; titleDiv.CssClass = "titleBar"; //Add Help to Title System.Web.UI.WebControls.Image helpImage = new System.Web.UI.WebControls.Image(); helpImage.ID = "help"; helpImage.CssClass = "helpIcon"; helpImage.ImageUrl = _aspNetService.GetClientScriptWebResourceUrl(this, typeof(TestDriverPage), "LTAF.Engine.Resources.helpicon.gif"); string helpPageUrl = _aspNetService.GetClientScriptWebResourceUrl(this, typeof(TestDriverPage), "LTAF.Engine.Resources.HelpPage.htm"); titleDiv.Controls.Add(new LiteralControl("<a href=\"#\" onclick=\"javascript:window.open('" + helpPageUrl + "','Help','toolbar=0, height=500, width=700, scrollbars=yes, resizable=yes');\" style=\"text-decoration: none\" title=\"help (new window)\">")); titleDiv.Controls.Add(helpImage); titleDiv.Controls.Add(new LiteralControl("</a>")); //Add Text to Title titleDiv.Controls.Add(new LiteralControl("<b>Lightweight Test Automation Framework</b>")); headerDiv.Controls.Add(titleDiv); //Add the Menu to the Header Panel menuPanel = new Panel(); menuPanel.ID = "MenuPanel"; menuPanel.CssClass = "menu"; headerDiv.Controls.Add(menuPanel); //Add Write to Disk Option to Menu this.WriteLogToDiskCheckBox = new CheckBox(); this.WriteLogToDiskCheckBox.ID = "WriteLogCheckBox"; this.WriteLogToDiskCheckBox.Text = "Write Log to Disk"; menuPanel.Controls.Add(this.WriteLogToDiskCheckBox); menuPanel.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;")); //Add Show Test Console Option to Menu this.ShowConsoleCheckBox = new CheckBox(); this.ShowConsoleCheckBox.ID = "ShowConsoleCheckBox"; this.ShowConsoleCheckBox.Checked = true; this.ShowConsoleCheckBox.AutoPostBack = true; this.ShowConsoleCheckBox.Text = "Show Console"; menuPanel.Controls.Add(this.ShowConsoleCheckBox); menuPanel.Controls.Add(new LiteralControl("<br />")); //Add Error Console to Menu _errorsLabel = new Label(); _errorsLabel.ID = "ErrorsLabel"; _errorsLabel.ForeColor = Color.Red; _errorsLabel.Font.Bold = true; menuPanel.Controls.Add(_errorsLabel); menuPanel.Controls.Add(new LiteralControl("<br />")); //Add Control Buttons to Menu Panel buttonPanel = new Panel(); buttonPanel.ID = "ButtonPanel"; buttonPanel.HorizontalAlign = HorizontalAlign.Center; menuPanel.Controls.Add(buttonPanel); //Add Run Button to Button Menu Button runButton = new Button(); runButton.ID = "RunTestcasesButton"; runButton.Text = "Run Tests"; runButton.Click += new EventHandler(RunTestcasesButton_Click); runButton.OnClientClick = "return prepareClientUI()"; buttonPanel.Controls.Add(runButton); headerDiv.DefaultButton = runButton.ID; //Add Run Failed Button to Button Menu Button runFailedButton = new Button(); runFailedButton.ID = "failedTests"; runFailedButton.Text = "Run Failed Tests"; runFailedButton.OnClientClick = "RerunFailedTests();return false;"; runFailedButton.Attributes.Add("disabled", "disabled"); buttonPanel.Controls.Add(runFailedButton); //Add Progress Spinner to Button Menu HtmlImage spinnerImage = new HtmlImage(); spinnerImage.ID = "spinner"; spinnerImage.Alt = "."; spinnerImage.Width = 12; spinnerImage.Height = 12; spinnerImage.Style.Add("visibility", "hidden"); spinnerImage.Src = _aspNetService.GetClientScriptWebResourceUrl(this, typeof(TestDriverPage), "LTAF.Engine.Resources.spinner.gif"); buttonPanel.Controls.Add(new LiteralControl("<br />")); buttonPanel.Controls.Add(spinnerImage); //Add Thread Label to Button Menu _threadId = new Label(); _threadId.ID = "ThreadId"; _threadId.EnableViewState = false; _threadId.Font.Italic = true; buttonPanel.Controls.Add(new LiteralControl("&nbsp;&nbsp;")); buttonPanel.Controls.Add(_threadId); //Add Test Case Treeview _testcasesTreeview = new TreeView(); _testcasesTreeview.ID = "testcasesTreeView"; _testcasesTreeview.Font.Size = FontUnit.Small; _testcasesTreeview.Font.Names = new string[3] { "Franklin", "Gothic", "Medium" }; _testcasesTreeview.ShowCheckBoxes = TreeNodeTypes.Leaf; this.TestsPanel.Controls.Add(_testcasesTreeview); //Add Commands Label to Footer Label commandsLabel = new Label(); commandsLabel.AssociatedControlID = "TraceConsole"; commandsLabel.ID = "Commands"; commandsLabel.Text = "Console: "; this.FooterPanel.Controls.Add(commandsLabel); //Add Debug Console to Footer Panel debugArea = new Panel(); debugArea.ID = "TraceConsole"; debugArea.CssClass = "debugConsole"; this.FooterPanel.Controls.Add(new LiteralControl("<br />")); this.FooterPanel.Controls.Add(debugArea); string scriptBlock = @" function prepareClientUI() { document.getElementById('ThreadId').innerHTML = '[Loading Tests. Please Wait.]'; return true; }"; _aspNetService.RegisterClientScriptBlock(this, typeof(Page), "BeforeTestExecution", scriptBlock, true); } private void TestcasesTreeview_Load(object sender, EventArgs e) { TestcasesTreeview_LoadInternal(); } internal void TestcasesTreeview_LoadInternal() { if (!_aspNetService.GetIsPostBack(this)) { // Load the test case tree nodes in alphabetical order and store them in ViewState TreeNode root = null; if (_testcasesTreeview.Nodes.Count > 0) { root = _testcasesTreeview.Nodes[0]; } else { root = new TreeNode("All Test Cases"); _testcasesTreeview.Nodes.Add(root); } _testcaseManager.PopulateTreeView(root); } else if (_aspNetService.GetRequestForm(this)["__EVENTTARGET"] == _testcasesTreeview.ClientID) { // if post came from treeview, then we toggle checkbox selection if (_testcasesTreeview.SelectedNode != null) { bool select = !IsChildNodeChecked(_testcasesTreeview.SelectedNode); UpdateChildNodes(_testcasesTreeview.SelectedNode, select); } } } private bool IsChildNodeChecked(TreeNode parentNode) { foreach (TreeNode node in parentNode.ChildNodes) { if (node.Checked || IsChildNodeChecked(node)) { return true; } } return false; } private void UpdateChildNodes(TreeNode parentNode, bool select) { foreach (TreeNode node in parentNode.ChildNodes) { node.Checked = select; UpdateChildNodes(node, select); } } private void RunTestcasesButton_Click(object sender, EventArgs e) { RunTestCases(); } /// <summary> /// RunTestCases /// </summary> protected virtual void RunTestCases() { IList<Testcase> testsToExecute = _testcaseManager.GetSelectedTestCases(_testcasesTreeview); if (WriteLogToDiskCheckBox.Checked) { string testPath = Server.MapPath(""); TestcaseLogger logger = new TestcaseLogger(testPath, this.TestcaseExecutor); // verify user has write access to folder try { logger.WriteStartupFile(); } catch (UnauthorizedAccessException) { _errorsLabel.Text = String.Format("Error: Write to log feature requires write access to '{0}' directory.", testPath); return; } } // Get a testcase executor and start int threadId = TestcaseExecutor.Start(testsToExecute, Request); _threadId.Text = "[Current ThreadId: " + threadId.ToString() + "]"; string startupScript = @" TestExecutor.set_threadId(" + threadId + @"); TestExecutor.set_logDetail(" + ((int) LogDetail) + @"); TestExecutor.TestcaseExecutedCallback = TreeView_TestcaseExecuted; TestExecutor.start();"; SystemWebExtensionsAbstractions.RegisterStartupScript(this, typeof(Page), "LTAF.Startup", startupScript, true); } /// <summary> /// GetCommand /// </summary> [WebMethod] public static BrowserCommand GetCommand(int threadId, BrowserInfo resultOfLastCommand) { return CommandManager.SetResultAndGetNextCommand(threadId, resultOfLastCommand); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace QuizDuell { public enum QuizDuellPlattform { IOS, ANDROID } public enum GameState { Waiting = 0, Active = 1, Finished = 2, GiveUp = 5, TimedOut = 6, Started = 10 } /// <summary> /// Inofficial Quizduell API interface. /// </summary> public class QuizDuellApi { public string Host { get; set; } // MD5-SALT - Different per Country/Plattform // qkgermany: SQ2zgOTmQc8KXmBP // TODO: Reverse the md5 salt for qkunited public string Salt { get; set; } // HMAC-KEYS - Different per Country/Plattform // IOS: 7GprrSCirEToJjG5 // APK: irETGpoJjG57rrSC public string Key { get; set; } // Rest Client public RestClient Client { get; set; } public CookieContainer Cookies { get; set; } public string UserAgent { get; set; } public QuizDuellPlattform Plattform { get; set; } // TODO: think about only maintaining one api Platform instead of the two different versions private Random random = new Random(); /// <summary> /// Creates the API interface. Expects either an authentication cookie within /// the user supplied cookie jar or a subsequent call to /// QuizduellApi.LoginUser() or QuizduellApi.CreateUser(). /// </summary> /// <param name="host"></param> /// <param name="cookies">Stores authentication tokens with each request made to the API</param> /// <param name="userAgent"></param> /// <param name="salt"></param> /// <param name="key"></param> public QuizDuellApi(string host, CookieContainer cookies = null, QuizDuellPlattform plattform = QuizDuellPlattform.ANDROID, string userAgent = "Quizduell A 1.3.2", string salt = "SQ2zgOTmQc8KXmBP", string key = "irETGpoJjG57rrSC") { // TODO: Create an instance of the config class, so we can deseriliaze the config data to a file at the end of the program run. Host = host; Plattform = plattform; Salt = salt; Key = key; UserAgent = userAgent; random = new Random(); if (cookies != null) { Cookies = cookies; Client = new RestClient(userAgent, cookies); } else { Client = new RestClient(userAgent); } } public QuizDuellApi(QuizDuellConfig config) { // TODO: Refactor the Properties so that they just wrap an instance of the config class. // NOTE: This way we can deserialize the config file at the end of program run and the user of the api does not have to deal with that. --- Think about this first, does it make sense that the api deals with deserializisation of the config file? Host = config.Host; Salt = config.Salt; Key = config.Key; UserAgent = config.UserAgent; Plattform = config.Plattform; Cookies = config.Cookies; Client = new RestClient(UserAgent, Cookies); random = new Random(); } // This method will generate an authcode, post_params will be sorted by name and then concatined to the other parameters private string GetAuthCode(string host, string relativeUrl, string client_date, IDictionary<string, string> post_params = null) { string auth = String.Format("https://{0}{1}{2}", host, relativeUrl, client_date); // Sort the post_params array and join it as a string if (post_params != null) { // NOTE: For HMAC post_params should not be urlencoded var list = new List<string>(post_params.Values); list.Sort(); // NOTE: Why would they use different sort orders on different platforms ?_? if (Plattform == QuizDuellPlattform.ANDROID) { // HACK: Default Comparer Sorts Special Chars, Numbers, Characters while ANDROID requires Numbers, Special Chars, Characters list.Sort((x, y) => { if (!Char.IsLetterOrDigit(x[0])) { if (Char.IsLetter(y[0])) return -1; else if (Char.IsDigit(y[0])) return 1; } // return x.CompareTo(y); // Does not work since it's using Culture Specific information return System.String.Compare(x, y, System.StringComparison.Ordinal); }); } auth += String.Join("", list); } return EncodeHMAC(auth, Key); ; } // This method will return the base 64 encoded string using the given input and key. private string EncodeHMAC(string input, string key) { Debug.WriteLine("HMAC-INPUT: " + input); var encoding = new UTF8Encoding(); var hmac = new HMACSHA256(encoding.GetBytes(key)); byte[] messageBytes = encoding.GetBytes(input); byte[] hashedValue = hmac.ComputeHash(messageBytes); // Convert to base64 string string base64 = Convert.ToBase64String(hashedValue); return base64; } // This Hashes the Salt + Password as MD5 and then returns it in hex representation. private string EncodePassword(string password, string password_salt) { byte[] md5 = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(password_salt + password)); // Turn the MD5 Bytes into their hex representation // string hashPassword = BitConverter.ToString(byteHashedPassword).Replace("-","").ToLower(); var hex = new StringBuilder(); foreach (var b in md5) { hex.AppendFormat("{0:x2}", b); } // lowercase: x2, use X2 for uppercase Debug.WriteLine("MD5_STRING: " + hex.ToString()); return hex.ToString(); } // Turns a Collection of KeyValuePairs to a url-encoded post_data string private string DictionaryToPostDataString(IDictionary<string, string> data) { string delimiter = String.Empty; var values = new StringBuilder(); // Alternative to force the sort Order: //foreach (KeyValuePair<string, string> kvp in data.OrderBy(k => k.Value)) // NOTE: Sorted Params? foreach (KeyValuePair<string, string> kvp in data) { // Alternative //System.Uri.EscapeDataString() //System.Net.WebUtility.UrlEncode() // EscapeUriString only escapes these characters: // ` % ^ [ ] \ { } | " < > space // NOTE: Why are [ and ] not escaped? // EscapeDataString escapes all of these: // = ` @ # $ % ^ & + [ ] \ { } | ; : " , / < > ? space values.Append(delimiter); values.Append(Uri.EscapeUriString(kvp.Key)); values.Append("="); //values.Append(Uri.EscapeUriString(kvp.Value).Replace("[", "%5B").Replace("]", "%5D")); //values.Append(System.Net.WebUtility.UrlEncode(kvp.Value).Replace("%40", "@")); values.Append(Uri.EscapeDataString(kvp.Value).Replace("%20", "+").Replace("%40", "@")); // HACK: Fix this UrlEncoding Mess, this breaks create user since mail contains @ which is not supposed to be urlencoded delimiter = "&"; } return values.ToString(); } [Obsolete] // TODO: Change all the Api Methods to use IDictionarys for the post_params instead of JObject private JObject Request(string relativeUrl, JObject post_params) { IDictionary<string, JToken> d = (JObject)post_params; Dictionary<string, string> dictionary = d.ToDictionary(pair => pair.Key, pair => (string)pair.Value); return Request(relativeUrl, dictionary); } private JObject Request(string relativeUrl, IDictionary<string, string> post_params = null) { return Request(Host, relativeUrl, post_params); } private JObject Request(string host, string relativeUrl, IDictionary<string, string> post_params) { string uri = String.Format("https://{0}{1}", host, relativeUrl); string clientDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string auth = GetAuthCode(host, relativeUrl, clientDate, post_params); // Custom Headers var customHeaders = new WebHeaderCollection(); if (Plattform == QuizDuellPlattform.ANDROID) { customHeaders.Set("dt", "a"); } if (Plattform == QuizDuellPlattform.ANDROID) { customHeaders.Set("Accept-Encoding", "identity"); } customHeaders.Set("Authorization", auth); customHeaders.Set("clientdate", clientDate); string responseText = "{}"; if (post_params != null) { // Post Request string postData = DictionaryToPostDataString(post_params); responseText = Client.MakeRequest(uri, "", postData, customHeaders); } else { // Get Request responseText = Client.MakeRequest(uri, "", customHeaders); } // Make sure that we have a valid JSON Object if (responseText == null || responseText.Contains("ACCESS NOT OK") || responseText.Contains("Error")) { // responseText = "{\"error\": \"ACCESS NOT OK\"}"; responseText = "{\"error\": \"" + responseText + "\"}"; } var jObject = JObject.Parse(responseText); return jObject; } #region /users/ #region User /// <summary> /// Creates a new Quizduell user. The user will automatically be logged in. /// </summary> /// <param name="name">the username for the quizduell account</param> /// <param name="password">the password for the new account</param> /// <param name="email">optional email parameter</param> /// <returns> /// Returns the following JSON structure on success: /// { /// "logged_in": true, /// "settings": {...}, /// "user": {...} /// } /// </returns> public JObject CreateUser(string name, string password, string email = "") { return CreateUser(name, password, Salt, email); } private JObject CreateUser(string name, string password, string password_salt, string email = "") { /* data = { 'name': name, 'email': email, 'pwd': hashlib.md5(self.password_salt + password).hexdigest() }*/ dynamic data = new JObject(); data.name = name; if (!String.IsNullOrEmpty(email)) { data.email = email; } // TODO: Email Creation no longer works, since changing sort order and encoding scheme. data.pwd = EncodePassword(password, password_salt); return Request("/users/create", data); } /// <summary> /// Authenticates an existing Quizduell user. /// @attention: Any user can only log in 10 times every 24 hours! /// </summary> /// <param name="name">the username for the quizduell account</param> /// <param name="password">the password for the quizduell account</param> /// <returns> /// Returns the following JSON structure on /// success: /// { /// "logged_in": true, /// "settings": {...}, /// "user": {...} /// } /// </returns> public JObject LoginUser(string name, string password) { return LoginUser(name, password, Salt); } private JObject LoginUser(string name, string password, string password_salt) { /* data = { 'name': name, 'pwd': hashlib.md5(self.password_salt + password).hexdigest() }*/ dynamic data = new JObject(); data.name = name; data.pwd = EncodePassword(password, password_salt); return Request("/users/login", data); } /// <summary> /// Updates an existing Quizduell user. The user will automatically be logged in. /// </summary> /// <param name="name">the current username</param> /// <param name="new_password">the new password to set</param> /// <param name="new_email">the new email to set</param> /// <returns> /// Returns the following JSON structure on success: /// { /// "logged_in": true, /// "settings": {...}, /// "user": {...} /// } /// </returns> public JObject UpdateUser(string name, string new_password, string new_email = "") { return UpdateUser(name, new_password, Salt, new_email); } private JObject UpdateUser(string name, string new_password, string password_salt, string new_email = "") { /* data = { 'name': name, 'email': email, 'pwd': hashlib.md5(self.password_salt + password).hexdigest() }*/ dynamic data = new JObject(); data.name = name; if (!String.IsNullOrEmpty(new_email)) { data.email = new_email; } data.pwd = EncodePassword(new_password, password_salt); return Request("/users/update_user", data); } /// <summary> /// Looks for a Quizduell user with the given name. /// </summary> /// <param name="name"></param> /// <returns> /// Returns the following /// JSON structure on success: /// { /// "u": { /// "avatar_code": "...", /// "name": "...", /// "user_id": "..." /// } /// } /// </returns> public JObject FindUser(string name) { /*data = { 'opponent_name': name }*/ dynamic data = new JObject(); data.opponent_name = name; return Request("/users/find_user", data); } /// <summary> /// Send a mail with a password restore link. /// </summary> /// <param name="email">the email where the password reset link will be sent.</param> /// <returns> /// Returns the following JSON structure on success: /// { /// "popup_mess": "Eine E-Mail ... wurde an deine E-Mail gesendet", /// "popup_title": "E-Mail gesendet" /// } /// </returns> public JObject ForgotPassword(string email) { /*data = { 'email': email }*/ dynamic data = new JObject(); data.email = email; return Request("/users/forgot_pwd", data); } /// <summary> /// Lists invited, active and finished games. /// </summary> /// <returns> /// Returns the following JSON structure on success: /// { /// "logged_in": true, /// "settings": {...}, /// "user": {...} /// } /// </returns> public JObject CurrentUserGames() { dynamic data = new JObject(); return Request("/users/current_user_games", data); } #endregion #region Friends /// <summary> /// Adds a Quizduell user as a friend. /// </summary> /// <param name="user_id">the user_id to add to your friendlist</param> /// <returns> /// Returns the following JSON structure on success: /// { /// "popup_mess": "Du bist jetzt mit ... befreundet", /// "popup_title": "Neuer Freund" /// } /// </returns> public JObject AddFriend(string user_id) { /* data = { 'friend_id': user_id }*/ dynamic data = new JObject(); data.friend_id = user_id; return Request("/users/add_friend", data); } /// <summary> /// Removes a Quizduell user from your friendlist. /// </summary> /// <param name="user_id">The user_id to remove from your friendlist</param> /// <returns> /// Returns the following JSON structure on success: /// { /// "removed_id": "..." /// } /// </returns> public JObject RemoveFriend(string user_id) { /*data = { 'friend_id': user_id }*/ dynamic data = new JObject(); data.friend_id = user_id; return Request("/users/remove_friend", data); } #endregion #region Avatar /// <summary> /// Change the displayed avatar. An avatar consists of individual mouth, /// hair, eyes, hats, etc. encoded in a numerical string, e.g. "0010999912" /// (A skin-colored avatar with a crown). /// </summary> /// <param name="avatar_code"></param> /// <returns> /// Returns the following JSON structure on success: /// { /// "t": true /// } /// </returns> public JObject UpdateAvatar(string avatar_code) { /* data = { 'avatar_code': avatar_code }*/ dynamic data = new JObject(); data.avatar_code = avatar_code; return Request("/users/update_avatar", data); } #endregion #region Message /// <summary> /// Send a message within a game. The message will be visible in all games against the same opponent. /// </summary> /// <param name="game_id"></param> /// <param name="message"></param> /// <returns> /// Returns the following JSON structure on success: /// { /// "m": [{ /// "created_at": "..., /// "from": ..., /// "id": "...", /// "text": "...", /// "to": ... /// }] /// } /// </returns> public JObject SendMessage(string game_id, string message) { /* data = { 'game_id': str(game_id), 'text': message }*/ dynamic data = new JObject(); data.game_id = game_id; data.text = message; return Request("/users/send_message", data); } #endregion #region Ranking /// <summary> /// Lists the top rated Quizduell players. /// </summary> /// <returns> /// Returns the following JSON structure on success: /// { /// "users": [{ /// "avatar_code": "...", /// "key": ..., /// "name": "...", /// "rating": ... /// }, ...] /// } /// /// </returns> public JObject TopListRating() { return Request("/users/top_list_rating"); } /// <summary> /// Lists the top rated Quizduell players. /// </summary> /// <returns> /// Returns the following JSON structure on success: /// { /// "users": [{ /// "avatar_code": "0010035604", /// "n_approved_questions": 192, /// "name": "Zwaanswijk" /// }, ...] /// } /// /// </returns> public JObject TopListWriters() { return Request("/users/top_list_writers"); } #endregion #region Blocking /// <summary> /// Puts a Quizduell user on the blocked list. /// </summary> /// <param name="user_id">The user_id to block</param> /// <returns> /// Returns the following JSON structure on success: /// { /// "blocked": [{ /// "avatar_code": "...", /// "name": "...", /// "user_id": "..." /// }, ...] /// } /// </returns> public JObject AddBlocked(string user_id) { /* data = { 'blocked_id': user_id }*/ dynamic data = new JObject(); data.blocked_id = user_id; return Request("/users/add_blocked", data); } /// <summary> /// Removes a Quizduell user from the blocked list. /// </summary> /// <param name="user_id">The user_id to unblock</param> /// <returns> /// Returns the following JSON structure on success: /// { /// "blocked": [...] /// } /// </returns> public JObject RemoveBlocked(string user_id) { /* data = { 'blocked_id': user_id }*/ dynamic data = new JObject(); data.blocked_id = user_id; return Request("/users/remove_blocked", data); } #endregion #region Device public JObject AddDeviceTokenIOS(string device_token) { return AddDeviceToken(device_token, "ios"); } private JObject AddDeviceToken(string device_token, string plattform) { /* POST https://qkgermany.feomedia.se/users/add_device_token_ios HTTP/1.1 * Host: qkgermany.feomedia.se * User-Agent: Germany/4.2.3 (iPhone; iOS 6.0; Scale/2.00) * clientdate: 2014-02-02 16:10:51 * Content-Type: application/x-www-form-urlencoded; charset=utf-8 * Authorization: UegIt9KGG248m3Qou7L1RsuN5yaL/CRFSvaA/0L3n6g= * * device_token=3abb175a%20b1620a03%200351a5bd%20ab179d88%20524db065%20b3f6bb7f%20d31ef834%20475c80b9 */ /* data = { 'device_token': device_token }*/ // TODO: Add Return Information and XML DOC Comment dynamic data = new JObject(); data.device_token = device_token; return Request("/users/add_device_token" + "_" + plattform, data); } #endregion #endregion #region /games/ #region Game /// <summary> /// Lists details of a game, including upcoming questions and their correct answers. /// </summary> /// <param name="game_id">the game_id for which you want to request the information</param> /// <returns> /// Returns the following JSON structure on success: /// { /// "game": { /// "cat_choices": [...], /// "elapsed_min": ..., /// "game_id": ..., /// "messages": [], /// "opponent": {...}, /// "opponent_answers": [...], /// "questions": [...], /// "state": ..., /// "your_answers": [...], /// "your_turn": false /// } /// } /// </returns> public JObject GetGame(string game_id) { return Request("/games/" + game_id); } /// <summary> /// Lists details of specified games, but without questions and answers. /// </summary> /// <param name="game_ids">The game_ids for which you want to request additional information</param> /// <returns> /// Returns the following JSON structure on success: /// { /// "games": [{ /// "cat_choices": [...], /// "elapsed_min": ..., /// "game_id": ..., /// "messages": [...], /// "opponent": {...}, /// "opponent_answers": [...], /// "state": ..., /// "your_answers": [...], /// "your_turn": ... /// }, ...] /// } /// </returns> public JObject GetGames(string[] game_ids) { /* data = { 'gids': json.dumps([int(i) for i in game_ids]) }*/ dynamic data = new JObject(); data.gids = String.Format("[{0}]", String.Join(",", game_ids)); return Request("/games/short_games", data); } /// <summary> /// Starts a game against a given opponent. /// </summary> /// <param name="user_id"></param> /// <returns> /// Returns the following JSON structure on success: /// { /// "game": { /// "cat_choices": [...], /// "elapsed_min": ..., /// "game_id": ..., /// "messages": [], /// "opponent": {...}, /// "opponent_answers": [...], /// "questions": [...], /// "state": 1, /// "your_answers": [...], /// "your_turn": false /// } /// } /// </returns> public JObject StartGame(string user_id) { /* data = { 'opponent_id': user_id }*/ dynamic data = new JObject(); data.opponent_id = user_id; return Request("/games/create_game", data); } /// <summary> /// Starts a game against a random opponent. /// </summary> /// <returns> /// Returns the following JSON structure on success: /// { /// "game": { /// "cat_choices": [...], /// "elapsed_min": ..., /// "game_id": ..., /// "messages": [], /// "opponent": {...}, /// "opponent_answers": [...], /// "questions": [...], /// "state": 1, /// "your_answers": [...], /// "your_turn": false /// } /// } /// </returns> public JObject StartRandomGame() { return Request("/games/start_random_game"); } /// <summary> /// Declines a Game Invitation /// </summary> /// <param name="game_id"></param> /// <returns> /// Returns the following JSON structure on success: /// { /// "t": true /// } /// </returns> public JObject DeclineGame(string game_id) { return AcceptGame(game_id, false); } public JObject AcceptGame(string game_id, bool accept = true) { /* data = { 'accept': '1', 'game_id': str(game_id) }*/ dynamic data = new JObject(); data.game_id = game_id; data.accept = accept ? 1 : 0; return Request("/games/accept", data); } /// <summary> /// Gives up a game. /// </summary> /// <param name="game_id"></param> /// <returns> /// Returns the following JSON structure on success: /// { /// "game": {...}, /// "popup": { /// "popup_mess": "Du hast gegen ... aufgegeben\n\nRating: -24", /// "popup_title": "Spiel beendet" /// } /// } /// </returns> public JObject GiveUp(string game_id) { // HACK: There is also a GET Interface, not sure which one is the newer one? /*GET https://qkunited.feomedia.se/games/6685949559832576/give_up HTTP/1.1 Host: qkunited.feomedia.se User-Agent: Quizduell/4.3 CFNetwork/548.1.4 Darwin/11.0.0 Authorization: IQM3lHeaOKwic/lubCELCX3Su++hAbqugiowG0Flq+w= clientdate: 2014-04-23 00:32:23 Cookie: auth=eyJfdXNlciI6WzYxMzQyMTE2MTg1Mzc0NzIsMSwiaE5iMDJ3dWNnMllBbmZWbHA5MFFNeCIsMTM5ODA4NzY2MywxMzk4MjEzMTEwLCJhYm90Il19|1398213131|939ebb1525cd094486be342762bfbc2f6de02c40 */ /* data = { 'game_id': str(game_id) }*/ dynamic data = new JObject(); data.game_id = game_id; return Request("/games/give_up", data); } /// <summary> /// Upload answers and the chosen category to an active game. The number of /// answers depends on the game state and is 3 for the first player in the /// first round and the last player in the last round, otherwise 6. /// Note: In the answers you must include all answers you gave in the previous rounds of the same game. /// </summary> /// <param name="game_id"></param> /// <param name="answers">3 or 6 values in {0,1,2,3} with 0 being correct, 8 is for round disrupted.</param> /// <param name="category_id">value in {0,1,2}</param> /// <returns> /// Returns the following JSON structure on success: /// { /// "game": { /// "your_answers": [...], /// "state": ..., /// "elapsed_min": ..., /// "your_turn": false, /// "game_id": ..., /// "cat_choices": [...], /// "opponent_answers": [...], /// "messages": [...], /// "opponent": {...} /// } /// } /// </returns> public JObject UploadRoundAnswers(string game_id, int[] answers, int category_id) { // HACK: The game is not submitting the category_id, instead it is submitting an array index, it's linearly using the categories, always 3 in a row per round. next round i +=3 so index can only be 0,1,2 /* NOTE: Example Request - Why is this using a different endpoint POST https://qkunited.feomedia.se/games/5732717270401024/upload_round_answers HTTP/1.1 data = { 'game_id': str(game_id), 'answers': str(answers), 'cat_choice': str(category_id) }*/ // Answers need to be in multiples of 3 if (answers.Length % 3 != 0) { throw new Exception("Error: answers need to be in multiples of 3 while the submitted count was: " + answers.Length); } dynamic data = new JObject(); // NOTE: Using alternative Endpoint --> which requires different sort order. if (Plattform == QuizDuellPlattform.ANDROID) { data.game_id = game_id.ToString(); } data.cat_choice = category_id.ToString(); data.answers = String.Format("[{0}]", String.Join(", ", answers)); // Android requires a space beetwen the values, IOS accepts this format too so making it general. //data.answers = String.Format("[{0}]", String.Join(",", answers)); /* Alternatives var postData = new Dictionary<string, object>() { {"game_id", game_id}, {"cat_choice", category_id} {"answers", answers}, }; // Alternative var x = data as IDictionary<string, string>; // ALternative var n = new NameValueCollection() { {"game_id", game_id}, {"answers", String.Format("[{0}]", String.Join(",", answers))}, {"cat_choice", category_id} };*/ if (Plattform == QuizDuellPlattform.ANDROID) { return Request("/games/upload_round_answers", data); } return Request(String.Format("/games/{0}/upload_round_answers", game_id), data); } #endregion #endregion #region /stats/ #region Stats /// <summary> /// Retrieves category statistics and ranking. /// </summary> /// <returns> /// Returns the following JSON structure on success: /// { /// "cat_stats": [...], /// "n_games_lost": ..., /// "n_games_played": ..., /// "n_games_tied": ..., /// "n_games_won": ..., /// "n_perfect_games": ..., /// "n_questions_answered": ..., /// "n_questions_correct": ..., /// "n_users": ..., /// "rank": ..., /// "rating": ... /// } /// </returns> public JObject CategoryStats() { return Request("/stats/my_stats"); } /// <summary> /// Retrieves game statistics per opponent. /// </summary> /// <returns> /// Returns the following JSON structure on success: /// { /// "game_stats": [{ /// "avatar_code": "...", /// "n_games_lost": 2, /// "n_games_tied": 2, /// "n_games_won": 0, /// "name": "...", /// "user_id": "..." /// }, ...], /// } /// </returns> public JObject GameStats() { return Request("/stats/my_game_stats"); } #endregion #endregion #region /web/ #region Category /// <summary> /// Lists all available categories. /// </summary> /// <returns> /// Returns the following JSON structure on success: /// { /// "cats": { /// "1": "Wunder der Technik", /// ... /// } /// } /// </returns> public JObject CategoryList() { return Request("/web/cats"); } /// <summary> /// Lists the number of Quizduell players. /// </summary> /// <returns></returns> public JObject CurrentPlayerNumber() { return Request("/web/num_players"); } #endregion #endregion #region Client Utility /// <summary> /// Returns the correct answer depended on a user supplied chance. /// </summary> /// <param name="correctAnswerChance">The chance to have a correct answer needs to be beetwen 0.0 [inklusive] and 1.0 [inklusive]</param> /// <returns></returns> public int GetAnswer(double correctAnswerChance = 0.8) { return (random.NextDouble() <= correctAnswerChance) ? 0 : random.Next(1, 4); } /// <summary> /// Normally we don't care what category we choose except in the last round where we need to chose the enemies category /// </summary> /// <param name="game"></param> /// <param name="requireAnswers">The required amount of answers for the current round</param> /// <returns></returns> public int GetCorrectCategoryID(JToken game, int requireAnswers) { // We don't care what category we choose except in the last round int category_id = random.Next(0, 3); if (requireAnswers == 3 && game["opponent_answers"].Count() != 0) { // it's the last Round and the opponent already picked a category List<int> category_choices = game["cat_choices"].Select(i => (int)i).ToList(); category_id = category_choices.Last(); } return category_id; } public int GetRequiredAnswerCount(JToken game) { // We start or its the last round so we only need 3 answers instead of 6 int answers_count = 6; var opponent_answers = game["opponent_answers"]; if (!opponent_answers.Any() || opponent_answers.Count() == 18) { answers_count = 3; } return answers_count; } #endregion } }
#define USE_TRACING using System; using System.Collections.Generic; using System.Globalization; using System.Xml; using Google.GData.AccessControl; using Google.GData.Client; using Google.GData.Extensions; namespace Google.GData.Documents { /// <summary> /// Name Table for string constants used in the Documents list api /// </summary> public class DocumentslistNametable : GDataParserNameTable { /// <summary>Document list namespace</summary> public const string NSDocumentslist = "http://schemas.google.com/docs/2007"; /// <summary>Document list prefix</summary> public const string Prefix = "docs"; /// <summary>Writers can invite element</summary> public const string WritersCanInvite = "writersCanInvite"; /// <summary>Changestamp element</summary> public const string Changestamp = "changestamp"; /// <summary>QuotaBytesTotal element</summary> public const string QuotaBytesTotal = "quotaBytesTotal"; /// <summary>QuotaBytesUsedInTrash element</summary> public const string QuotaBytesUsedInTrash = "quotaBytesUsedInTrash"; /// <summary>LargestChangestamp element</summary> public const string LargestChangestamp = "largestChangestamp"; /// <summary>RemainingChangestamps element</summary> public const string RemainingChangestamps = "remainingChangestamps"; /// <summary>ImportFormat element</summary> public const string ImportFormat = "importFormat"; /// <summary>ExportFormat element</summary> public const string ExportFormat = "exportFormat"; /// <summary>Source element</summary> public const string Source = "source"; /// <summary>Target element</summary> public const string Target = "target"; /// <summary>Reason element</summary> public const string Reason = "reason"; /// <summary>Feature element</summary> public const string Feature = "feature"; /// <summary>FeatureName element</summary> public const string FeatureName = "featureName"; /// <summary>FeatureRate element</summary> public const string FeatureRate = "featureRate"; /// <summary>MaxUploadSize element</summary> public const string MaxUploadSize = "maxUploadSize"; /// <summary>Kind element</summary> public const string Kind = "kind"; /// <summary>AdditionalRoleInfo element</summary> public const string AdditionalRoleInfo = "additionalRoleInfo"; /// <summary>AdditionalRoleSet element</summary> public const string AdditionalRoleSet = "additionalRoleSet"; /// <summary>AdditionalRole element</summary> public const string AdditionalRole = "additionalRole"; /// <summary>PrimaryRole element</summary> public const string PrimaryRole = "primaryRole"; /// <summary>ArchiveResourceId element</summary> public const string ArchiveResourceId = "archiveResourceId"; /// <summary>ArchiveConversion element</summary> public const string ArchiveConversion = "archiveConversion"; /// <summary>ArchiveNotify element</summary> public const string ArchiveNotify = "archiveNotify"; /// <summary>ArchiveStatus element</summary> public const string ArchiveStatus = "archiveStatus"; /// <summary>ArchiveComplete element</summary> public const string ArchiveComplete = "archiveComplete"; /// <summary>ArchiveTotal element</summary> public const string ArchiveTotal = "archiveTotal"; /// <summary>ArchiveTotalComplete element</summary> public const string ArchiveTotalComplete = "archiveTotalComplete"; /// <summary>ArchiveTotalFailure element</summary> public const string ArchiveTotalFailure = "archiveTotalFailure"; /// <summary>ArchiveFailure element</summary> public const string ArchiveFailure = "archiveFailure"; /// <summary>ArchiveNotifyStatus element</summary> public const string ArchiveNotifyStatus = "archiveNotifyStatus"; /// <summary>Publish element</summary> public const string Publish = "publish"; /// <summary>PublishAuto element</summary> public const string PublishAuto = "publishAuto"; /// <summary>PublishOutsideDomain element</summary> public const string PublishOutsideDomain = "publishOutsideDomain"; /// <summary>Description element</summary> public const string Description = "description"; } /// <summary> /// Entry API customization class for defining entries in an Event feed. /// </summary> public class DocumentEntry : AbstractEntry { private static readonly string PRESENTATION_KIND = DocumentsService.DocumentsNamespace + "#presentation"; private static readonly string DOCUMENT_KIND = DocumentsService.DocumentsNamespace + "#document"; private static readonly string SPREADSHEET_KIND = DocumentsService.DocumentsNamespace + "#spreadsheet"; private static readonly string DRAWING_KIND = DocumentsService.DocumentsNamespace + "#drawing"; private static readonly string PDF_KIND = DocumentsService.DocumentsNamespace + "#pdf"; private static readonly string FOLDER_KIND = DocumentsService.DocumentsNamespace + "#folder"; private static readonly string FORM_KIND = DocumentsService.DocumentsNamespace + "#form"; private static readonly string PARENT_FOLDER_REL = DocumentsService.DocumentsNamespace + "#parent"; private static readonly string STARRED_KIND = BaseNameTable.gLabels + "#starred"; private static readonly string TRASHED_KIND = BaseNameTable.gLabels + "#trashed"; private static readonly string HIDDEN_KIND = BaseNameTable.gLabels + "#hidden"; private static readonly string VIEWED_KIND = BaseNameTable.gLabels + "#viewed"; private static readonly string MINE_KIND = BaseNameTable.gLabels + "#mine"; private static readonly string PRIVATE_KIND = BaseNameTable.gLabels + "#private"; private static readonly string SHARED_KIND = BaseNameTable.gLabels + "#shared-with-domain"; /// <summary> /// a predefined atom category for Documents /// </summary> public static AtomCategory DOCUMENT_CATEGORY = new AtomCategory(DOCUMENT_KIND, new AtomUri(BaseNameTable.gKind), "document"); /// <summary> /// a predefined atom category for Spreadsheets /// </summary> public static AtomCategory SPREADSHEET_CATEGORY = new AtomCategory(SPREADSHEET_KIND, new AtomUri(BaseNameTable.gKind), "spreadsheet"); /// <summary> /// a predefined atom category for PDF /// </summary> public static AtomCategory PDF_CATEGORY = new AtomCategory(PDF_KIND, new AtomUri(BaseNameTable.gKind), "pdf"); /// <summary> /// a predefined atom category for Presentations /// </summary> public static AtomCategory PRESENTATION_CATEGORY = new AtomCategory(PRESENTATION_KIND, new AtomUri(BaseNameTable.gKind), "presentation"); /// <summary> /// a predefined atom category for Drawings /// </summary> public static AtomCategory DRAWING_CATEGORY = new AtomCategory(DRAWING_KIND, new AtomUri(BaseNameTable.gKind), "drawing"); /// <summary> /// a predefined atom category for folders /// </summary> public static AtomCategory FOLDER_CATEGORY = new AtomCategory(FOLDER_KIND, new AtomUri(BaseNameTable.gKind), "folder"); /// <summary> /// a predefined atom category for forms /// </summary> public static AtomCategory FORM_CATEGORY = new AtomCategory(FORM_KIND, new AtomUri(BaseNameTable.gKind), "form"); /// <summary> /// a predefined atom category for starred documents /// </summary> public static AtomCategory STARRED_CATEGORY = new AtomCategory(STARRED_KIND, new AtomUri(BaseNameTable.gLabels), "starred"); /// <summary> /// a predefined atom category for trashed documents /// </summary> public static AtomCategory TRASHED_CATEGORY = new AtomCategory(TRASHED_KIND, new AtomUri(BaseNameTable.gLabels), "trashed"); /// <summary> /// a predefined atom category for hidden documents /// </summary> public static AtomCategory HIDDEN_CATEGORY = new AtomCategory(HIDDEN_KIND, new AtomUri(BaseNameTable.gLabels), "hidden"); /// <summary> /// a predefined atom category for VIEWED documents /// </summary> public static AtomCategory VIEWED_CATEGORY = new AtomCategory(VIEWED_KIND, new AtomUri(BaseNameTable.gLabels), "viewed"); /// <summary> /// a predefined atom category for owned by user documents /// </summary> public static AtomCategory MINE_CATEGORY = new AtomCategory(MINE_KIND, new AtomUri(BaseNameTable.gLabels), "mine"); /// <summary> /// a predefined atom category for private documents /// </summary> public static AtomCategory PRIVATE_CATEGORY = new AtomCategory(PRIVATE_KIND, new AtomUri(BaseNameTable.gLabels), "private"); /// <summary> /// a predefined atom category for shared documents /// </summary> public static AtomCategory SHARED_CATEGORY = new AtomCategory(SHARED_KIND, new AtomUri(BaseNameTable.gLabels), "shared-with-domain"); /// <summary> /// Constructs a new EventEntry instance with the appropriate category /// to indicate that it is an event. /// </summary> public DocumentEntry() { ProtocolMajor = VersionDefaults.VersionThree; Tracing.TraceMsg("Created DocumentEntry"); AddExtension(new FeedLink()); AddExtension(new ResourceId()); AddExtension(new WritersCanInvite()); AddExtension(new LastViewed()); AddExtension(new LastModifiedBy()); AddExtension(new QuotaBytesUsed()); AddExtension(new Description()); } /// <summary> /// Reflects if this entry is a word processor document /// </summary> public bool IsDocument { get { return Categories.Contains(DOCUMENT_CATEGORY); } set { ToggleCategory(DOCUMENT_CATEGORY, value); } } /// <summary> /// Reflects if this entry is a spreadsheet document /// </summary> public bool IsSpreadsheet { get { return Categories.Contains(SPREADSHEET_CATEGORY); } set { ToggleCategory(SPREADSHEET_CATEGORY, value); } } /// <summary> /// Reflects if this entry is a presentation document /// </summary> public bool IsPresentation { get { return Categories.Contains(PRESENTATION_CATEGORY); } set { ToggleCategory(PRESENTATION_CATEGORY, value); } } /// <summary> /// Reflects if this entry is a drawing document /// </summary> public bool IsDrawing { get { return Categories.Contains(DRAWING_CATEGORY); } set { ToggleCategory(DRAWING_CATEGORY, value); } } /// <summary> /// Reflects if this entry is a form /// </summary> public bool IsForm { get { return Categories.Contains(FORM_CATEGORY); } set { ToggleCategory(FORM_CATEGORY, value); } } /// <summary> /// Reflects if this entry is a PDF document /// </summary> public bool IsPDF { get { return Categories.Contains(PDF_CATEGORY); } set { ToggleCategory(PDF_CATEGORY, value); } } /// <summary> /// Reflects if this entry is starred /// </summary> public bool IsStarred { get { return Categories.Contains(STARRED_CATEGORY); } set { ToggleCategory(STARRED_CATEGORY, value); } } /// <summary> /// returns true if this is a folder /// </summary> public bool IsFolder { get { return Categories.Contains(FOLDER_CATEGORY); } set { ToggleCategory(FOLDER_CATEGORY, value); } } /// <summary> /// returns the string that should represent the Uri to the access control list /// </summary> /// <returns>the value of the hret attribute for the acl feedlink, or null if not found</returns> public string AccessControlList { get { List<FeedLink> list = FindExtensions<FeedLink>(GDataParserNameTable.XmlFeedLinkElement, BaseNameTable.gNamespace); foreach (FeedLink fl in list) { if (fl.Rel == AclNameTable.LINK_REL_ACCESS_CONTROL_LIST) { return fl.Href; } } return null; } } /// <summary> /// returns the string that should represent the Uri to the revision document /// </summary> /// <returns>the value of the hret attribute for the revisons feedlink, or null if not found</returns> public string RevisionDocument { get { List<FeedLink> list = FindExtensions<FeedLink>(GDataParserNameTable.XmlFeedLinkElement, BaseNameTable.gNamespace); foreach (FeedLink fl in list) { if (fl.Rel == DocumentsService.Revisions) { return fl.Href; } } return null; } } /// <summary> /// returns the href value of the parent link releationship /// </summary> /// <returns></returns> public List<AtomLink> ParentFolders { get { List<AtomLink> links = Links.FindServiceList(PARENT_FOLDER_REL, AtomLink.ATOM_TYPE); return links; } } /// <summary> /// Documents resource Identifier. /// </summary> /// <returns></returns> public string ResourceId { get { return GetStringValue<ResourceId>(GDataParserNameTable.XmlResourceIdElement, GDataParserNameTable.gNamespace); } } /// <summary> /// Identifies if a collaborator can modify the ACLs of the document /// </summary> /// <returns></returns> public bool WritersCanInvite { get { string v = GetStringValue<WritersCanInvite>(DocumentslistNametable.WritersCanInvite, DocumentslistNametable.NSDocumentslist); // v can either be 1/0 or true/false bool ret = Utilities.XSDTrue == v; if (!ret) { ret = "0" == v; } return ret; } set { string v = value ? Utilities.XSDTrue : Utilities.XSDFalse; SetStringValue<WritersCanInvite>(v, DocumentslistNametable.WritersCanInvite, DocumentslistNametable.NSDocumentslist); } } /// <summary> /// Returns the last viewed timestamp /// </summary> /// <returns></returns> public DateTime LastViewed { get { LastViewed e = FindExtension(GDataParserNameTable.XmlLastViewedElement, GDataParserNameTable.gNamespace) as LastViewed; if (e != null && e.Value != null) { return DateTime.Parse(e.Value, CultureInfo.InvariantCulture); } return DateTime.MinValue; } } /// <summary> /// returns the last modifiedBy Element /// </summary> /// <returns></returns> public LastModifiedBy LastModified { get { return FindExtension(GDataParserNameTable.XmlLastModifiedByElement, GDataParserNameTable.gNamespace) as LastModifiedBy; } } /// <summary> /// returns the last quotabytesused Element /// </summary> /// <returns></returns> public QuotaBytesUsed QuotaUsed { get { return FindExtension(GDataParserNameTable.XmlQuotaBytesUsedElement, GDataParserNameTable.gNamespace) as QuotaBytesUsed; } } /// <summary> /// Identifies the description of the resource /// </summary> /// <returns></returns> public string Description { get { return GetStringValue<Description>(DocumentslistNametable.Description, DocumentslistNametable.NSDocumentslist); } set { SetStringValue<Description>(value, DocumentslistNametable.Description, DocumentslistNametable.NSDocumentslist); } } /// <summary> /// add the documentslist NS /// </summary> /// <param name="writer">The XmlWrite, where we want to add default namespaces to</param> protected override void AddOtherNamespaces(XmlWriter writer) { base.AddOtherNamespaces(writer); if (writer == null) { throw new ArgumentNullException("writer"); } string strPrefix = writer.LookupPrefix(DocumentslistNametable.NSDocumentslist); if (strPrefix == null) { writer.WriteAttributeString("xmlns", DocumentslistNametable.Prefix, null, DocumentslistNametable.NSDocumentslist); } } /// <summary> /// Checks if this is a namespace declaration that we already added /// </summary> /// <param name="node">XmlNode to check</param> /// <returns>True if this node should be skipped</returns> protected override bool SkipNode(XmlNode node) { if (base.SkipNode(node)) { return true; } return (node.NodeType == XmlNodeType.Attribute && node.Name.StartsWith("xmlns") && string.Compare(node.Value, DocumentslistNametable.NSDocumentslist) == 0); } } /// <summary> /// Determines if a collaborator can modify a documents ACL /// </summary> public class WritersCanInvite : SimpleAttribute { /// <summary> /// default constructor for docs:writersCanInvite /// </summary> public WritersCanInvite() : base(DocumentslistNametable.WritersCanInvite, DocumentslistNametable.Prefix, DocumentslistNametable.NSDocumentslist) { } } /// <summary> /// Identifies the description of the resource /// </summary> public class Description : SimpleElement { /// <summary> /// default constructor for docs:description /// </summary> public Description() : base(DocumentslistNametable.Description, DocumentslistNametable.Prefix, DocumentslistNametable.NSDocumentslist) { } } }
using System; using System.IO; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using WeifenLuo.WinFormsUI.Docking; using ConfigToggle.Resources; using PluginCore.Localization; using PluginCore.Utilities; using PluginCore.Managers; using PluginCore.Helpers; using ProjectManager.Projects.AS3; using PluginCore; namespace ConfigToggle { public class PluginMain : IPlugin { private String pluginName = "ConfigToggle"; private String pluginGuid = "64B999EB-EC9C-4263-AF25-E2E6DF733107"; private String pluginHelp = "www.flashdevelop.org/community/"; private String pluginDesc = "Allows toggling compiler constants"; private String pluginAuth = "Hubert Rutkowski"; private String settingFilename; private Settings settingObject; private DockContent pluginPanel; private PluginUI pluginUI; private Image pluginImage; #region Required Properties /// <summary> /// Api level of the plugin /// </summary> public Int32 Api { get { return 1; } } /// <summary> /// Name of the plugin /// </summary> public String Name { get { return this.pluginName; } } /// <summary> /// GUID of the plugin /// </summary> public String Guid { get { return this.pluginGuid; } } /// <summary> /// Author of the plugin /// </summary> public String Author { get { return this.pluginAuth; } } /// <summary> /// Description of the plugin /// </summary> public String Description { get { return this.pluginDesc; } } /// <summary> /// Web address for help /// </summary> public String Help { get { return this.pluginHelp; } } /// <summary> /// Object that contains the settings /// </summary> [Browsable(false)] public Object Settings { get { return this.settingObject; } } #endregion #region Required Methods /// <summary> /// Initializes the plugin /// </summary> public void Initialize() { this.InitBasics(); this.LoadSettings(); this.AddEventHandlers(); this.InitLocalization(); this.CreatePluginPanel(); this.CreateMenuItem(); } /// <summary> /// Disposes the plugin /// </summary> public void Dispose() { this.SaveSettings(); } /// <summary> /// Handles the incoming events /// </summary> public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority prority) { switch (e.Type) { // Catches FileSwitch event and displays the filename it in the PluginUI. /*case EventType.FileSwitch: string fileName = PluginBase.MainForm.CurrentDocument.FileName; pluginUI.Output.Text += fileName + "\r\n"; TraceManager.Add("Switched to " + fileName); // tracing to output panel break;*/ // Catches Project change event and display the active project path case EventType.Command: string cmd = (e as DataEvent).Action; if (cmd == "ProjectManager.Project") { IProject project = PluginBase.CurrentProject; if (project == null ) { //pluginUI.Output.Text += "Project closed.\r\n"; } else if ((project as AS3Project) == null) { this.pluginPanel.Hide(); } else { //pluginUI.Output.Text += "Project open: " + project.ProjectPath + "\r\n"; pluginUI.RefreshUI(); } } break; } } #endregion #region Custom Methods /// <summary> /// Initializes important variables /// </summary> public void InitBasics() { String dataPath = Path.Combine(PathHelper.DataDir, pluginName); if (!Directory.Exists(dataPath)) Directory.CreateDirectory(dataPath); this.settingFilename = Path.Combine(dataPath, "Settings.fdb"); this.pluginImage = PluginBase.MainForm.FindImage("105"); } /// <summary> /// Adds the required event handlers /// </summary> public void AddEventHandlers() { // Set events you want to listen (combine as flags) EventManager.AddEventHandler(this, /*EventType.FileSwitch |*/ EventType.Command); } /// <summary> /// Initializes the localization of the plugin /// </summary> public void InitLocalization() { LocaleVersion locale = PluginBase.MainForm.Settings.LocaleVersion; switch (locale) { /* case LocaleVersion.fi_FI : // We have Finnish available... or not. :) LocaleHelper.Initialize(LocaleVersion.fi_FI); break; */ default : // Plugins should default to English... LocaleHelper.Initialize(LocaleVersion.en_US); break; } this.pluginDesc = LocaleHelper.GetString("Info.Description"); } /// <summary> /// Creates a menu item for the plugin and adds a ignored key /// </summary> public void CreateMenuItem() { ToolStripMenuItem viewMenu = (ToolStripMenuItem)PluginBase.MainForm.FindMenuItem("ViewMenu"); viewMenu.DropDownItems.Add(new ToolStripMenuItem("CONFIG::toggle plugin", this.pluginImage, new EventHandler(this.OpenPanel), this.settingObject.SampleShortcut)); PluginBase.MainForm.IgnoredKeys.Add(this.settingObject.SampleShortcut); } /// <summary> /// Creates a plugin panel for the plugin /// </summary> public void CreatePluginPanel() { this.pluginUI = new PluginUI(this); this.pluginUI.Text = LocaleHelper.GetString("Title.PluginPanel"); this.pluginPanel = PluginBase.MainForm.CreateDockablePanel(this.pluginUI, this.pluginGuid, this.pluginImage, DockState.DockRight); } /// <summary> /// Loads the plugin settings /// </summary> public void LoadSettings() { this.settingObject = new Settings(); if (!File.Exists(this.settingFilename)) this.SaveSettings(); else { Object obj = ObjectSerializer.Deserialize(this.settingFilename, this.settingObject); this.settingObject = (Settings)obj; } } /// <summary> /// Saves the plugin settings /// </summary> public void SaveSettings() { ObjectSerializer.Serialize(this.settingFilename, this.settingObject); } /// <summary> /// Opens the plugin panel if closed /// </summary> public void OpenPanel(Object sender, System.EventArgs e) { this.pluginPanel.Show(); } #endregion } }
using Lucene.Net.Documents; using Lucene.Net.Support; using System.Text; namespace Lucene.Net.Document { using NUnit.Framework; using System.IO; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using Fields = Lucene.Net.Index.Fields; using IndexableField = Lucene.Net.Index.IndexableField; using IndexReader = Lucene.Net.Index.IndexReader; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * 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 MockTokenizer = Lucene.Net.Analysis.MockTokenizer; using PhraseQuery = Lucene.Net.Search.PhraseQuery; using Query = Lucene.Net.Search.Query; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using Term = Lucene.Net.Index.Term; using TermQuery = Lucene.Net.Search.TermQuery; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; /// <summary> /// Tests <seealso cref="Document"/> class. /// </summary> [TestFixture] public class TestDocument : LuceneTestCase { internal string BinaryVal = "this text will be stored as a byte array in the index"; internal string BinaryVal2 = "this text will be also stored as a byte array in the index"; [Test] public virtual void TestBinaryField() { Documents.Document doc = new Documents.Document(); FieldType ft = new FieldType(); ft.Stored = true; IndexableField stringFld = new Field("string", BinaryVal, ft); IndexableField binaryFld = new StoredField("binary", BinaryVal.GetBytes(Encoding.UTF8)); IndexableField binaryFld2 = new StoredField("binary", BinaryVal2.GetBytes(Encoding.UTF8)); doc.Add(stringFld); doc.Add(binaryFld); Assert.AreEqual(2, doc.Fields.Count); Assert.IsTrue(binaryFld.BinaryValue() != null); Assert.IsTrue(binaryFld.FieldType().Stored); Assert.IsFalse(binaryFld.FieldType().Indexed); string binaryTest = doc.GetBinaryValue("binary").Utf8ToString(); Assert.IsTrue(binaryTest.Equals(BinaryVal)); string stringTest = doc.Get("string"); Assert.IsTrue(binaryTest.Equals(stringTest)); doc.Add(binaryFld2); Assert.AreEqual(3, doc.Fields.Count); BytesRef[] binaryTests = doc.GetBinaryValues("binary"); Assert.AreEqual(2, binaryTests.Length); binaryTest = binaryTests[0].Utf8ToString(); string binaryTest2 = binaryTests[1].Utf8ToString(); Assert.IsFalse(binaryTest.Equals(binaryTest2)); Assert.IsTrue(binaryTest.Equals(BinaryVal)); Assert.IsTrue(binaryTest2.Equals(BinaryVal2)); doc.RemoveField("string"); Assert.AreEqual(2, doc.Fields.Count); doc.RemoveFields("binary"); Assert.AreEqual(0, doc.Fields.Count); } /// <summary> /// Tests <seealso cref="Document#removeField(String)"/> method for a brand new Document /// that has not been indexed yet. /// </summary> /// <exception cref="Exception"> on error </exception> [Test] public virtual void TestRemoveForNewDocument() { Documents.Document doc = MakeDocumentWithFields(); Assert.AreEqual(10, doc.Fields.Count); doc.RemoveFields("keyword"); Assert.AreEqual(8, doc.Fields.Count); doc.RemoveFields("doesnotexists"); // removing non-existing fields is // siltenlty ignored doc.RemoveFields("keyword"); // removing a field more than once Assert.AreEqual(8, doc.Fields.Count); doc.RemoveFields("text"); Assert.AreEqual(6, doc.Fields.Count); doc.RemoveFields("text"); Assert.AreEqual(6, doc.Fields.Count); doc.RemoveFields("text"); Assert.AreEqual(6, doc.Fields.Count); doc.RemoveFields("doesnotexists"); // removing non-existing fields is // siltenlty ignored Assert.AreEqual(6, doc.Fields.Count); doc.RemoveFields("unindexed"); Assert.AreEqual(4, doc.Fields.Count); doc.RemoveFields("unstored"); Assert.AreEqual(2, doc.Fields.Count); doc.RemoveFields("doesnotexists"); // removing non-existing fields is // siltenlty ignored Assert.AreEqual(2, doc.Fields.Count); doc.RemoveFields("indexed_not_tokenized"); Assert.AreEqual(0, doc.Fields.Count); } [Test] public virtual void TestConstructorExceptions() { FieldType ft = new FieldType(); ft.Stored = true; new Field("name", "value", ft); // okay new StringField("name", "value", Field.Store.NO); // okay try { new Field("name", "value", new FieldType()); Assert.Fail(); } catch (System.ArgumentException e) { // expected exception } new Field("name", "value", ft); // okay try { FieldType ft2 = new FieldType(); ft2.Stored = true; ft2.StoreTermVectors = true; new Field("name", "value", ft2); Assert.Fail(); } catch (System.ArgumentException e) { // expected exception } } /// <summary> /// Tests <seealso cref="Document#getValues(String)"/> method for a brand new Document /// that has not been indexed yet. /// </summary> /// <exception cref="Exception"> on error </exception> [Test] public virtual void TestGetValuesForNewDocument() { DoAssert(MakeDocumentWithFields(), false); } /// <summary> /// Tests <seealso cref="Document#getValues(String)"/> method for a Document retrieved /// from an index. /// </summary> /// <exception cref="Exception"> on error </exception> [Test] public virtual void TestGetValuesForIndexedDocument() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir); writer.AddDocument(MakeDocumentWithFields()); IndexReader reader = writer.Reader; IndexSearcher searcher = NewSearcher(reader); // search for something that does exists Query query = new TermQuery(new Term("keyword", "test1")); // ensure that queries return expected results without DateFilter first ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); DoAssert(searcher.Doc(hits[0].Doc), true); writer.Dispose(); reader.Dispose(); dir.Dispose(); } [Test] public virtual void TestGetValues() { Documents.Document doc = MakeDocumentWithFields(); Assert.AreEqual(new string[] { "test1", "test2" }, doc.GetValues("keyword")); Assert.AreEqual(new string[] { "test1", "test2" }, doc.GetValues("text")); Assert.AreEqual(new string[] { "test1", "test2" }, doc.GetValues("unindexed")); Assert.AreEqual(new string[0], doc.GetValues("nope")); } [Test] public virtual void TestPositionIncrementMultiFields() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir); writer.AddDocument(MakeDocumentWithFields()); IndexReader reader = writer.Reader; IndexSearcher searcher = NewSearcher(reader); PhraseQuery query = new PhraseQuery(); query.Add(new Term("indexed_not_tokenized", "test1")); query.Add(new Term("indexed_not_tokenized", "test2")); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); DoAssert(searcher.Doc(hits[0].Doc), true); writer.Dispose(); reader.Dispose(); dir.Dispose(); } private Documents.Document MakeDocumentWithFields() { Documents.Document doc = new Documents.Document(); FieldType stored = new FieldType(); stored.Stored = true; FieldType indexedNotTokenized = new FieldType(); indexedNotTokenized.Indexed = true; indexedNotTokenized.Tokenized = false; doc.Add(new StringField("keyword", "test1", Field.Store.YES)); doc.Add(new StringField("keyword", "test2", Field.Store.YES)); doc.Add(new TextField("text", "test1", Field.Store.YES)); doc.Add(new TextField("text", "test2", Field.Store.YES)); doc.Add(new Field("unindexed", "test1", stored)); doc.Add(new Field("unindexed", "test2", stored)); doc.Add(new TextField("unstored", "test1", Field.Store.NO)); doc.Add(new TextField("unstored", "test2", Field.Store.NO)); doc.Add(new Field("indexed_not_tokenized", "test1", indexedNotTokenized)); doc.Add(new Field("indexed_not_tokenized", "test2", indexedNotTokenized)); return doc; } private void DoAssert(Documents.Document doc, bool fromIndex) { IndexableField[] keywordFieldValues = doc.GetFields("keyword"); IndexableField[] textFieldValues = doc.GetFields("text"); IndexableField[] unindexedFieldValues = doc.GetFields("unindexed"); IndexableField[] unstoredFieldValues = doc.GetFields("unstored"); Assert.IsTrue(keywordFieldValues.Length == 2); Assert.IsTrue(textFieldValues.Length == 2); Assert.IsTrue(unindexedFieldValues.Length == 2); // this test cannot work for documents retrieved from the index // since unstored fields will obviously not be returned if (!fromIndex) { Assert.IsTrue(unstoredFieldValues.Length == 2); } Assert.IsTrue(keywordFieldValues[0].StringValue.Equals("test1")); Assert.IsTrue(keywordFieldValues[1].StringValue.Equals("test2")); Assert.IsTrue(textFieldValues[0].StringValue.Equals("test1")); Assert.IsTrue(textFieldValues[1].StringValue.Equals("test2")); Assert.IsTrue(unindexedFieldValues[0].StringValue.Equals("test1")); Assert.IsTrue(unindexedFieldValues[1].StringValue.Equals("test2")); // this test cannot work for documents retrieved from the index // since unstored fields will obviously not be returned if (!fromIndex) { Assert.IsTrue(unstoredFieldValues[0].StringValue.Equals("test1")); Assert.IsTrue(unstoredFieldValues[1].StringValue.Equals("test2")); } } [Test] public virtual void TestFieldSetValue() { Field field = new StringField("id", "id1", Field.Store.YES); Documents.Document doc = new Documents.Document(); doc.Add(field); doc.Add(new StringField("keyword", "test", Field.Store.YES)); Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir); writer.AddDocument(doc); field.StringValue = "id2"; writer.AddDocument(doc); field.StringValue = "id3"; writer.AddDocument(doc); IndexReader reader = writer.Reader; IndexSearcher searcher = NewSearcher(reader); Query query = new TermQuery(new Term("keyword", "test")); // ensure that queries return expected results without DateFilter first ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); int result = 0; for (int i = 0; i < 3; i++) { Documents.Document doc2 = searcher.Doc(hits[i].Doc); Field f = (Field)doc2.GetField("id"); if (f.StringValue.Equals("id1")) { result |= 1; } else if (f.StringValue.Equals("id2")) { result |= 2; } else if (f.StringValue.Equals("id3")) { result |= 4; } else { Assert.Fail("unexpected id field"); } } writer.Dispose(); reader.Dispose(); dir.Dispose(); Assert.AreEqual(7, result, "did not see all IDs"); } // LUCENE-3616 [Test] public virtual void TestInvalidFields() { try { new Field("foo", new MockTokenizer(new StreamReader("")), StringField.TYPE_STORED); Assert.Fail("did not hit expected exc"); } catch (System.ArgumentException iae) { // expected } } // LUCENE-3682 [Test] public virtual void TestTransitionAPI() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), dir); Documents.Document doc = new Documents.Document(); doc.Add(new Field("stored", "abc", Field.Store.YES, Field.Index.NO)); doc.Add(new Field("stored_indexed", "abc xyz", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("stored_tokenized", "abc xyz", Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("indexed", "abc xyz", Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.Add(new Field("tokenized", "abc xyz", Field.Store.NO, Field.Index.ANALYZED)); doc.Add(new Field("tokenized_reader", new StringReader("abc xyz"))); doc.Add(new Field("tokenized_tokenstream", w.w.Analyzer.TokenStream("tokenized_tokenstream", new StringReader("abc xyz")))); doc.Add(new Field("binary", new byte[10])); doc.Add(new Field("tv", "abc xyz", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES)); doc.Add(new Field("tv_pos", "abc xyz", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS)); doc.Add(new Field("tv_off", "abc xyz", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS)); doc.Add(new Field("tv_pos_off", "abc xyz", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); w.AddDocument(doc); IndexReader r = w.Reader; w.Dispose(); doc = r.Document(0); // 4 stored fields Assert.AreEqual(4, doc.Fields.Count); Assert.AreEqual("abc", doc.Get("stored")); Assert.AreEqual("abc xyz", doc.Get("stored_indexed")); Assert.AreEqual("abc xyz", doc.Get("stored_tokenized")); BytesRef br = doc.GetBinaryValue("binary"); Assert.IsNotNull(br); Assert.AreEqual(10, br.Length); IndexSearcher s = new IndexSearcher(r); Assert.AreEqual(1, s.Search(new TermQuery(new Term("stored_indexed", "abc xyz")), 1).TotalHits); Assert.AreEqual(1, s.Search(new TermQuery(new Term("stored_tokenized", "abc")), 1).TotalHits); Assert.AreEqual(1, s.Search(new TermQuery(new Term("stored_tokenized", "xyz")), 1).TotalHits); Assert.AreEqual(1, s.Search(new TermQuery(new Term("indexed", "abc xyz")), 1).TotalHits); Assert.AreEqual(1, s.Search(new TermQuery(new Term("tokenized", "abc")), 1).TotalHits); Assert.AreEqual(1, s.Search(new TermQuery(new Term("tokenized", "xyz")), 1).TotalHits); Assert.AreEqual(1, s.Search(new TermQuery(new Term("tokenized_reader", "abc")), 1).TotalHits); Assert.AreEqual(1, s.Search(new TermQuery(new Term("tokenized_reader", "xyz")), 1).TotalHits); Assert.AreEqual(1, s.Search(new TermQuery(new Term("tokenized_tokenstream", "abc")), 1).TotalHits); Assert.AreEqual(1, s.Search(new TermQuery(new Term("tokenized_tokenstream", "xyz")), 1).TotalHits); foreach (string field in new string[] { "tv", "tv_pos", "tv_off", "tv_pos_off" }) { Fields tvFields = r.GetTermVectors(0); Terms tvs = tvFields.Terms(field); Assert.IsNotNull(tvs); Assert.AreEqual(2, tvs.Size()); TermsEnum tvsEnum = tvs.Iterator(null); Assert.AreEqual(new BytesRef("abc"), tvsEnum.Next()); DocsAndPositionsEnum dpEnum = tvsEnum.DocsAndPositions(null, null); if (field.Equals("tv")) { Assert.IsNull(dpEnum); } else { Assert.IsNotNull(dpEnum); } Assert.AreEqual(new BytesRef("xyz"), tvsEnum.Next()); Assert.IsNull(tvsEnum.Next()); } r.Dispose(); dir.Dispose(); } [Test] public virtual void TestNumericFieldAsString() { Documents.Document doc = new Documents.Document(); doc.Add(new IntField("int", 5, Field.Store.YES)); Assert.AreEqual("5", doc.Get("int")); Assert.IsNull(doc.Get("somethingElse")); doc.Add(new IntField("int", 4, Field.Store.YES)); Assert.AreEqual(new string[] { "5", "4" }, doc.GetValues("int")); Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter(Random(), dir); iw.AddDocument(doc); DirectoryReader ir = iw.Reader; Documents.Document sdoc = ir.Document(0); Assert.AreEqual("5", sdoc.Get("int")); Assert.IsNull(sdoc.Get("somethingElse")); Assert.AreEqual(new string[] { "5", "4" }, sdoc.GetValues("int")); ir.Dispose(); iw.Dispose(); dir.Dispose(); } } }
// 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.Threading; using Xunit; namespace System.Text.RegularExpressions.Tests { public class RegexConstructorTests { public static IEnumerable<object[]> Ctor_TestData() { yield return new object[] { "foo", RegexOptions.None, Timeout.InfiniteTimeSpan }; yield return new object[] { "foo", RegexOptions.RightToLeft, Timeout.InfiniteTimeSpan }; yield return new object[] { "foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant, Timeout.InfiniteTimeSpan }; yield return new object[] { "foo", RegexOptions.None, new TimeSpan(1) }; yield return new object[] { "foo", RegexOptions.None, TimeSpan.FromMilliseconds(int.MaxValue - 1) }; } [Theory] [MemberData(nameof(Ctor_TestData))] public static void Ctor(string pattern, RegexOptions options, TimeSpan matchTimeout) { if (matchTimeout == Timeout.InfiniteTimeSpan) { if (options == RegexOptions.None) { Regex regex1 = new Regex(pattern); Assert.Equal(pattern, regex1.ToString()); Assert.Equal(options, regex1.Options); Assert.False(regex1.RightToLeft); Assert.Equal(matchTimeout, regex1.MatchTimeout); } Regex regex2 = new Regex(pattern, options); Assert.Equal(pattern, regex2.ToString()); Assert.Equal(options, regex2.Options); Assert.Equal((options & RegexOptions.RightToLeft) != 0, regex2.RightToLeft); Assert.Equal(matchTimeout, regex2.MatchTimeout); } Regex regex3 = new Regex(pattern, options, matchTimeout); Assert.Equal(pattern, regex3.ToString()); Assert.Equal(options, regex3.Options); Assert.Equal((options & RegexOptions.RightToLeft) != 0, regex3.RightToLeft); Assert.Equal(matchTimeout, regex3.MatchTimeout); } [Fact] public static void Ctor_Invalid() { // Pattern is null Assert.Throws<ArgumentNullException>("pattern", () => new Regex(null)); Assert.Throws<ArgumentNullException>("pattern", () => new Regex(null, RegexOptions.None)); Assert.Throws<ArgumentNullException>("pattern", () => new Regex(null, RegexOptions.None, new TimeSpan())); // Options are invalid Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)(-1))); Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)(-1), new TimeSpan())); Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)0x400)); Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)0x400, new TimeSpan())); Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.RightToLeft)); Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture)); Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Singleline)); Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace)); // MatchTimeout is invalid Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, new TimeSpan(-1))); Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, TimeSpan.Zero)); Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, TimeSpan.FromMilliseconds(int.MaxValue))); } [Fact] public void CacheSize_Get() { Assert.Equal(15, Regex.CacheSize); } [Theory] [InlineData(0)] [InlineData(12)] public void CacheSize_Set(int newCacheSize) { int originalCacheSize = Regex.CacheSize; Regex.CacheSize = newCacheSize; Assert.Equal(newCacheSize, Regex.CacheSize); Regex.CacheSize = originalCacheSize; } [Fact] public void CacheSize_Set_NegativeValue_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("value", () => Regex.CacheSize = -1); } [Theory] // \d, \D, \s, \S, \w, \W, \P, \p inside character range [InlineData(@"cat([a-\d]*)dog", RegexOptions.None)] [InlineData(@"([5-\D]*)dog", RegexOptions.None)] [InlineData(@"cat([6-\s]*)dog", RegexOptions.None)] [InlineData(@"cat([c-\S]*)", RegexOptions.None)] [InlineData(@"cat([7-\w]*)", RegexOptions.None)] [InlineData(@"cat([a-\W]*)dog", RegexOptions.None)] [InlineData(@"([f-\p{Lu}]\w*)\s([\p{Lu}]\w*)", RegexOptions.None)] [InlineData(@"([1-\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", RegexOptions.None)] [InlineData(@"[\p]", RegexOptions.None)] [InlineData(@"[\P]", RegexOptions.None)] [InlineData(@"([\pcat])", RegexOptions.None)] [InlineData(@"([\Pcat])", RegexOptions.None)] [InlineData(@"(\p{", RegexOptions.None)] [InlineData(@"(\p{Ll", RegexOptions.None)] // \x, \u, \a, \b, \e, \f, \n, \r, \t, \v, \c, inside character range [InlineData(@"(cat)([\o]*)(dog)", RegexOptions.None)] // Use < in a group [InlineData(@"cat(?<0>dog)", RegexOptions.None)] [InlineData(@"cat(?<1dog>dog)", RegexOptions.None)] [InlineData(@"cat(?<dog)_*>dog)", RegexOptions.None)] [InlineData(@"cat(?<dog!>)_*>dog)", RegexOptions.None)] [InlineData(@"cat(?<dog >)_*>dog)", RegexOptions.None)] [InlineData(@"cat(?<dog<>)_*>dog)", RegexOptions.None)] [InlineData(@"cat(?<>dog)", RegexOptions.None)] [InlineData(@"cat(?<->dog)", RegexOptions.None)] [InlineData(@"(?<cat>cat)\w+(?<dog-16>dog)", RegexOptions.None)] [InlineData(@"(?<cat>cat)\w+(?<dog-1uosn>dog)", RegexOptions.None)] [InlineData(@"(?<cat>cat)\w+(?<dog-catdog>dog)", RegexOptions.None)] [InlineData(@"(?<cat>cat)\w+(?<dog-()*!@>dog)", RegexOptions.None)] // Use (? in a group [InlineData("cat(?(?#COMMENT)cat)", RegexOptions.None)] [InlineData("cat(?(?'cat'cat)dog)", RegexOptions.None)] [InlineData("cat(?(?<cat>cat)dog)", RegexOptions.None)] [InlineData("cat(?(?afdcat)dog)", RegexOptions.None)] // Pattern whitespace [InlineData(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace", RegexOptions.IgnorePatternWhitespace)] [InlineData(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace", RegexOptions.None)] // Back reference [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\kcat", RegexOptions.None)] [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k<cat2>", RegexOptions.None)] [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k<8>cat", RegexOptions.None)] [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k<8>cat", RegexOptions.ECMAScript)] [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k8", RegexOptions.None)] [InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k8", RegexOptions.ECMAScript)] // Octal, decimal [InlineData(@"(cat)(\7)", RegexOptions.None)] [InlineData(@"(cat)\s+(?<2147483648>dog)", RegexOptions.None)] [InlineData(@"(cat)\s+(?<21474836481097>dog)", RegexOptions.None)] // Scan control [InlineData(@"(cat)(\c*)(dog)", RegexOptions.None)] [InlineData(@"(cat)\c", RegexOptions.None)] [InlineData(@"(cat)(\c *)(dog)", RegexOptions.None)] [InlineData(@"(cat)(\c?*)(dog)", RegexOptions.None)] [InlineData("(cat)(\\c\0*)(dog)", RegexOptions.None)] [InlineData(@"(cat)(\c`*)(dog)", RegexOptions.None)] [InlineData(@"(cat)(\c\|*)(dog)", RegexOptions.None)] [InlineData(@"(cat)(\c\[*)(dog)", RegexOptions.None)] // Nested quantifiers [InlineData("^[abcd]{0,16}*$", RegexOptions.None)] [InlineData("^[abcd]{1,}*$", RegexOptions.None)] [InlineData("^[abcd]{1}*$", RegexOptions.None)] [InlineData("^[abcd]{0,16}?*$", RegexOptions.None)] [InlineData("^[abcd]{1,}?*$", RegexOptions.None)] [InlineData("^[abcd]{1}?*$", RegexOptions.None)] [InlineData("^[abcd]*+$", RegexOptions.None)] [InlineData("^[abcd]+*$", RegexOptions.None)] [InlineData("^[abcd]?*$", RegexOptions.None)] [InlineData("^[abcd]*?+$", RegexOptions.None)] [InlineData("^[abcd]+?*$", RegexOptions.None)] [InlineData("^[abcd]??*$", RegexOptions.None)] [InlineData("^[abcd]*{0,5}$", RegexOptions.None)] [InlineData("^[abcd]+{0,5}$", RegexOptions.None)] [InlineData("^[abcd]?{0,5}$", RegexOptions.None)] // Invalid character escapes [InlineData(@"\u", RegexOptions.None)] [InlineData(@"\ua", RegexOptions.None)] [InlineData(@"\u0", RegexOptions.None)] [InlineData(@"\x", RegexOptions.None)] [InlineData(@"\x2", RegexOptions.None)] // Invalid character class [InlineData("[", RegexOptions.None)] [InlineData("[]", RegexOptions.None)] [InlineData("[a", RegexOptions.None)] [InlineData("[^", RegexOptions.None)] [InlineData("[cat", RegexOptions.None)] [InlineData("[^cat", RegexOptions.None)] [InlineData("[a-", RegexOptions.None)] [InlineData(@"\p{", RegexOptions.None)] [InlineData(@"\p{cat", RegexOptions.None)] [InlineData(@"\p{cat}", RegexOptions.None)] [InlineData(@"\P{", RegexOptions.None)] [InlineData(@"\P{cat", RegexOptions.None)] [InlineData(@"\P{cat}", RegexOptions.None)] // Invalid grouping constructs [InlineData("(", RegexOptions.None)] [InlineData("(?", RegexOptions.None)] [InlineData("(?<", RegexOptions.None)] [InlineData("(?<cat>", RegexOptions.None)] [InlineData("(?'", RegexOptions.None)] [InlineData("(?'cat'", RegexOptions.None)] [InlineData("(?:", RegexOptions.None)] [InlineData("(?imn", RegexOptions.None)] [InlineData("(?imn )", RegexOptions.None)] [InlineData("(?=", RegexOptions.None)] [InlineData("(?!", RegexOptions.None)] [InlineData("(?<=", RegexOptions.None)] [InlineData("(?<!", RegexOptions.None)] [InlineData("(?>", RegexOptions.None)] [InlineData("(?)", RegexOptions.None)] [InlineData("(?<)", RegexOptions.None)] [InlineData("(?')", RegexOptions.None)] [InlineData(@"\1", RegexOptions.None)] [InlineData(@"\1", RegexOptions.None)] [InlineData(@"\k", RegexOptions.None)] [InlineData(@"\k<", RegexOptions.None)] [InlineData(@"\k<1", RegexOptions.None)] [InlineData(@"\k<cat", RegexOptions.None)] [InlineData(@"\k<>", RegexOptions.None)] // Invalid alternation constructs [InlineData("(?(", RegexOptions.None)] [InlineData("(?()|", RegexOptions.None)] [InlineData("(?(cat", RegexOptions.None)] [InlineData("(?(cat)|", RegexOptions.None)] // Regex with 0 numeric names [InlineData("foo(?<0>bar)", RegexOptions.None)] [InlineData("foo(?'0'bar)", RegexOptions.None)] // Regex without closing > [InlineData("foo(?<1bar)", RegexOptions.None)] [InlineData("foo(?'1bar)", RegexOptions.None)] // Misc [InlineData(@"\p{klsak", RegexOptions.None)] [InlineData("(?r:cat)", RegexOptions.None)] [InlineData("(?c:cat)", RegexOptions.None)] [InlineData("(??e:cat)", RegexOptions.None)] // Character class subtraction [InlineData("[a-f-[]]+", RegexOptions.None)] // Not character class substraction [InlineData("[A-[]+", RegexOptions.None)] public void Ctor_InvalidPattern(string pattern, RegexOptions options) { Assert.Throws<ArgumentException>(() => new Regex(pattern, options)); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using Aurora.Simulation.Base; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using Aurora.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; namespace OpenSim.Services { public class ServerConnector : IService, IGridRegistrationUrlModule { private IRegistryCore m_registry; private IConfigSource m_config; public string Name { get { return GetType().Name; } } #region IGridRegistrationUrlModule Members public string UrlName { get { return "ServerURI"; } } public bool DoMultiplePorts { get { return true; } } public void AddExistingUrlForClient(string SessionID, string url, uint port) { IHttpServer server = m_registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(port); server.AddStreamHandler(new ServerHandler(url, SessionID, m_registry)); } public string GetUrlForRegisteringClient(string SessionID, uint port) { IHttpServer server = m_registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(port); string url = "/server" + UUID.Random(); server.AddStreamHandler(new ServerHandler(url, SessionID, m_registry)); return url; } public void RemoveUrlForClient(string sessionID, string url, uint port) { IHttpServer server = m_registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(port); server.RemoveHTTPHandler("POST", url); } #endregion #region IService Members public void Initialize(IConfigSource config, IRegistryCore registry) { } public void Start(IConfigSource config, IRegistryCore registry) { m_config = config; IConfig handlerConfig = config.Configs["AuroraConnectors"]; if (!handlerConfig.GetBoolean("AllowRemoteCalls", false)) return; m_registry = registry; m_registry.RequestModuleInterface<IGridRegistrationService>().RegisterModule(this); } public void FinishedStartup() { if (m_registry != null) { uint port = m_config.Configs["Network"].GetUInt("http_listener_port", 8003); AddExistingUrlForClient("", "/", port); //AddUDPConector(8008); } } /*private void AddUDPConector(int port) { Thread thread = new Thread(delegate() { UdpClient server = new UdpClient("127.0.0.1", port); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); byte[] data = server.Receive(ref sender); OSDMap map = (OSDMap)OSDParser.DeserializeJson(new MemoryStream(data)); ServerHandler handler = new ServerHandler("", "", m_registry); byte[] Data = handler.HandleMap(map); }); }*/ #endregion } public class MethodImplementation { public MethodInfo Method; public ConnectorBase Reference; public CanBeReflected Attribute; } public class ServerHandler : BaseStreamHandler { protected string m_SessionID; protected IRegistryCore m_registry; protected static Dictionary<string, List<MethodImplementation>> m_methods = null; public ServerHandler(string url, string SessionID, IRegistryCore registry) : base("POST", url) { m_SessionID = SessionID; m_registry = registry; if (m_methods == null) { m_methods = new Dictionary<string, List<MethodImplementation>>(); List<string> alreadyRunPlugins = new List<string>(); foreach (ConnectorBase plugin in ConnectorRegistry.Connectors) { if (alreadyRunPlugins.Contains(plugin.PluginName)) continue; alreadyRunPlugins.Add(plugin.PluginName); foreach (MethodInfo method in plugin.GetType().GetMethods()) { CanBeReflected reflection = (CanBeReflected)Attribute.GetCustomAttribute(method, typeof(CanBeReflected)); if (reflection != null) { string methodName = reflection.RenamedMethod == "" ? method.Name : reflection.RenamedMethod; List<MethodImplementation> methods = new List<MethodImplementation>(); MethodImplementation imp = new MethodImplementation() { Method = method, Reference = plugin, Attribute = reflection }; if (!m_methods.TryGetValue(methodName, out methods)) m_methods.Add(methodName, (methods = new List<MethodImplementation>())); methods.Add(imp); } } } } } public override byte[] Handle(string path, Stream requestData, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); try { OSDMap args = WebUtils.GetOSDMap(body, false); if (args != null) return HandleMap(args); } catch(Exception ex) { MainConsole.Instance.Warn("[ServerHandler]: Error occured: " + ex.ToString()); } return new byte[0]; } public byte[] HandleMap(OSDMap args) { if (args.ContainsKey("Method")) { IGridRegistrationService urlModule = m_registry.RequestModuleInterface<IGridRegistrationService>(); string method = args["Method"].AsString(); MethodImplementation methodInfo; if (GetMethodInfo(method, args.Count - 1, out methodInfo)) { if (m_SessionID == "") { if (methodInfo.Attribute.ThreatLevel != ThreatLevel.None) return new byte[0]; } else if (!urlModule.CheckThreatLevel(m_SessionID, method, methodInfo.Attribute.ThreatLevel)) return new byte[0]; MainConsole.Instance.Debug("[Server]: Method Called: " + method); ParameterInfo[] paramInfo = methodInfo.Method.GetParameters(); object[] parameters = new object[paramInfo.Length]; int paramNum = 0; foreach (ParameterInfo param in paramInfo) parameters[paramNum++] = Util.OSDToObject(args[param.Name], param.ParameterType); object o = methodInfo.Method.FastInvoke(paramInfo, methodInfo.Reference, parameters); OSDMap response = new OSDMap(); if (o == null)//void method response["Value"] = "null"; else response["Value"] = Util.MakeOSD(o, methodInfo.Method.ReturnType); response["Success"] = true; return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(response, true)); } } MainConsole.Instance.Warn("[ServerHandler]: Post did not have a method block"); return new byte[0]; } private bool GetMethodInfo(string method, int parameters, out MethodImplementation methodInfo) { List<MethodImplementation> methods = new List<MethodImplementation>(); if (m_methods.TryGetValue(method, out methods)) { if (methods.Count == 1) { methodInfo = methods[0]; return true; } foreach (MethodImplementation m in methods) { if (m.Method.GetParameters().Length == parameters) { methodInfo = m; return true; } } } MainConsole.Instance.Warn("COULD NOT FIND METHOD: " + method); methodInfo = null; return false; } } }
//----------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // 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 Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.IdentityModel.Protocols.WSTrust; using System.IdentityModel.Tokens; using System.Security.Claims; using Saml2SecurityTokenHandler = Microsoft.IdentityModel.Tokens.Saml2SecurityTokenHandler; namespace Microsoft.IdentityModel.Test { /// <summary> /// /// </summary> [TestClass] public class Saml2SecurityTokenHandlerTests { public TestContext TestContext { get; set; } [ClassInitialize] public static void ClassSetup(TestContext testContext) { } [ClassCleanup] public static void ClassCleanup() { } [TestInitialize] public void Initialize() { } [TestMethod] [TestProperty("TestCaseID", "f0b4edf5-e1bd-448f-9c0f-50b2a47bfd24")] [Description("Tests: Constructors")] public void Saml2SecurityTokenHandler_Constructors() { Saml2SecurityTokenHandler saml2SecurityTokenHandler = new Saml2SecurityTokenHandler(); } [TestMethod] [TestProperty("TestCaseID", "1832c430-b491-48db-86bb-59faf72304bd")] [Description("Tests: Defaults")] public void Saml2SecurityTokenHandler_Defaults() { Saml2SecurityTokenHandler samlSecurityTokenHandler = new Saml2SecurityTokenHandler(); Assert.IsTrue(samlSecurityTokenHandler.MaximumTokenSizeInBytes == TokenValidationParameters.DefaultMaximumTokenSizeInBytes, "MaximumTokenSizeInBytes"); } [TestMethod] [TestProperty("TestCaseID", "e40d2758-e36c-4b52-9ac9-31bcfc27c308")] [Description("Tests: GetSets")] public void Saml2SecurityTokenHandler_GetSets() { Saml2SecurityTokenHandler samlSecurityTokenHandler = new Saml2SecurityTokenHandler(); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)0, ExpectedException.ArgumentOutOfRangeException(substringExpected: "IDX10101")); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)1, ExpectedException.NoExceptionExpected); } [TestMethod] [TestProperty("TestCaseID", "617fb57a-9b95-40a3-8cf4-652b33450a54")] [Description("Tests: Publics")] public void Saml2SecurityTokenHandler_Publics() { //CanReadToken(); ValidateAudience(); ValidateIssuer(); } private void CanReadToken() { // CanReadToken Saml2SecurityTokenHandler samlSecurityTokenHandler = new Saml2SecurityTokenHandler(); Assert.IsFalse(CanReadToken(securityToken: null, samlSecurityTokenHandler: samlSecurityTokenHandler, expectedException: ExpectedException.NoExceptionExpected)); string samlString = new string('S', TokenValidationParameters.DefaultMaximumTokenSizeInBytes + 1); Assert.IsFalse(CanReadToken(samlString, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected)); samlString = new string('S', TokenValidationParameters.DefaultMaximumTokenSizeInBytes); CanReadToken(securityToken: samlString, samlSecurityTokenHandler: samlSecurityTokenHandler, expectedException: ExpectedException.NoExceptionExpected); samlString = IdentityUtilities.CreateSamlToken(); Assert.IsFalse(CanReadToken(securityToken: samlString, samlSecurityTokenHandler: samlSecurityTokenHandler, expectedException: ExpectedException.NoExceptionExpected)); samlString = IdentityUtilities.CreateSaml2Token(); Assert.IsTrue(CanReadToken(securityToken: samlString, samlSecurityTokenHandler: samlSecurityTokenHandler, expectedException: ExpectedException.NoExceptionExpected)); } private bool CanReadToken(string securityToken, Saml2SecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { bool canReadToken = false; try { canReadToken = samlSecurityTokenHandler.CanReadToken(securityToken); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return canReadToken; } private void ValidateIssuer() { DerivedSamlSecurityTokenHandler samlSecurityTokenHandler = new DerivedSamlSecurityTokenHandler(); ExpectedException expectedException = ExpectedException.NoExceptionExpected; ValidateIssuer(null, new TokenValidationParameters { ValidateIssuer = false }, samlSecurityTokenHandler, expectedException); expectedException = ExpectedException.ArgumentNullException( substringExpected: "Parameter name: validationParameters"); ValidateIssuer("bob", null, samlSecurityTokenHandler, expectedException); expectedException = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10204"); ValidateIssuer("bob", new TokenValidationParameters { }, samlSecurityTokenHandler, expectedException); expectedException = ExpectedException.NoExceptionExpected; string issuer = ValidateIssuer("bob", new TokenValidationParameters { ValidIssuer = "bob" }, samlSecurityTokenHandler, expectedException); Assert.IsTrue(issuer == "bob", "issuer mismatch"); expectedException = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205"); ValidateIssuer("bob", new TokenValidationParameters { ValidIssuer = "frank" }, samlSecurityTokenHandler, expectedException); List<string> validIssuers = new List<string> { "john", "paul", "george", "ringo" }; expectedException = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205"); ValidateIssuer("bob", new TokenValidationParameters { ValidIssuers = validIssuers }, samlSecurityTokenHandler, expectedException); expectedException = ExpectedException.NoExceptionExpected; ValidateIssuer("bob", new TokenValidationParameters { ValidateIssuer = false }, samlSecurityTokenHandler, expectedException); validIssuers.Add("bob"); expectedException = ExpectedException.NoExceptionExpected; issuer = ValidateIssuer("bob", new TokenValidationParameters { ValidIssuers = validIssuers }, samlSecurityTokenHandler, expectedException); Assert.IsTrue(issuer == "bob", "issuer mismatch"); expectedException = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10204"); TokenValidationParameters validationParameters = new TokenValidationParameters { ValidateAudience = false, IssuerValidator = IdentityUtilities.IssuerValidatorEcho, }; ValidateIssuer("bob", validationParameters, samlSecurityTokenHandler, expectedException); // no delegate secondary should still succeed expectedException = ExpectedException.NoExceptionExpected; validationParameters = new TokenValidationParameters { ValidateAudience = false, ValidIssuers = validIssuers, }; issuer = ValidateIssuer("bob", validationParameters, samlSecurityTokenHandler, expectedException); Assert.IsTrue(issuer == "bob", "issuer mismatch"); // no delegate, secondary should fail validIssuers = new List<string> { "john", "paul", "george", "ringo" }; expectedException = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205"); validationParameters = new TokenValidationParameters { IssuerSigningKey = new X509SecurityKey(KeyingMaterial.DefaultCert_2048), ValidateAudience = false, ValidIssuer = "http://Bob", }; ValidateIssuer("bob", validationParameters, samlSecurityTokenHandler, expectedException); validationParameters.ValidateIssuer = false; validationParameters.IssuerValidator = IdentityUtilities.IssuerValidatorThrows; ValidateIssuer("bob", validationParameters, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); } private string ValidateIssuer(string issuer, TokenValidationParameters validationParameters, DerivedSamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { string returnVal = string.Empty; try { returnVal = samlSecurityTokenHandler.ValidateIssuerPublic(issuer, new DerivedSaml2SecurityToken(), validationParameters); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return returnVal; } [TestMethod] [TestProperty("TestCaseID", "142ADF8F-F8A8-4E89-A795-53BFB39C660F")] [Description("Tests: ValidateToken")] public void Saml2SecurityTokenHandler_ValidateToken() { // parameter validation Saml2SecurityTokenHandler tokenHandler = new Saml2SecurityTokenHandler(); TestUtilities.ValidateToken(securityToken: null, validationParameters: new TokenValidationParameters(), tokenValidator: tokenHandler, expectedException: ExpectedException.ArgumentNullException(substringExpected: "name: securityToken")); TestUtilities.ValidateToken(securityToken: "s", validationParameters: null, tokenValidator: tokenHandler, expectedException: ExpectedException.ArgumentNullException(substringExpected: "name: validationParameters")); tokenHandler.MaximumTokenSizeInBytes = 1; TestUtilities.ValidateToken(securityToken: "ss", validationParameters: new TokenValidationParameters(), tokenValidator: tokenHandler, expectedException: ExpectedException.ArgumentException(substringExpected: "IDX10209")); tokenHandler.MaximumTokenSizeInBytes = TokenValidationParameters.DefaultMaximumTokenSizeInBytes; string samlToken = IdentityUtilities.CreateSaml2Token(); TestUtilities.ValidateToken(samlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, tokenHandler, ExpectedException.NoExceptionExpected); // EncryptedAssertion SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor { AppliesToAddress = IdentityUtilities.DefaultAudience, EncryptingCredentials = new EncryptedKeyEncryptingCredentials(KeyingMaterial.DefaultAsymmetricCert_2048), Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromHours(1)), SigningCredentials = KeyingMaterial.DefaultAsymmetricSigningCreds_2048_RsaSha2_Sha2, Subject = IdentityUtilities.DefaultClaimsIdentity, TokenIssuerName = IdentityUtilities.DefaultIssuer, }; samlToken = IdentityUtilities.CreateSaml2Token(tokenDescriptor); TestUtilities.ValidateToken(samlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, tokenHandler, new ExpectedException(typeExpected: typeof(EncryptedTokenDecryptionFailedException), substringExpected: "ID4022")); TokenValidationParameters validationParameters = IdentityUtilities.DefaultAsymmetricTokenValidationParameters; validationParameters.ClientDecryptionTokens = new List<SecurityToken>{ KeyingMaterial.DefaultX509Token_2048 }.AsReadOnly(); TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, ExpectedException.NoExceptionExpected); TestUtilities.ValidateTokenReplay(samlToken, tokenHandler, validationParameters); TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, ExpectedException.NoExceptionExpected); validationParameters.LifetimeValidator = (nb, exp, st, tvp) => { return false; }; TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, new ExpectedException(typeExpected: typeof(SecurityTokenInvalidLifetimeException), substringExpected: "IDX10230:")); validationParameters.ValidateLifetime = false; validationParameters.LifetimeValidator = IdentityUtilities.LifetimeValidatorThrows; TestUtilities.ValidateToken(securityToken: samlToken, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: ExpectedException.NoExceptionExpected); } private void ValidateAudience() { Saml2SecurityTokenHandler tokenHandler = new Saml2SecurityTokenHandler(); ExpectedException expectedException; string samlString = IdentityUtilities.CreateSaml2Token(); TokenValidationParameters validationParameters = new TokenValidationParameters { IssuerSigningToken = IdentityUtilities.DefaultAsymmetricSigningToken, RequireExpirationTime = false, RequireSignedTokens = false, ValidIssuer = IdentityUtilities.DefaultIssuer, }; // Do not validate audience validationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // no valid audiences validationParameters.ValidateAudience = true; expectedException = ExpectedException.SecurityTokenInvalidAudienceException("IDX10208"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = true; validationParameters.ValidAudience = "John"; expectedException = new ExpectedException(typeExpected: typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // UriKind.Absolute, no match. validationParameters.ValidateAudience = true; validationParameters.ValidAudience = IdentityUtilities.NotDefaultAudience; expectedException = new ExpectedException(typeExpected: typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); expectedException = ExpectedException.NoExceptionExpected; validationParameters.ValidAudience = IdentityUtilities.DefaultAudience; validationParameters.ValidAudiences = null; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // !UriKind.Absolute List<string> audiences = new List<string> { "John", "Paul", "George", "Ringo" }; validationParameters.ValidAudience = null; validationParameters.ValidAudiences = audiences; validationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // UriKind.Absolute, no match audiences = new List<string> { "http://www.John.com", "http://www.Paul.com", "http://www.George.com", "http://www.Ringo.com", " " }; validationParameters.ValidAudience = null; validationParameters.ValidAudiences = audiences; validationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = true; expectedException = new ExpectedException(typeExpected: typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = true; expectedException = ExpectedException.NoExceptionExpected; audiences.Add(IdentityUtilities.DefaultAudience); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.AudienceValidator = (aud, token, tvp) => { return false; }; expectedException = new ExpectedException(typeExpected: typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10231:"); audiences.Add(IdentityUtilities.DefaultAudience); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = false; validationParameters.AudienceValidator = IdentityUtilities.AudienceValidatorThrows; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: ExpectedException.NoExceptionExpected); } private class DerivedSamlSecurityTokenHandler : Saml2SecurityTokenHandler { public ClaimsIdentity CreateClaimsPublic(Saml2SecurityToken samlToken, string issuer, TokenValidationParameters validationParameters) { return base.CreateClaimsIdentity(samlToken, issuer, validationParameters); } public string ValidateIssuerPublic(string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters) { return base.ValidateIssuer(issuer, securityToken, validationParameters); } } private class DerivedSaml2SecurityToken : Saml2SecurityToken { public Saml2Assertion SamlAssertion { get; set; } public DerivedSaml2SecurityToken() : base(new DerivedSaml2Assertion(IdentityUtilities.DefaultIssuer)) { } public DerivedSaml2SecurityToken(Saml2Assertion samlAssertion) : base(samlAssertion) { } } private class DerivedSaml2Assertion : Saml2Assertion { public DerivedSaml2Assertion(string issuer) : base(new Saml2NameIdentifier(issuer)) { DerivedIssuer = issuer; } public string DerivedIssuer { get; set; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Data; using System.Data.SqlClient; using Microsoft.Synchronization; using Microsoft.Synchronization.Data; namespace SyncApplication { public partial class SyncForm : Form { ProgressForm _progressForm; string fromPeer = string.Empty, toPeer = string.Empty; public SyncForm() { InitializeComponent(); if (string.IsNullOrEmpty(textPeer1Machine.Text)) { textPeer1Machine.Text = Environment.MachineName; } if (string.IsNullOrEmpty(textPeer2Machine.Text)) { textPeer2Machine.Text = Environment.MachineName; } if (string.IsNullOrEmpty(textPeer3Machine.Text)) { textPeer3Machine.Text = Environment.MachineName; } _progressForm = null; } DbSyncProvider SetupSyncProvider(string connectionString, DbSyncProvider peerProvider) { const int TombstoneAgingInHours = 100; SqlConnection connection = new SqlConnection(connectionString); peerProvider.Connection = connection; // // 1. Create sync adapter for each sync table and attach it to the provider // Following DataAdapter style in ADO.NET, DbSyncAdapter is the equivelent for sync. // The code below shows how to create DbSyncAdapter objects for orders // and order_details tables using stored procedures stored on the database. // peerProvider.ScopeName = "Sales"; string ordersTableName = "orders"; if (connection.Database == "peer1") { ordersTableName = "ordertable"; } // orders table DbSyncAdapter adaptorOrders = null; if (connection.Database == "peer1") { adaptorOrders = new DbSyncAdapter(ordersTableName, "orders"); DbSyncColumnMappingCollection colMap = adaptorOrders.ColumnMappings; colMap.Add("orderid", "order_id"); colMap.Add("orderdate", "order_date"); adaptorOrders.RowIdColumns.Add("orderid"); } else { adaptorOrders = new DbSyncAdapter(ordersTableName); adaptorOrders.RowIdColumns.Add("order_id"); } // select incremental changes command SqlCommand chgsOrdersCmd = new SqlCommand(); chgsOrdersCmd.CommandType = CommandType.StoredProcedure; chgsOrdersCmd.CommandText = "sp_" + ordersTableName + "_selectchanges"; chgsOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncMetadataOnly, SqlDbType.Int); chgsOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncMinTimestamp, SqlDbType.BigInt); adaptorOrders.SelectIncrementalChangesCommand = chgsOrdersCmd; string orderidCol = null; string orderdateCol = null; if (connection.Database == "peer1") { orderidCol = "@orderid"; orderdateCol = "@orderdate"; } else { orderidCol = "@order_id"; orderdateCol = "@order_date"; } // insert row command SqlCommand insOrdersCmd = new SqlCommand(); insOrdersCmd.CommandType = CommandType.StoredProcedure; insOrdersCmd.CommandText = "sp_" + ordersTableName + "_applyinsert"; insOrdersCmd.Parameters.Add(orderidCol, SqlDbType.Int); insOrdersCmd.Parameters.Add(orderdateCol, SqlDbType.DateTime); insOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrders.InsertCommand = insOrdersCmd; // update row command SqlCommand updOrdersCmd = new SqlCommand(); updOrdersCmd.CommandType = CommandType.StoredProcedure; updOrdersCmd.CommandText = "sp_" + ordersTableName + "_applyupdate"; updOrdersCmd.Parameters.Add(orderidCol, SqlDbType.Int); updOrdersCmd.Parameters.Add(orderdateCol, SqlDbType.DateTime); updOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncMinTimestamp, SqlDbType.BigInt); updOrdersCmd.Parameters.Add("@sync_force_write", SqlDbType.Int); updOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrders.UpdateCommand = updOrdersCmd; // delete row command SqlCommand delOrdersCmd = new SqlCommand(); delOrdersCmd.CommandType = CommandType.StoredProcedure; delOrdersCmd.CommandText = "sp_" + ordersTableName + "_applydelete"; delOrdersCmd.Parameters.Add(orderidCol, SqlDbType.Int); delOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncMinTimestamp, SqlDbType.BigInt); delOrdersCmd.Parameters.Add("@sync_force_write", SqlDbType.Int); delOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrders.DeleteCommand = delOrdersCmd; // get row command SqlCommand selRowOrdersCmd = new SqlCommand(); selRowOrdersCmd.CommandType = CommandType.StoredProcedure; selRowOrdersCmd.CommandText = "sp_" + ordersTableName + "_selectrow"; selRowOrdersCmd.Parameters.Add(orderidCol, SqlDbType.Int); adaptorOrders.SelectRowCommand = selRowOrdersCmd; // insert row metadata command SqlCommand insMetadataOrdersCmd = new SqlCommand(); insMetadataOrdersCmd.CommandType = CommandType.StoredProcedure; insMetadataOrdersCmd.CommandText = "sp_" + ordersTableName + "_insertmetadata"; insMetadataOrdersCmd.Parameters.Add(orderidCol, SqlDbType.Int); insMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncCreatePeerKey, SqlDbType.Int); insMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncCreatePeerTimestamp, SqlDbType.BigInt); insMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncUpdatePeerKey, SqlDbType.Int); insMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncUpdatePeerTimestamp, SqlDbType.BigInt); insMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncRowIsTombstone, SqlDbType.Int); insMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrders.InsertMetadataCommand = insMetadataOrdersCmd; // update row metadata command SqlCommand updMetadataOrdersCmd = new SqlCommand(); updMetadataOrdersCmd.CommandType = CommandType.StoredProcedure; updMetadataOrdersCmd.CommandText = "sp_" + ordersTableName + "_updatemetadata"; updMetadataOrdersCmd.Parameters.Add(orderidCol, SqlDbType.Int); updMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncCreatePeerKey, SqlDbType.Int); updMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncCreatePeerTimestamp, SqlDbType.BigInt); updMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncUpdatePeerKey, SqlDbType.Int); updMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncUpdatePeerTimestamp, SqlDbType.BigInt); updMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncCheckConcurrency, SqlDbType.Int); updMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncRowTimestamp, SqlDbType.BigInt); updMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrders.UpdateMetadataCommand = updMetadataOrdersCmd; // delete row metadata command SqlCommand delMetadataOrdersCmd = new SqlCommand(); delMetadataOrdersCmd.CommandType = CommandType.StoredProcedure; delMetadataOrdersCmd.CommandText = "sp_" + ordersTableName + "_deletemetadata"; delMetadataOrdersCmd.Parameters.Add(orderidCol, SqlDbType.Int); delMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncCheckConcurrency, SqlDbType.Int); delMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncRowTimestamp, SqlDbType.BigInt); delMetadataOrdersCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrders.DeleteMetadataCommand = delMetadataOrdersCmd; // get tombstones for cleanup SqlCommand selTombstonesOrdersCmd = new SqlCommand(); selTombstonesOrdersCmd.CommandType = CommandType.StoredProcedure; selTombstonesOrdersCmd.CommandText = "sp_" + ordersTableName + "_selecttombstones"; selTombstonesOrdersCmd.Parameters.Add("@tombstone_aging_in_hours", SqlDbType.Int).Value = TombstoneAgingInHours; adaptorOrders.SelectMetadataForCleanupCommand = selTombstonesOrdersCmd; peerProvider.SyncAdapters.Add(adaptorOrders); // order_details table DbSyncAdapter adaptorOrderDetails = new DbSyncAdapter("order_details"); adaptorOrderDetails.RowIdColumns.Add("order_id"); // select incremental inserts command SqlCommand chgsOrderDetailsCmd = new SqlCommand(); chgsOrderDetailsCmd.CommandType = CommandType.StoredProcedure; chgsOrderDetailsCmd.CommandText = "sp_order_details_selectchanges"; chgsOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncMetadataOnly, SqlDbType.Int); chgsOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncMinTimestamp, SqlDbType.BigInt); adaptorOrderDetails.SelectIncrementalChangesCommand = chgsOrderDetailsCmd; // insert row command SqlCommand insOrderDetailsCmd = new SqlCommand(); insOrderDetailsCmd.CommandType = CommandType.StoredProcedure; insOrderDetailsCmd.CommandText = "sp_order_details_applyinsert"; insOrderDetailsCmd.Parameters.Add("@order_id", SqlDbType.Int); insOrderDetailsCmd.Parameters.Add("@order_details_id", SqlDbType.Int); insOrderDetailsCmd.Parameters.Add("@product", SqlDbType.VarChar, 100); insOrderDetailsCmd.Parameters.Add("@quantity", SqlDbType.Int); insOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrderDetails.InsertCommand = insOrderDetailsCmd; // update row command SqlCommand updOrderDetailsCmd = new SqlCommand(); updOrderDetailsCmd.CommandType = CommandType.StoredProcedure; updOrderDetailsCmd.CommandText = "sp_order_details_applyupdate"; updOrderDetailsCmd.Parameters.Add("@order_id", SqlDbType.Int); updOrderDetailsCmd.Parameters.Add("@order_details_id", SqlDbType.Int); updOrderDetailsCmd.Parameters.Add("@product", SqlDbType.VarChar, 100); updOrderDetailsCmd.Parameters.Add("@quantity", SqlDbType.Int); updOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncMinTimestamp, SqlDbType.BigInt); updOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrderDetails.UpdateCommand = updOrderDetailsCmd; // delete row command SqlCommand delOrderDetailsCmd = new SqlCommand(); delOrderDetailsCmd.CommandType = CommandType.StoredProcedure; delOrderDetailsCmd.CommandText = "sp_order_details_applydelete"; delOrderDetailsCmd.Parameters.Add("@order_id", SqlDbType.Int); delOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncMinTimestamp, SqlDbType.BigInt); delOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrderDetails.DeleteCommand = delOrderDetailsCmd; // get row command SqlCommand selRowOrderDetailsCmd = new SqlCommand(); selRowOrderDetailsCmd.CommandType = CommandType.StoredProcedure; selRowOrderDetailsCmd.CommandText = "sp_order_details_selectrow"; selRowOrderDetailsCmd.Parameters.Add("@order_id", SqlDbType.Int); adaptorOrderDetails.SelectRowCommand = selRowOrderDetailsCmd; // insert row metadata command SqlCommand insMetadataOrderDetailsCmd = new SqlCommand(); insMetadataOrderDetailsCmd.CommandType = CommandType.StoredProcedure; insMetadataOrderDetailsCmd.CommandText = "sp_order_details_insertmetadata"; insMetadataOrderDetailsCmd.Parameters.Add("@order_id", SqlDbType.Int); insMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncCreatePeerKey, SqlDbType.Int); insMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncCreatePeerTimestamp, SqlDbType.BigInt); insMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncUpdatePeerKey, SqlDbType.Int); insMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncUpdatePeerTimestamp, SqlDbType.BigInt); insMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncRowIsTombstone, SqlDbType.Int); insMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrderDetails.InsertMetadataCommand = insMetadataOrderDetailsCmd; // update row metadata command SqlCommand updMetadataOrderDetailsCmd = new SqlCommand(); updMetadataOrderDetailsCmd.CommandType = CommandType.StoredProcedure; updMetadataOrderDetailsCmd.CommandText = "sp_order_details_updatemetadata"; updMetadataOrderDetailsCmd.Parameters.Add("@order_id", SqlDbType.Int); updMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncCreatePeerKey, SqlDbType.Int); updMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncCreatePeerTimestamp, SqlDbType.BigInt); updMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncUpdatePeerKey, SqlDbType.Int); updMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncUpdatePeerTimestamp, SqlDbType.BigInt); updMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncCheckConcurrency, SqlDbType.Int); updMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncRowTimestamp, SqlDbType.BigInt); updMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrderDetails.UpdateMetadataCommand = updMetadataOrderDetailsCmd; // delete row metadata command SqlCommand delMetadataOrderDetailsCmd = new SqlCommand(); delMetadataOrderDetailsCmd.CommandType = CommandType.StoredProcedure; delMetadataOrderDetailsCmd.CommandText = "sp_order_details_deletemetadata"; delMetadataOrderDetailsCmd.Parameters.Add("@order_id", SqlDbType.Int); delMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncCheckConcurrency, SqlDbType.Int); delMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncRowTimestamp, SqlDbType.BigInt); delMetadataOrderDetailsCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; adaptorOrderDetails.DeleteMetadataCommand = delMetadataOrderDetailsCmd; // get tombstones for cleanup SqlCommand selTombstonesOrderDetailsCmd = new SqlCommand(); selTombstonesOrderDetailsCmd.CommandType = CommandType.StoredProcedure; selTombstonesOrderDetailsCmd.CommandText = "sp_order_details_selecttombstones"; selTombstonesOrderDetailsCmd.Parameters.Add("@tombstone_aging_in_hours", SqlDbType.Int).Value = TombstoneAgingInHours; adaptorOrderDetails.SelectMetadataForCleanupCommand = selTombstonesOrderDetailsCmd; peerProvider.SyncAdapters.Add(adaptorOrderDetails); // // 2. Setup provider wide commands // There are few commands on the provider itself and not on a table sync adapter: // SelectNewTimestampCommand: Returns the new high watermark for current sync // SelectScopeInfoCommand: Returns sync knowledge, cleanup knowledge and scope version (timestamp) // UpdateScopeInfoCommand: Sets the new values for sync knowledge and cleanup knowledge // SqlCommand anchorCmd = new SqlCommand(); anchorCmd.CommandType = CommandType.Text; anchorCmd.CommandText = "select @" + DbSyncSession.SyncNewTimestamp + " = @@DBTS"; // for SQL Server 2005 SP2, use "min_active_rowversion() - 1" anchorCmd.Parameters.Add("@" + DbSyncSession.SyncNewTimestamp, SqlDbType.BigInt).Direction = ParameterDirection.Output; peerProvider.SelectNewTimestampCommand = anchorCmd; // // Select local replica info // SqlCommand selReplicaInfoCmd = new SqlCommand(); selReplicaInfoCmd.CommandType = CommandType.Text; selReplicaInfoCmd.CommandText = "select " + "@" + DbSyncSession.SyncScopeId + " = scope_Id, " + "@" + DbSyncSession.SyncScopeKnowledge + " = scope_sync_knowledge, " + "@" + DbSyncSession.SyncScopeCleanupKnowledge + " = scope_tombstone_cleanup_knowledge, " + "@" + DbSyncSession.SyncScopeTimestamp + " = scope_timestamp " + "from scope_info " + "where scope_name = @" + DbSyncSession.SyncScopeName; selReplicaInfoCmd.Parameters.Add("@" + DbSyncSession.SyncScopeName, SqlDbType.NVarChar, 100); selReplicaInfoCmd.Parameters.Add("@" + DbSyncSession.SyncScopeId, SqlDbType.UniqueIdentifier).Direction = ParameterDirection.Output; selReplicaInfoCmd.Parameters.Add("@" + DbSyncSession.SyncScopeKnowledge, SqlDbType.VarBinary, 10000).Direction = ParameterDirection.Output; selReplicaInfoCmd.Parameters.Add("@" + DbSyncSession.SyncScopeCleanupKnowledge, SqlDbType.VarBinary, 10000).Direction = ParameterDirection.Output; selReplicaInfoCmd.Parameters.Add("@" + DbSyncSession.SyncScopeTimestamp, SqlDbType.BigInt).Direction = ParameterDirection.Output; peerProvider.SelectScopeInfoCommand = selReplicaInfoCmd; // // Update local replica info // SqlCommand updReplicaInfoCmd = new SqlCommand(); updReplicaInfoCmd.CommandType = CommandType.Text; updReplicaInfoCmd.CommandText = "update scope_info set " + "scope_sync_knowledge = @" + DbSyncSession.SyncScopeKnowledge + ", " + "scope_tombstone_cleanup_knowledge = @" + DbSyncSession.SyncScopeCleanupKnowledge + " " + "where scope_name = @" + DbSyncSession.SyncScopeName + " ;" + "set @" + DbSyncSession.SyncRowCount + " = @@rowcount"; updReplicaInfoCmd.Parameters.Add("@" + DbSyncSession.SyncScopeKnowledge, SqlDbType.VarBinary, 10000); updReplicaInfoCmd.Parameters.Add("@" + DbSyncSession.SyncScopeCleanupKnowledge, SqlDbType.VarBinary, 10000); updReplicaInfoCmd.Parameters.Add("@" + DbSyncSession.SyncScopeName, SqlDbType.NVarChar, 100); updReplicaInfoCmd.Parameters.Add("@" + DbSyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output; peerProvider.UpdateScopeInfoCommand = updReplicaInfoCmd; // // 3. Track sync process // peerProvider.SyncProgress += new EventHandler<DbSyncProgressEventArgs>(ShowProgress); peerProvider.ApplyChangeFailed += new EventHandler<DbApplyChangeFailedEventArgs>(ShowFailures); return peerProvider; } // // Synchronize Call // private void buttonSynchronize_Click(object sender, EventArgs e) { try { // // 1. Create instance of the sync components (peer, agent, peer) // This demo illustrates direct connection to server database. In this scenario, // all sync components reside in the sample process. // DbSyncProvider localProvider = new DbSyncProvider(); DbSyncProvider remoteProvider = new DbSyncProvider(); localProvider = SetupSyncProvider(GetFromPeerConnectionString(), localProvider); localProvider.SyncProviderPosition = SyncProviderPosition.Local; remoteProvider = SetupSyncProvider(GetToPeerConnectionString(), remoteProvider); remoteProvider.SyncProviderPosition = SyncProviderPosition.Remote; SyncOrchestrator syncOrchestrator = new SyncOrchestrator(); // sync direction: local -> remote syncOrchestrator.LocalProvider = localProvider; syncOrchestrator.RemoteProvider = remoteProvider; syncOrchestrator.Direction = SyncDirectionOrder.Upload; syncOrchestrator.SessionProgress += new EventHandler<SyncStagedProgressEventArgs>(ProgressChanged); _progressForm = new ProgressForm(); _progressForm.Show(); SyncOperationStatistics syncStats = syncOrchestrator.Synchronize(); _progressForm.ShowStatistics(syncStats); // Update the UI _progressForm.EnableClose(); _progressForm = null; } catch (Exception ex) { MessageBox.Show(ex.Message); if (_progressForm != null) { _progressForm.EnableClose(); _progressForm = null; } } } #region UI Code private void buttonExit_Click(object sender, EventArgs e) { Application.Exit(); } public void ShowProgress(object syncOrchestrator, DbSyncProgressEventArgs args) { if (null != _progressForm) { _progressForm.Report(args); } } public void ShowFailures(object syncOrchestrator, DbApplyChangeFailedEventArgs args) { ConflictForm form = new ConflictForm(); form.HandleConflict(fromPeer, toPeer, args); form.ShowDialog(); } public void ProgressChanged(object sender, SyncStagedProgressEventArgs args) { if (null != _progressForm) { _progressForm.ProgressChanged(args); } } protected string GetFromPeerName() { if (fromPeer1.Checked) { return "peer1"; } else if (fromPeer2.Checked) { return "peer2"; } else { return "peer3"; } } protected string GetFromPeerConnectionString() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder["integrated Security"] = true; if (fromPeer1.Checked) { builder["Data Source"] = textPeer1Machine.Text; builder["Initial Catalog"] = "peer1"; } else if (fromPeer2.Checked) { builder["Data Source"] = textPeer2Machine.Text; builder["Initial Catalog"] = "peer2"; } else { builder["Data Source"] = textPeer3Machine.Text; builder["Initial Catalog"] = "peer3"; } return builder.ToString(); } protected string GetToPeerName() { if (toPeer1.Checked) { return "peer1"; } else if (toPeer2.Checked) { return "peer2"; } else { return "peer3"; } } protected string GetToPeerConnectionString() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder["integrated Security"] = true; if (toPeer1.Checked) { builder["Data Source"] = textPeer1Machine.Text; builder["Initial Catalog"] = "peer1"; } else if (toPeer2.Checked) { builder["Data Source"] = textPeer2Machine.Text; builder["Initial Catalog"] = "peer2"; } else { builder["Data Source"] = textPeer3Machine.Text; builder["Initial Catalog"] = "peer3"; } return builder.ToString(); } protected TextBox GetFromPeerChangeTextBox() { if (dataGridOrders.Visible) { if (fromPeer1.Checked) { return textPeer1OrdersChange; } else if (fromPeer2.Checked) { return textPeer2OrdersChange; } else { return textPeer3OrdersChange; } } else { if (fromPeer1.Checked) { return textPeer1OrderDetailsChange; } else if (fromPeer2.Checked) { return textPeer2OrderDetailsChange; } else { return textPeer3OrderDetailsChange; } } } protected TextBox GetToPeerChangeTextBox() { if (dataGridOrders.Visible) { if (toPeer1.Checked) { return textPeer1OrdersChange; } else if (toPeer2.Checked) { return textPeer2OrdersChange; } else { return textPeer3OrdersChange; } } else { if (toPeer1.Checked) { return textPeer1OrderDetailsChange; } else if (toPeer2.Checked) { return textPeer2OrderDetailsChange; } else { return textPeer3OrderDetailsChange; } } } protected void ClearChangeText() { textPeer1OrdersChange.Text = ""; textPeer2OrdersChange.Text = ""; textPeer3OrdersChange.Text = ""; textPeer1OrderDetailsChange.Text = ""; textPeer2OrderDetailsChange.Text = ""; textPeer3OrderDetailsChange.Text = ""; Application.DoEvents(); } protected string GetConnectionString() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder["integrated Security"] = true; if (tabOrders.Visible) { if (radioPeer1Orders.Checked) { builder["Data Source"] = textPeer1Machine.Text; builder["Initial Catalog"] = "peer1"; } else if (radioPeer2Orders.Checked) { builder["Data Source"] = textPeer2Machine.Text; builder["Initial Catalog"] = "peer2"; } else { builder["Data Source"] = textPeer3Machine.Text; builder["Initial Catalog"] = "peer3"; } } else { if (radioPeer1OrderDetails.Checked) { builder["Data Source"] = textPeer1Machine.Text; builder["Initial Catalog"] = "peer1"; } else if (radioPeer2OrderDetails.Checked) { builder["Data Source"] = textPeer2Machine.Text; builder["Initial Catalog"] = "peer2"; } else { builder["Data Source"] = textPeer3Machine.Text; builder["Initial Catalog"] = "peer3"; } } return builder.ToString(); } protected TextBox GetCheckedChangeTextBox() { if (tabOrders.Visible) { if (radioPeer1Orders.Checked) { return textPeer1OrdersChange; } else if (radioPeer2Orders.Checked) { return textPeer2OrdersChange; } else { return textPeer3OrdersChange; } } else { if (radioPeer1OrderDetails.Checked) { return textPeer1OrderDetailsChange; } else if (radioPeer2OrderDetails.Checked) { return textPeer2OrderDetailsChange; } else { return textPeer3OrderDetailsChange; } } } protected void ReportRandomChanges(TextBox textBox, string description) { textBox.Text = description; Application.DoEvents(); } private void buttonRefreshOrders_Click(object sender, EventArgs e) { try { string connectionString = GetConnectionString(); string commandString = "Select * from"; if (connectionString.Contains("peer1")) commandString += " ordertable"; else commandString += " orders"; SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, GetConnectionString()); DataTable dataTable = new DataTable(); dataAdapter.Fill(dataTable); dataGridOrders.DataSource = dataTable; Application.DoEvents(); } catch (Exception exp) { MessageBox.Show(exp.Message); } } private void buttonRefreshOrderDetails_Click(object sender, EventArgs e) { try { string commandString = "Select * from order_details"; SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, GetConnectionString()); DataTable dataTable = new DataTable(); dataAdapter.Fill(dataTable); dataGridOrderDetails.DataSource = dataTable; Application.DoEvents(); } catch (Exception exp) { MessageBox.Show(exp.Message); } } private void radioPeer1Orders_CheckedChanged(object sender, EventArgs e) { buttonRefreshOrders_Click(sender, e); } private void radioPeer2Orders_CheckedChanged(object sender, EventArgs e) { buttonRefreshOrders_Click(sender, e); } private void radioPeer3Orders_CheckedChanged(object sender, EventArgs e) { buttonRefreshOrders_Click(sender, e); } private void radioPeer1OrderDetails_CheckedChanged(object sender, EventArgs e) { buttonRefreshOrderDetails_Click(sender, e); } private void radioPeer2OrderDetails_CheckedChanged(object sender, EventArgs e) { buttonRefreshOrderDetails_Click(sender, e); } private void radioPeer3OrderDetails_CheckedChanged(object sender, EventArgs e) { buttonRefreshOrderDetails_Click(sender, e); } private void fromPeer1_CheckedChanged(object sender, EventArgs e) { if (toPeer1.Checked) { toPeer2.Checked = true; Application.DoEvents(); } } private void fromPeer2_CheckedChanged(object sender, EventArgs e) { if (toPeer2.Checked) { toPeer1.Checked = true; Application.DoEvents(); } } private void fromPeer3_CheckedChanged(object sender, EventArgs e) { if (toPeer3.Checked) { toPeer1.Checked = true; Application.DoEvents(); } } private void toPeer1_CheckedChanged(object sender, EventArgs e) { if (fromPeer1.Checked) { fromPeer2.Checked = true; Application.DoEvents(); } } private void toPeer2_CheckedChanged(object sender, EventArgs e) { if (fromPeer2.Checked) { fromPeer1.Checked = true; Application.DoEvents(); } } private void toPeer3_CheckedChanged(object sender, EventArgs e) { if (fromPeer3.Checked) { fromPeer1.Checked = true; Application.DoEvents(); } } #endregion #region Random Inserts, Updates and Delets to client DB private void InsertOrder(string connString, int key, TextBox changeBox) { SqlConnection connection = new SqlConnection(connString); SqlCommand command = new SqlCommand(); if (connection.Database == "peer1") command.CommandText = "INSERT INTO ordertable(orderid, orderdate) values(@order_id, @order_date)"; else command.CommandText = "INSERT INTO orders(order_id, order_date) values(@order_id, @order_date)"; command.Parameters.AddWithValue("@order_id", key); command.Parameters.AddWithValue("@order_date", DateTime.Now); command.Connection = connection; try { connection.Open(); int count = command.ExecuteNonQuery(); count /= 2; ReportRandomChanges(changeBox, count.ToString() + " rows inserted"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Item Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { connection.Close(); } } private void InsertOrderDetails(string connString, int key, TextBox changeBox) { SqlConnection connection = new SqlConnection(connString); SqlCommand command = new SqlCommand(); command.CommandText = "INSERT INTO order_details(order_id, order_details_id, product, quantity) values(@order_id, @order_details_id, @product, @quantity)"; command.Parameters.AddWithValue("@order_id", key); command.Parameters.AddWithValue("@order_details_id", key % 1000); command.Parameters.AddWithValue("@product", "NEW"); command.Parameters.AddWithValue("@quantity", key % 1000000); command.Connection = connection; try { connection.Open(); int count = command.ExecuteNonQuery(); count /= 2; ReportRandomChanges(changeBox, count.ToString() + " rows inserted"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Item Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { connection.Close(); } } private void UpdateOrder(string connString, int key, TextBox changeBox) { Random rand = new Random(); SqlConnection connection = new SqlConnection(connString); SqlCommand command = new SqlCommand(); if (connection.Database == "peer1") command.CommandText = "UPDATE ordertable SET orderdate = @order_date where orderid % @factor < 10"; else command.CommandText = "UPDATE orders SET order_date = @order_date where order_id % @factor < 10"; command.Parameters.AddWithValue("@factor", key); command.Parameters.AddWithValue("@order_date", DateTime.Now); command.Connection = connection; try { connection.Open(); int count = command.ExecuteNonQuery(); count /= 2; ReportRandomChanges(changeBox, count.ToString() + " rows updated"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Item Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { connection.Close(); } } private void UpdateOrderDetails(string connString, int key, TextBox changeBox) { SqlConnection connection = new SqlConnection(connString); SqlCommand command = new SqlCommand(); command.CommandText = "UPDATE order_details SET quantity = @quantity, product = @product where order_id % @factor < 10"; command.Parameters.AddWithValue("@factor", key); command.Parameters.AddWithValue("@product", "UPD"); command.Parameters.AddWithValue("@quantity", key % 1000000); command.Connection = connection; try { connection.Open(); int count = command.ExecuteNonQuery(); count /= 2; ReportRandomChanges(changeBox, count.ToString() + " rows updated"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Item Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { connection.Close(); } } private void DeleteOrder(string connString, int key, TextBox changeBox) { SqlConnection connection = new SqlConnection(connString); SqlCommand command = new SqlCommand(); if (connection.Database == "peer1") command.CommandText = "DELETE ordertable WHERE orderid % @factor < 5"; else command.CommandText = "DELETE orders WHERE order_id % @factor < 5"; command.Parameters.AddWithValue("@factor", key); command.Connection = connection; try { connection.Open(); int count = command.ExecuteNonQuery(); count /= 2; ReportRandomChanges(changeBox, count.ToString() + " rows deleted"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Item Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { connection.Close(); } } private void DeleteOrderDetails(string connString, int key, TextBox changeBox) { SqlConnection connection = new SqlConnection(connString); SqlCommand command = new SqlCommand(); command.CommandText = "DELETE order_details WHERE order_id % @factor < 10"; command.Parameters.AddWithValue("@factor", key); command.Connection = connection; try { connection.Open(); int count = command.ExecuteNonQuery(); count /= 2; ReportRandomChanges(changeBox, count.ToString() + " rows deleted"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Item Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { connection.Close(); } } private void buttonApplyOrdersInserts_Click(object sender, EventArgs e) { Random rand = new Random(); ClearChangeText(); InsertOrder(GetConnectionString(), rand.Next((int)(DateTime.Now.ToFileTime() % 10000)), GetCheckedChangeTextBox()); } private void buttonApplyOrderDetailsInserts_Click(object sender, EventArgs e) { Random rand = new Random(); ClearChangeText(); InsertOrderDetails(GetConnectionString(), rand.Next((int)(DateTime.Now.ToFileTime() % 10000)), GetCheckedChangeTextBox()); } private void buttonApplyOrdersUpdates_Click(object sender, EventArgs e) { Random rand = new Random(); ClearChangeText(); UpdateOrder(GetConnectionString(), rand.Next((int)(DateTime.Now.ToFileTime() % 1000)), GetCheckedChangeTextBox()); } private void buttonApplyOrderDetailsUpdates_Click(object sender, EventArgs e) { Random rand = new Random(); ClearChangeText(); UpdateOrderDetails(GetConnectionString(), rand.Next((int)(DateTime.Now.ToFileTime() % 1000)), GetCheckedChangeTextBox()); } private void buttonApplyOrdersDeletes_Click(object sender, EventArgs e) { Random rand = new Random(); ClearChangeText(); DeleteOrder(GetConnectionString(), rand.Next((int)(DateTime.Now.ToFileTime()% 1000)), GetCheckedChangeTextBox()); } private void buttonApplyOrderDetailsDeletes_Click(object sender, EventArgs e) { Random rand = new Random(); ClearChangeText(); DeleteOrderDetails(GetConnectionString(), rand.Next((int)(DateTime.Now.ToFileTime() % 1000)), GetCheckedChangeTextBox()); } private void buttonInsInsConflict_Click(object sender, EventArgs e) { Random rand = new Random(); int key = rand.Next((int)(DateTime.Now.ToFileTime() % 10000)); ClearChangeText(); if (dataGridOrders.Visible) { // from peer InsertOrder(GetFromPeerConnectionString(), key, GetFromPeerChangeTextBox()); // to peer InsertOrder(GetToPeerConnectionString(), key, GetToPeerChangeTextBox()); } else { // from peer InsertOrderDetails(GetFromPeerConnectionString(), key, GetFromPeerChangeTextBox()); // to peer InsertOrderDetails(GetToPeerConnectionString(), key, GetToPeerChangeTextBox()); } } private void buttonUpdUpdConflict_Click(object sender, EventArgs e) { Random rand = new Random(); int key = rand.Next((int)(DateTime.Now.ToFileTime() % 10000)); ClearChangeText(); if (dataGridOrders.Visible) { // from peer UpdateOrder(GetFromPeerConnectionString(), key, GetFromPeerChangeTextBox()); // to peer UpdateOrder(GetToPeerConnectionString(), key, GetToPeerChangeTextBox()); } else { // from peer UpdateOrderDetails(GetFromPeerConnectionString(), key, GetFromPeerChangeTextBox()); // to peer UpdateOrderDetails(GetToPeerConnectionString(), key, GetToPeerChangeTextBox()); } } private void buttonUpdDelConflict_Click(object sender, EventArgs e) { Random rand = new Random(); int key = rand.Next((int)(DateTime.Now.ToFileTime() % 100)); ClearChangeText(); if (dataGridOrders.Visible) { // from peer UpdateOrder(GetFromPeerConnectionString(), key, GetFromPeerChangeTextBox()); // to peer DeleteOrder(GetToPeerConnectionString(), key, GetToPeerChangeTextBox()); } else { // from peer UpdateOrderDetails(GetFromPeerConnectionString(), key, GetFromPeerChangeTextBox()); // to peer DeleteOrderDetails(GetToPeerConnectionString(), key, GetToPeerChangeTextBox()); } } #endregion private void buttonCleanupOrdersMetadata_Click(object sender, EventArgs e) { try { DbSyncProvider provider = new DbSyncProvider(); provider = SetupSyncProvider(GetConnectionString(), provider); if (provider.CleanupMetadata() == false) { MessageBox.Show("Metadata cleanup failed. Please retry"); } } catch (Exception ex) { MessageBox.Show(ex.Message); if (_progressForm != null) { _progressForm.EnableClose(); _progressForm = null; } } } } }
using System; using System.Collections.Generic; using System.Linq; using Commencement.Core.Domain; using Commencement.Tests.Core; using Commencement.Tests.Core.Extensions; using Commencement.Tests.Core.Helpers; using FluentNHibernate.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; using UCDArch.Core.PersistanceSupport; using UCDArch.Data.NHibernate; using UCDArch.Testing.Extensions; namespace Commencement.Tests.Repositories { /// <summary> /// Entity Name: TemplateToken /// LookupFieldName: Name /// </summary> [TestClass] public class TemplateTokenRepositoryTests : AbstractRepositoryTests<TemplateToken, int, TemplateTokenMap> { /// <summary> /// Gets or sets the TemplateToken repository. /// </summary> /// <value>The TemplateToken repository.</value> public IRepository<TemplateToken> TemplateTokenRepository { get; set; } #region Init and Overrides /// <summary> /// Initializes a new instance of the <see cref="TemplateTokenRepositoryTests"/> class. /// </summary> public TemplateTokenRepositoryTests() { TemplateTokenRepository = new Repository<TemplateToken>(); } /// <summary> /// Gets the valid entity of type T /// </summary> /// <param name="counter">The counter.</param> /// <returns>A valid entity of type T</returns> protected override TemplateToken GetValid(int? counter) { var rtValue = CreateValidEntities.TemplateToken(counter); rtValue.TemplateType = Repository.OfType<TemplateType>().Queryable.First(); return rtValue; } /// <summary> /// A Query which will return a single record /// </summary> /// <param name="numberAtEnd"></param> /// <returns></returns> protected override IQueryable<TemplateToken> GetQuery(int numberAtEnd) { return TemplateTokenRepository.Queryable.Where(a => a.Name.EndsWith(numberAtEnd.ToString())); } /// <summary> /// A way to compare the entities that were read. /// For example, this would have the assert.AreEqual("Comment" + counter, entity.Comment); /// </summary> /// <param name="entity"></param> /// <param name="counter"></param> protected override void FoundEntityComparison(TemplateToken entity, int counter) { Assert.AreEqual("Name" + counter, entity.Name); } /// <summary> /// Updates , compares, restores. /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> protected override void UpdateUtility(TemplateToken entity, ARTAction action) { const string updateValue = "Updated"; switch (action) { case ARTAction.Compare: Assert.AreEqual(updateValue, entity.Name); break; case ARTAction.Restore: entity.Name = RestoreValue; break; case ARTAction.Update: RestoreValue = entity.Name; entity.Name = updateValue; break; } } /// <summary> /// Loads the data. /// </summary> protected override void LoadData() { TemplateTokenRepository.DbContext.BeginTransaction(); LoadTemplateType(3); LoadRecords(5); TemplateTokenRepository.DbContext.CommitTransaction(); } #endregion Init and Overrides #region TemplateType Tests #region Invalid Tests /// <summary> /// Tests the TemplateType with A value of null does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestTemplateTypeWithAValueOfNullDoesNotSave() { TemplateToken templateToken = null; try { #region Arrange templateToken = GetValid(9); templateToken.TemplateType = null; #endregion Arrange #region Act TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.EnsurePersistent(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(templateToken); Assert.AreEqual(templateToken.TemplateType, null); var results = templateToken.ValidationResults().AsMessageList(); results.AssertErrorsAre("TemplateType: may not be null"); Assert.IsTrue(templateToken.IsTransient()); Assert.IsFalse(templateToken.IsValid()); throw; } } [TestMethod] [ExpectedException(typeof(NHibernate.TransientObjectException))] public void TestTemplateTypeWithANewValueDoesNotSave() { TemplateToken templateToken = null; try { #region Arrange templateToken = GetValid(9); templateToken.TemplateType = CreateValidEntities.TemplateType(9); #endregion Arrange #region Act TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.EnsurePersistent(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception ex) { Assert.IsNotNull(templateToken); Assert.IsNotNull(ex); Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.TemplateType, Entity: Commencement.Core.Domain.TemplateType", ex.Message); throw; } } #endregion Invalid Tests #region Valid Tests [TestMethod] public void TestTemplateTokenWithExistingTemplateTypeSaves() { #region Arrange var templateToken= GetValid(9); templateToken.TemplateType = Repository.OfType<TemplateType>().GetNullableById(2); Assert.IsNotNull(templateToken.TemplateType); #endregion Arrange #region Act TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.EnsurePersistent(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(templateToken.IsTransient()); Assert.IsTrue(templateToken.IsValid()); Assert.IsNotNull(templateToken.TemplateType); #endregion Assert } #endregion Valid Tests [TestMethod] public void TestDeleteTemplateTokenDoesNotCascadeToTemplateType() { #region Arrange var templateToken = GetValid(9); var templateType = Repository.OfType<TemplateType>().GetNullableById(2); templateToken.TemplateType = templateType; Assert.IsNotNull(templateType); TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.EnsurePersistent(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); var saveId = templateToken.Id; NHibernateSessionManager.Instance.GetSession().Evict(templateType); NHibernateSessionManager.Instance.GetSession().Evict(templateToken); #endregion Arrange #region Act templateToken = TemplateTokenRepository.GetNullableById(saveId); Assert.IsNotNull(templateToken); TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.Remove(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); #endregion Act #region Assert NHibernateSessionManager.Instance.GetSession().Evict(templateType); Assert.IsNull(TemplateTokenRepository.GetNullableById(saveId)); Assert.IsNotNull(Repository.OfType<TemplateType>().GetNullableById(2)); #endregion Assert } #region Cascade Tests #endregion Cascade Tests #endregion TemplateType Tests #region Name Tests #region Invalid Tests /// <summary> /// Tests the Name with null value does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestNameWithNullValueDoesNotSave() { TemplateToken templateToken = null; try { #region Arrange templateToken = GetValid(9); templateToken.Name = null; #endregion Arrange #region Act TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.EnsurePersistent(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(templateToken); var results = templateToken.ValidationResults().AsMessageList(); results.AssertErrorsAre("Name: may not be null or empty"); Assert.IsTrue(templateToken.IsTransient()); Assert.IsFalse(templateToken.IsValid()); throw; } } /// <summary> /// Tests the Name with empty string does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestNameWithEmptyStringDoesNotSave() { TemplateToken templateToken = null; try { #region Arrange templateToken = GetValid(9); templateToken.Name = string.Empty; #endregion Arrange #region Act TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.EnsurePersistent(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(templateToken); var results = templateToken.ValidationResults().AsMessageList(); results.AssertErrorsAre("Name: may not be null or empty"); Assert.IsTrue(templateToken.IsTransient()); Assert.IsFalse(templateToken.IsValid()); throw; } } /// <summary> /// Tests the Name with spaces only does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestNameWithSpacesOnlyDoesNotSave() { TemplateToken templateToken = null; try { #region Arrange templateToken = GetValid(9); templateToken.Name = " "; #endregion Arrange #region Act TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.EnsurePersistent(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(templateToken); var results = templateToken.ValidationResults().AsMessageList(); results.AssertErrorsAre("Name: may not be null or empty"); Assert.IsTrue(templateToken.IsTransient()); Assert.IsFalse(templateToken.IsValid()); throw; } } /// <summary> /// Tests the Name with too long value does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestNameWithTooLongValueDoesNotSave() { TemplateToken templateToken = null; try { #region Arrange templateToken = GetValid(9); templateToken.Name = "x".RepeatTimes((50 + 1)); #endregion Arrange #region Act TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.EnsurePersistent(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(templateToken); Assert.AreEqual(50 + 1, templateToken.Name.Length); var results = templateToken.ValidationResults().AsMessageList(); results.AssertErrorsAre("Name: length must be between 0 and 50"); Assert.IsTrue(templateToken.IsTransient()); Assert.IsFalse(templateToken.IsValid()); throw; } } #endregion Invalid Tests #region Valid Tests /// <summary> /// Tests the Name with one character saves. /// </summary> [TestMethod] public void TestNameWithOneCharacterSaves() { #region Arrange var templateToken = GetValid(9); templateToken.Name = "x"; #endregion Arrange #region Act TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.EnsurePersistent(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(templateToken.IsTransient()); Assert.IsTrue(templateToken.IsValid()); #endregion Assert } /// <summary> /// Tests the Name with long value saves. /// </summary> [TestMethod] public void TestNameWithLongValueSaves() { #region Arrange var templateToken = GetValid(9); templateToken.Name = "x".RepeatTimes(50); #endregion Arrange #region Act TemplateTokenRepository.DbContext.BeginTransaction(); TemplateTokenRepository.EnsurePersistent(templateToken); TemplateTokenRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(50, templateToken.Name.Length); Assert.IsFalse(templateToken.IsTransient()); Assert.IsTrue(templateToken.IsValid()); #endregion Assert } #endregion Valid Tests #endregion Name Tests #region Token Tests [TestMethod] public void TestTokenReturnsExpectedValue1() { #region Arrange var record = new TemplateToken(); record.Name = "Test"; #endregion Arrange #region Assert Assert.AreEqual("{Test}", record.Token); #endregion Assert } [TestMethod] public void TestTokenReturnsExpectedValue2() { #region Arrange var record = new TemplateToken(); record.Name = " The quick brown fox Jumps "; #endregion Arrange #region Assert Assert.AreEqual("{ThequickbrownfoxJumps}", record.Token); #endregion Assert } #endregion Token Tests #region Fluent Mapping Tests [TestMethod] public void TestCanCorrectlyMapTemplateToken() { #region Arrange var id = TemplateTokenRepository.Queryable.Max(x => x.Id) + 1; var session = NHibernateSessionManager.Instance.GetSession(); LoadTemplateType(2); var templateType = Repository.OfType<TemplateType>().Queryable.First(); #endregion Arrange #region Act/Assert new PersistenceSpecification<TemplateToken>(session) .CheckProperty(c => c.Id, id) .CheckProperty(c => c.Name, "Name Text") .CheckReference(c => c.TemplateType, templateType) .VerifyTheMappings(); #endregion Act/Assert } #endregion Fluent Mapping Tests #region Reflection of Database. /// <summary> /// Tests all fields in the database have been tested. /// If this fails and no other tests, it means that a field has been added which has not been tested above. /// </summary> [TestMethod] public void TestAllFieldsInTheDatabaseHaveBeenTested() { #region Arrange var expectedFields = new List<NameAndType>(); expectedFields.Add(new NameAndType("Id", "System.Int32", new List<string> { "[Newtonsoft.Json.JsonPropertyAttribute()]", "[System.Xml.Serialization.XmlIgnoreAttribute()]" })); expectedFields.Add(new NameAndType("Name", "System.String", new List<string> { "[NHibernate.Validator.Constraints.LengthAttribute((Int32)50)]", "[UCDArch.Core.NHibernateValidator.Extensions.RequiredAttribute()]" })); expectedFields.Add(new NameAndType("TemplateType", "Commencement.Core.Domain.TemplateType", new List<string> { "[NHibernate.Validator.Constraints.NotNullAttribute()]" })); expectedFields.Add(new NameAndType("Token", "System.String", new List<string>())); #endregion Arrange AttributeAndFieldValidation.ValidateFieldsAndAttributes(expectedFields, typeof(TemplateToken)); } #endregion Reflection of Database. } }
// Copyright (c) 2007-2014 Joe White // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace DGrok.Framework { internal class LexScanner { private class Match { private int _length; private string _parsedText; private TokenType _tokenType; public Match(TokenType tokenType, int length) : this(tokenType, length, "") { } public Match(TokenType tokenType, int length, string parsedText) { _tokenType = tokenType; _length = length; _parsedText = parsedText; } public int Length { get { return _length; } } public string ParsedText { get { return _parsedText; } } public TokenType TokenType { get { return _tokenType; } } } private string _fileName; private int _index; private string _source; private Dictionary<string, TokenType> _wordTypes; public LexScanner(string source, string fileName) { _source = source; _fileName = fileName; _wordTypes = new Dictionary<string, TokenType>(StringComparer.InvariantCultureIgnoreCase); AddWordTypes(TokenSets.Semikeyword, "Semikeyword".Length); AddWordTypes(TokenSets.Keyword, "Keyword".Length); } private Location Location { get { return new Location(_fileName, _source, _index); } } private void AddWordTypes(IEnumerable<TokenType> tokenTypes, int suffixLength) { foreach (TokenType tokenType in tokenTypes) { string tokenString = tokenType.ToString(); string baseWord = tokenString.Substring(0, tokenString.Length - suffixLength); _wordTypes[baseWord.ToLowerInvariant()] = tokenType; } } private Match AmpersandIdentifier() { if (Peek(0) != '&' || !IsWordLeadChar(Peek(1))) return null; int offset = 2; while (IsWordContinuationChar(Peek(offset))) ++offset; return new Match(TokenType.Identifier, offset); } private Match BareWord() { if (!IsWordLeadChar(Peek(0))) return null; int offset = 1; while (IsWordContinuationChar(Peek(offset))) ++offset; string word = _source.Substring(_index, offset); TokenType tokenType; if (_wordTypes.ContainsKey(word)) tokenType = _wordTypes[word]; else tokenType = TokenType.Identifier; return new Match(tokenType, offset); } private bool CanRead(int offset) { return _index + offset < _source.Length; } private Match CurlyBraceComment() { if (Peek(0) != '{') return null; int offset = 1; while (CanRead(offset) && Peek(offset) != '}') ++offset; ++offset; if (Peek(1) == '$') { string parsedText = _source.Substring(_index + 2, offset - 3).TrimEnd(); return new Match(TokenType.CompilerDirective, offset, parsedText); } else return new Match(TokenType.CurlyBraceComment, offset); } private Match DotDot() { if (Peek(0) == '.' && Peek(1) == '.') return new Match(TokenType.DotDot, 2); return null; } private Match DoubleQuotedApostrophe() { if (Peek(0) == '"' && Peek(1) == '\'' && Peek(2) == '"') return new Match(TokenType.StringLiteral, 3); return null; } private Match EqualityOrAssignmentOperator() { switch (Peek(0)) { case ':': if (Peek(1) == '=') return new Match(TokenType.ColonEquals, 2); break; case '<': switch (Peek(1)) { case '=': return new Match(TokenType.LessOrEqual, 2); case '>': return new Match(TokenType.NotEqual, 2); } return new Match(TokenType.LessThan, 1); case '=': return new Match(TokenType.EqualSign, 1); case '>': if (Peek(1) == '=') return new Match(TokenType.GreaterOrEqual, 2); return new Match(TokenType.GreaterThan, 1); } return null; } private Match HexNumber() { if (Peek(0) != '$') return null; int offset = 1; while (IsHexDigit(Peek(offset))) ++offset; return new Match(TokenType.Number, offset); } private bool IsHexDigit(char ch) { return (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'); } private bool IsWordContinuationChar(char ch) { return (Char.IsLetterOrDigit(ch) || ch == '_'); } private bool IsWordLeadChar(char ch) { return (Char.IsLetter(ch) || ch == '_'); } private Match NextMatch() { return BareWord() ?? EqualityOrAssignmentOperator() ?? Number() ?? StringLiteral() ?? SingleLineComment() ?? CurlyBraceComment() ?? ParenStarComment() ?? DotDot() ?? SingleCharacter() ?? HexNumber() ?? AmpersandIdentifier() ?? DoubleQuotedApostrophe(); } public Token NextToken() { while (_index < _source.Length && Char.IsWhiteSpace(_source[_index])) ++_index; if (_index >= _source.Length) return null; Match match = NextMatch(); if (match == null) throw new LexException("Unrecognized character '" + _source[_index] + "'", Location); string text = _source.Substring(_index, match.Length); Token result = new Token(match.TokenType, Location, text, match.ParsedText); _index += match.Length; return result; } private Match Number() { if (!Char.IsNumber(Peek(0))) return null; int offset = 1; while (Char.IsNumber(Peek(offset))) ++offset; if (Peek(offset) == '.' && Peek(offset + 1) != '.') { ++offset; while (Char.IsNumber(Peek(offset))) ++offset; } if (Peek(offset) == 'e' || Peek(offset) == 'E') { ++offset; if (Peek(offset) == '+' || Peek(offset) == '-') ++offset; while (Char.IsNumber(Peek(offset))) ++offset; } return new Match(TokenType.Number, offset); } private Match ParenStarComment() { if (Peek(0) != '(' || Peek(1) != '*') return null; int offset = 2; while (CanRead(offset) && !(Read(offset) == '*' && Peek(offset + 1) == ')')) ++offset; offset += 2; if (Peek(2) == '$') { string parsedText = _source.Substring(_index + 3, offset - 5).TrimEnd(); return new Match(TokenType.CompilerDirective, offset, parsedText); } else return new Match(TokenType.ParenStarComment, offset); } private char Peek(int offset) { if (CanRead(offset)) return Read(offset); return Char.MaxValue; } private char Read(int offset) { return _source[_index + offset]; } private Match SingleCharacter() { char ch = _source[_index]; switch (ch) { case '(': return new Match(TokenType.OpenParenthesis, 1); case ')': return new Match(TokenType.CloseParenthesis, 1); case '*': return new Match(TokenType.TimesSign, 1); case '+': return new Match(TokenType.PlusSign, 1); case ',': return new Match(TokenType.Comma, 1); case '-': return new Match(TokenType.MinusSign, 1); case '.': return new Match(TokenType.Dot, 1); case '/': return new Match(TokenType.DivideBySign, 1); case ':': return new Match(TokenType.Colon, 1); case ';': return new Match(TokenType.Semicolon, 1); case '@': return new Match(TokenType.AtSign, 1); case '[': return new Match(TokenType.OpenBracket, 1); case ']': return new Match(TokenType.CloseBracket, 1); case '^': return new Match(TokenType.Caret, 1); } return null; } private Match SingleLineComment() { if (Peek(0) != '/' || Peek(1) != '/') return null; int offset = 2; while (CanRead(offset) && Read(offset) != '\r' && Read(offset) != '\n') ++offset; return new Match(TokenType.SingleLineComment, offset); } private Match StringLiteral() { char firstChar = Read(0); if (firstChar != '\'' && firstChar != '#') return null; int offset = 0; while (Peek(offset) == '\'' || Peek(offset) == '#') { if (Peek(offset) == '\'') { ++offset; while (Read(offset) != '\'') ++offset; ++offset; } else { ++offset; if (Read(offset) == '$') ++offset; while (Char.IsLetterOrDigit(Peek(offset))) ++offset; } } return new Match(TokenType.StringLiteral, offset); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using Xunit; public class PathCombineTests { private static readonly char s_separator = Path.DirectorySeparatorChar; [Fact] public static void PathIsNull() { VerifyException<ArgumentNullException>(null); } [Fact] public static void VerifyEmptyPath() { //paths is empty Verify(new String[0]); } [Fact] public static void VerifyPath1Element() { //paths has 1 element Verify(new String[] { "abc" }); } [Fact] public static void VerifyPath2Elements() { //paths has 2 elements Verify(new String[] { "abc", "def" }); } [Fact] public static void VerifyPathManyElements() { //paths has many elements Verify(new String[] { "abc" + s_separator + "def", "def", "ghi", "jkl", "mno" }); } [Fact] public static void PathIsNullWihtoutRootedAfterArgumentNull() { //any path is null without rooted after (ANE) CommonCasesException<ArgumentNullException>(null); } [Fact] public static void ContainsInvalidCharWithoutRootedAfterArgumentNull() { //any path contains invalid character without rooted after (AE) CommonCasesException<ArgumentException>("ab\0cd"); } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void ContainsInvalidCharWithoutRootedAfterArgumentNull_Windows() { //any path contains invalid character without rooted after (AE) CommonCasesException<ArgumentException>("ab\"cd"); CommonCasesException<ArgumentException>("ab\"cd"); CommonCasesException<ArgumentException>("ab<cd"); CommonCasesException<ArgumentException>("ab>cd"); CommonCasesException<ArgumentException>("ab|cd"); CommonCasesException<ArgumentException>("ab\bcd"); CommonCasesException<ArgumentException>("ab\0cd"); CommonCasesException<ArgumentException>("ab\tcd"); } [Fact] public static void ContainsInvalidCharWithRootedAfterArgumentNull() { //any path contains invalid character with rooted after (AE) CommonCasesException<ArgumentException>("ab\0cd", s_separator + "abc"); } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void ContainsInvalidCharWithRootedAfterArgumentNull_Windows() { //any path contains invalid character with rooted after (AE) CommonCasesException<ArgumentException>("ab\"cd", s_separator + "abc"); CommonCasesException<ArgumentException>("ab<cd", s_separator + "abc"); CommonCasesException<ArgumentException>("ab>cd", s_separator + "abc"); CommonCasesException<ArgumentException>("ab|cd", s_separator + "abc"); CommonCasesException<ArgumentException>("ab\bcd", s_separator + "abc"); CommonCasesException<ArgumentException>("ab\tcd", s_separator + "abc"); } [Fact] public static void PathIsRooted() { //any path is rooted (starts with \, \\, A:) CommonCases(s_separator + "abc"); CommonCases(s_separator + s_separator + "abc"); } [Fact] public static void PathIsEmptyCommonCases() { //any path is empty (skipped) CommonCases(""); } [Fact] public static void PathIsEmptyMultipleArguments() { //all paths are empty Verify(new String[] { "" }); Verify(new String[] { "", "" }); Verify(new String[] { "", "", "" }); Verify(new String[] { "", "", "", "" }); Verify(new String[] { "", "", "", "", "" }); } [Fact] public static void PathIsSingleElement() { //any path is single element CommonCases("abc"); CommonCases("abc" + s_separator); } [Fact] public static void PathIsMultipleElements() { //any path is multiple element CommonCases(Path.Combine("abc", Path.Combine("def", "ghi"))); } [Fact] public static void PathElementsAllSeparated() { Verify(new string[] { "abc" + s_separator, "def" + s_separator }); Verify(new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator }); Verify(new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator, "jkl" + s_separator }); Verify(new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator, "jkl" + s_separator, "mno" + s_separator }); } private static void Verify(string[] paths) { String rVal; String expected = String.Empty; if (paths.Length > 0) expected = paths[0]; for (int i = 1; i < paths.Length; i++) { expected = Path.Combine(expected, paths[i]); } //verify passed as array case rVal = Path.Combine(paths); Assert.Equal(expected, rVal); //verify passed as elements case switch (paths.Length) { case 0: rVal = Path.Combine(); break; case 1: rVal = Path.Combine(paths[0]); break; case 2: rVal = Path.Combine(paths[0], paths[1]); break; case 3: rVal = Path.Combine(paths[0], paths[1], paths[2]); break; case 4: rVal = Path.Combine(paths[0], paths[1], paths[2], paths[3]); break; case 5: rVal = Path.Combine(paths[0], paths[1], paths[2], paths[3], paths[4]); break; default: Assert.True(false, String.Format("Test doesn't cover case with {0} items passed seperately, add it.", paths.Length)); break; } Assert.Equal(expected, rVal); } public static void CommonCases(string testing) { Verify(new string[] { testing }); Verify(new string[] { "abc", testing }); Verify(new string[] { testing, "abc" }); Verify(new string[] { "abc", "def", testing }); Verify(new string[] { "abc", testing, "def" }); Verify(new string[] { testing, "abc", "def" }); Verify(new string[] { "abc", "def", "ghi", testing }); Verify(new string[] { "abc", "def", testing, "ghi" }); Verify(new string[] { "abc", testing, "def", "ghi" }); Verify(new string[] { testing, "abc", "def", "ghi" }); Verify(new string[] { "abc", "def", "ghi", "jkl", testing }); Verify(new string[] { "abc", "def", "ghi", testing, "jkl" }); Verify(new string[] { "abc", "def", testing, "ghi", "jkl" }); Verify(new string[] { "abc", testing, "def", "ghi", "jkl" }); Verify(new string[] { testing, "abc", "def", "ghi", "jkl" }); } private static void VerifyException<T>(string[] paths) where T : Exception { Assert.Throws<T>(() => Path.Combine(paths)); //verify passed as elements case if (paths != null) { Assert.InRange(paths.Length, 1, 5); Assert.Throws<T>(() => { switch (paths.Length) { case 0: Path.Combine(); break; case 1: Path.Combine(paths[0]); break; case 2: Path.Combine(paths[0], paths[1]); break; case 3: Path.Combine(paths[0], paths[1], paths[2]); break; case 4: Path.Combine(paths[0], paths[1], paths[2], paths[3]); break; case 5: Path.Combine(paths[0], paths[1], paths[2], paths[3], paths[4]); break; } }); } } private static void CommonCasesException<T>(string testing) where T : Exception { VerifyException<T>(new string[] { testing }); VerifyException<T>(new string[] { "abc", testing }); VerifyException<T>(new string[] { testing, "abc" }); VerifyException<T>(new string[] { "abc", "def", testing }); VerifyException<T>(new string[] { "abc", testing, "def" }); VerifyException<T>(new string[] { testing, "abc", "def" }); VerifyException<T>(new string[] { "abc", "def", "ghi", testing }); VerifyException<T>(new string[] { "abc", "def", testing, "ghi" }); VerifyException<T>(new string[] { "abc", testing, "def", "ghi" }); VerifyException<T>(new string[] { testing, "abc", "def", "ghi" }); VerifyException<T>(new string[] { "abc", "def", "ghi", "jkl", testing }); VerifyException<T>(new string[] { "abc", "def", "ghi", testing, "jkl" }); VerifyException<T>(new string[] { "abc", "def", testing, "ghi", "jkl" }); VerifyException<T>(new string[] { "abc", testing, "def", "ghi", "jkl" }); VerifyException<T>(new string[] { testing, "abc", "def", "ghi", "jkl" }); } private static void CommonCasesException<T>(string testing, string testing2) where T : Exception { VerifyException<T>(new string[] { testing, testing2 }); VerifyException<T>(new string[] { "abc", testing, testing2 }); VerifyException<T>(new string[] { testing, "abc", testing2 }); VerifyException<T>(new string[] { testing, testing2, "def" }); VerifyException<T>(new string[] { "abc", "def", testing, testing2 }); VerifyException<T>(new string[] { "abc", testing, "def", testing2 }); VerifyException<T>(new string[] { "abc", testing, testing2, "ghi" }); VerifyException<T>(new string[] { testing, "abc", "def", testing2 }); VerifyException<T>(new string[] { testing, "abc", testing2, "ghi" }); VerifyException<T>(new string[] { testing, testing2, "def", "ghi" }); VerifyException<T>(new string[] { "abc", "def", "ghi", testing, testing2 }); VerifyException<T>(new string[] { "abc", "def", testing, "ghi", testing2 }); VerifyException<T>(new string[] { "abc", "def", testing, testing2, "jkl" }); VerifyException<T>(new string[] { "abc", testing, "def", "ghi", testing2 }); VerifyException<T>(new string[] { "abc", testing, "def", testing2, "jkl" }); VerifyException<T>(new string[] { "abc", testing, testing2, "ghi", "jkl" }); VerifyException<T>(new string[] { testing, "abc", "def", "ghi", testing2 }); VerifyException<T>(new string[] { testing, "abc", "def", testing2, "jkl" }); VerifyException<T>(new string[] { testing, "abc", testing2, "ghi", "jkl" }); VerifyException<T>(new string[] { testing, testing2, "def", "ghi", "jkl" }); } }
/* Copyright 2019-2021 Sannel Software, L.L.C. 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 Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Sannel.House.Devices.Interfaces; using Sannel.House.Devices.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Sannel.House.Base.Web; using Sannel.House.Base.Models; using System.Net; using System.Diagnostics.CodeAnalysis; namespace Sannel.House.Devices.Controllers { /// <summary> /// Controller dealing with Alternate Id /// </summary> /// <seealso cref="Microsoft.AspNetCore.Mvc.Controller" /> [Route("api/[controller]")] [ApiController] [Authorize] public class AlternateIdController : Controller { private readonly IDeviceService service; private readonly ILogger logger; /// <summary> /// Initializes a new instance of the <see cref="AlternateIdController" /> class. /// </summary> /// <param name="service">The repository.</param> /// <param name="logger">The logger.</param> /// <exception cref="ArgumentNullException"> /// repository /// or /// logger /// </exception> public AlternateIdController(IDeviceService service, ILogger<AlternateIdController> logger) { this.service = service ?? throw new ArgumentNullException(nameof(service)); this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// <summary> /// Gets the specified device identifier. /// </summary> /// <param name="deviceId">The device identifier.</param> /// <returns></returns> [HttpGet("{deviceId}")] [ProducesResponseType(200)] [ProducesResponseType(400)] [ProducesResponseType(404)] [Authorize(Policy = "ReadDevice")] public async Task<ActionResult<ResponseModel<IEnumerable<AlternateDeviceId>>>> Get(int deviceId) { if(deviceId < 0) { logger.LogError("Invalid device id({0}) passed in.", deviceId); return BadRequest(new ErrorResponseModel("Invalid DeviceId", "deviceId", "Device Id must be greater then or equal to 0")); } var list = await service.GetAlternateIdsForDeviceAsync(deviceId); if(list == null || !list.Any()) { logger.LogDebug("Device with Id {0} not found", deviceId); return NotFound(new ErrorResponseModel(HttpStatusCode.NotFound, "Device Not Found", "device", "Device not found")); } return Ok(new ResponseModel<IEnumerable<AlternateDeviceId>>("Alternate Ids", list)); } /// <summary> /// Posts the specified mac address. /// </summary> /// <param name="macAddress">The mac address.</param> /// <param name="deviceId">The device identifier.</param> /// <returns></returns> [HttpPost("mac/{macAddress}/{deviceId}")] [ProducesResponseType(200)] [ProducesResponseType(400)] [ProducesResponseType(404)] [Authorize(Policy = "WriteDevice")] public async Task<ActionResult<ResponseModel<Device>>> Post(long macAddress, int deviceId) { if(macAddress < 0) { logger.LogError("Invalid macAddress passed {macAddress}", macAddress); return BadRequest(new ErrorResponseModel("Invalid Mac Address", "macAddress", "Invalid MacAddress it must be greater then 0")); } if(deviceId <= 0) { logger.LogError("Invalid device id({deviceId}) passed in.", deviceId); return BadRequest(new ErrorResponseModel("Invalid Device Id", "deviceId", "Device Id must be greater then 0")); } try { var device = await service.AddAlternateMacAddressAsync(deviceId, macAddress); if(device == null) { logger.LogDebug("No device found with id {deviceId}", deviceId); return NotFound(new ErrorResponseModel(HttpStatusCode.NotFound, "Device Not Found", "notFound", "No device found with that id")); } return Ok(new ResponseModel<Device>("Device", device)); } catch(AlternateDeviceIdException aIdException) { logger.LogError(aIdException, "Alternate Device Id Exception"); return BadRequest(new ErrorResponseModel("Mac Address Already Connected", "macAddress", "That mac address is already connected to a device")); } } /// <summary> /// Posts the specified UUID. /// </summary> /// <param name="uuid">The UUID.</param> /// <param name="deviceId">The device identifier.</param> /// <returns></returns> [HttpPost("uuid/{uuid}/{deviceId}")] [ProducesResponseType(200)] [ProducesResponseType(400)] [ProducesResponseType(404)] [Authorize(Policy = "WriteDevice")] public async Task<ActionResult<ResponseModel<Device>>> Post(Guid uuid, int deviceId) { if(uuid == Guid.Empty) { logger.LogError("Empty Guid passed in for Uuid"); return BadRequest(new ErrorResponseModel("Guid is Empty","uuid", "Uuid must be a valid Guid and not Guid.Empty")); } if(deviceId < 0) { logger.LogError("Invalid device id({deviceId}) passed in.", deviceId); return BadRequest(new ErrorResponseModel("Invalid Device Id", "deviceId", "Device Id must be greater then or equal to 0")); } try { var device = await service.AddAlternateUuidAsync(deviceId, uuid); if(device == null) { logger.LogDebug("No device found with id {deviceId}", deviceId); return NotFound(new ErrorResponseModel(HttpStatusCode.NotFound, "Device Not Found", "notFound", "No device found with that id")); } return Ok(new ResponseModel<Device>("Device", device)); } catch(AlternateDeviceIdException aIdException) { logger.LogError(aIdException, "Alternate Device Id Exception"); return BadRequest(new ErrorResponseModel("Uuid Already Connected", "uuid", "That Uuid is already connected to a device")); } } /// <summary> /// Posts the specified manufacture. /// </summary> /// <param name="manufacture">The manufacture.</param> /// <param name="manufactureId">The manufacture identifier.</param> /// <param name="deviceId">The device identifier.</param> /// <returns></returns> [HttpPost("manufactureid/{manufacture}/{manufactureId}/{deviceId}")] [ProducesResponseType(200)] [ProducesResponseType(400)] [ProducesResponseType(404)] [Authorize(Policy = "WriteDevice")] public async Task<ActionResult<ResponseModel<Device>>> Post([NotNull]string manufacture, [NotNull]string manufactureId, int deviceId) { if(string.IsNullOrWhiteSpace(manufacture)) { logger.LogError("Null or Empty Manufacture"); return BadRequest(new ErrorResponseModel("Manufacture is Empty","manufacture", "manufacture must not be null or whitespace")); } if(string.IsNullOrWhiteSpace(manufactureId)) { logger.LogError("Null or Empty ManufactureId"); return BadRequest(new ErrorResponseModel("ManufactureID is Empty","manufactureId", "manufactureId must not be null or whitespace")); } if(deviceId < 0) { logger.LogError("Invalid device id({deviceId}) passed in.", deviceId); return BadRequest(new ErrorResponseModel("Invalid Device Id", "deviceId", "Device Id must be greater then or equal to 0")); } try { var device = await service.AddAlternateManufactureIdAsync(deviceId, manufacture, manufactureId); if(device == null) { logger.LogDebug("No device found with id {deviceId}", deviceId); return NotFound(new ErrorResponseModel(HttpStatusCode.NotFound, "Device Not Found", "notFound", "No device found with that id")); } return Ok(new ResponseModel<Device>("Device", device)); } catch(AlternateDeviceIdException aIdException) { logger.LogError(aIdException, "Alternate Device Id Exception"); return BadRequest(new ErrorResponseModel("Manufacture and ManufactureId Already Connected", "manufactureId", "That Manufacture and ManufactureId is already connected to a device")); } } /// <summary> /// Deletes the specified mac address. /// </summary> /// <param name="macAddress">The mac address.</param> /// <returns></returns> [HttpDelete("mac/{macAddress}")] [ProducesResponseType(200)] [ProducesResponseType(400)] [ProducesResponseType(404)] [Authorize(Policy = "WriteDevice")] public async Task<ActionResult<ResponseModel<Device>>> Delete(long macAddress) { if(macAddress <= 0) { logger.LogError("Invalid macAddress passed {macAddress}", macAddress); return BadRequest(new ErrorResponseModel("Invalid Mac Address","macAddress", "Invalid MacAddress it must be greater then or equal to 0")); } var device = await service.RemoveAlternateMacAddressAsync(macAddress); if(device == null) { logger.LogDebug("No Mac Address found with id {macAddress}", macAddress); return NotFound(new ErrorResponseModel(HttpStatusCode.NotFound,"Mac Address Not Found","macAddress", "Mac Address not found")); } return Ok(new ResponseModel<Device>("Device",device)); } /// <summary> /// Deletes the specified UUID. /// </summary> /// <param name="uuid">The UUID.</param> /// <returns></returns> [HttpDelete("uuid/{uuid}")] [ProducesResponseType(200)] [ProducesResponseType(400)] [ProducesResponseType(404)] [Authorize(Policy = "WriteDevice")] public async Task<ActionResult<ResponseModel<Device>>> Delete(Guid uuid) { if(uuid == Guid.Empty) { logger.LogError("Empty Guid passed in for Uuid"); return BadRequest(new ErrorResponseModel("Uuid is Empty","uuid", "Uuid must be a valid Guid and not Guid.Empty")); } var device = await service.RemoveAlternateUuidAsync(uuid); if(device == null) { logger.LogDebug("Uuid not found {uuid}", uuid); return NotFound(new ErrorResponseModel(HttpStatusCode.NotFound,"Uuid Not Found","uuid", "Uuid not found")); } return Ok(new ResponseModel<Device>("Device", device)); } /// <summary> /// Deletes the specified manufacture. /// </summary> /// <param name="manufacture">The manufacture.</param> /// <param name="manufactureId">The manufacture identifier.</param> /// <returns></returns> [HttpDelete("manufactureid/{manufacture}/{manufactureId}")] [ProducesResponseType(200)] [ProducesResponseType(400)] [ProducesResponseType(404)] [Authorize(Policy = "WriteDevice")] public async Task<ActionResult<ResponseModel<Device>>> Delete([NotNull]string manufacture, [NotNull]string manufactureId) { if(string.IsNullOrWhiteSpace(manufacture)) { logger.LogError("Null or Empty Manufacture"); return BadRequest(new ErrorResponseModel("Manufacture is Empty","manufacture", "Manufacture must not be null or whitespace")); } if(string.IsNullOrWhiteSpace(manufactureId)) { logger.LogError("Null or Empty ManufactureId"); return BadRequest(new ErrorResponseModel("ManufactureID is Empty","manufactureId", "ManufactureId must not be null or whitespace")); } var device = await service.RemoveAlternateManufactureIdAsync(manufacture, manufactureId); if(device == null) { logger.LogDebug("ManufactureId not found {manufacture}/{manufactureId}", manufacture, manufactureId); return NotFound(new ErrorResponseModel(HttpStatusCode.NotFound,"ManufactureId Not Found","manufactureid", "Manufacture/ManufactureId not found")); } return Ok(new ResponseModel<Device>("Device", device)); } } }
using System; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using Fairweather.Service; using Standardization; using Cell = System.Windows.Forms.DataGridViewCell; using ColumnType = Common.Our_DGV_Column_Type; namespace Common.Controls { /// <summary> /// The logic in this file handles the actual opening and closing of /// the grid cells - it is not concerned with the way a cells is /// chosen for opening. /// </summary> partial class Advanced_Grid_View { public virtual void Open_Cell(DataGridViewCell cell) { if (cell != null) Open_Cell(cell.ColumnIndex, cell.RowIndex); } /// Sets the active cell to the one with the given coordinates /// Uses FinishField and ShowControl, disables OnActiveControlLeave /// Raises Active_Cell_Changed public virtual void Open_Cell(int col, int row) { if (row == -1) {// 29th August, 15 December Close_Cell(); return; } if (bf_switch_cell) return; bf_switch_cell = true; bf_active_control_leave = true; try { if (!Verify_Cell_OK_For_Selecting(ref col, ref row)) return; var selected = this[col, row]; last_Active_Cell = selected; Close_Cell(); //17th June // 12 Oct - velko // 06 Nov // 08 Dec //CurrentCell = this[col, row]; var ac = Active_Cell; if (ac != null) ac.Selected = false; bool read_only; Control ctrl; Get_Active_Control(col, row, out read_only, out ctrl); (read_only || (ctrl != null)).tiff(); Active_Cell = selected; if (read_only) { // Make_Readonly_Cell(selected); selected.Selected = row == this.Empty_Row_Index ? false : true; } else { selected.Selected = false; Active_Control = ctrl; Show_Control(); } On_Active_Cell_Changed(EventArgs.Empty); base.OnCellEnter(new DataGridViewCellEventArgs(col, row)); } finally { bf_switch_cell = false; bf_active_control_leave = false; } } public virtual void Show_Control() { var cell = Active_Cell; var ctrl = m_active_control; if (cell == null || ctrl == null) return; int col = cell.ColumnIndex; int row = cell.RowIndex; Prepare_Control_For_Display(col, row); //if (!Is_Visible(row)) // this.FirstDisplayedScrollingRowIndex = row; bf_enter = true; try { ctrl.Visible = true; ctrl.BringToFront(); ctrl.Select_Focus(); ctrl.Refresh(); } finally { bf_enter = false; } } protected virtual void Prepare_Control_For_Display(int col, int row) { var p1 = this.Get_Cell_Coords(col, row, true); Set_Control_Value(); Set_Active_Control_Size_Location(); if (m_active_control is TextBox) ((TextBox)m_active_control).SelectAll(); if (m_active_control is Numeric_Box) ((Numeric_Box)m_active_control).Has_User_Typed_Text = false; // m_active_control.BringToFront(); } public void Set_Active_Control_Size_Location() { var ctrl = m_active_control; if (ctrl == null) return; int width, height; Point pt; Get_Active_Control_Size_Location(out width, out height, out pt); ctrl.Size = new Size(width, height); ctrl.Location = pt; } /// <summary> /// Does not throw if _active_control == null /// Throws on _active_cell == null /// Override for custom positioning. /// </summary> protected virtual void Get_Active_Control_Size_Location(out int width, out int height, out Point pt) { H.assign(out width, out height, out pt); var ctrl = m_active_control; if (ctrl == null) return; var cell = Active_Cell; if (cell == null) return; int col = Active_Cell.ColumnIndex; int row = Active_Cell.RowIndex; width = Active_Cell.Size.Width; height = cst_row_height; pt = this.Get_Cell_Coords(col, row, false, true).Value; // former crap... //switch (m_column_types[col]) { // case ColumnType.NumericBox: { // m_active_control.Size = new Size(Active_Cell.Size.Width - 1, // m_active_control.Size.Height); // break; // } // case ColumnType.ComboBox: { // m_active_control.Size = new Size(Active_Cell.Size.Width, // m_active_control.Size.Height); // break; // } // case ColumnType.Normal: { // m_active_control.Size = new Size(Active_Cell.Size.Width - 7, // m_active_control.Size.Height); // break; // } // default: // return; //} if (ctrl is TextBox) { // cell_w - 7, ctrl_h width -= 6; height -= 5; (ctrl as TextBox).SelectAll(); // pt = pt.Translate(2, 4); pt = pt.Translate(2, 3); } else if (ctrl is Advanced_Combo_Box) { height -= 1; } else if (ctrl is Numeric_Box) { width -= 1; height -= 1; // pt = pt.Translate(-1, 0); } else if (ctrl is Our_Date_Time) { height += 1; pt = pt.Translate(-1, 0); } else { width -= 1; height = ctrl.Height; } } /* Helpers */ public virtual bool Is_Readonly(int col, int row) { var type = m_column_types[col]; return type == ColumnType.Readonly_Decimal; } protected virtual void Get_Active_Control(int col, int row, out bool read_only, out Control ctrl) { read_only = false; ctrl = null; if (Is_Readonly(col, row)) { read_only = true; // 2nd June return; } if (m_ctrls.TryGetValue(col, out ctrl)) return; } /// <summary> /// Allows you to prevent a cell from being selected /// or to choose another cell /// </summary> protected virtual bool Verify_Cell_OK_For_Selecting(ref int col, ref int row) { return true; } // **************************** public void Commit_Value(bool close, bool force_update) { if (b_commit_value) return; b_commit_value = true; var tmp_active_cell = this.Active_Cell; var tmp_active_control = this.Active_Control; try { if (tmp_active_cell == null) return; var row = tmp_active_cell.RowIndex; var col = tmp_active_cell.ColumnIndex; if (row < 0) return; if (Is_Readonly(col, row)) { if (close) { this.Focus(); this.CurrentCell = null; } return; } if (tmp_active_control == null) return; if (row < 0) { if (tmp_active_cell.DataGridView != null) return; } if (close) { bf_active_control_leave = true; bf_main_column_value_entered = true; bf_enter = true; bf_leave = true; try { // This is to make sure the form does not // automatically switch to the next control // when the dummy box is hidden if (this.ContainsFocus) this.Focus(); // END tmp_active_control.Visible = false; this.Invalidate(tmp_active_control.Bounds); this.Force_Handle(); BeginInvoke((MethodInvoker)(() => { this.Update(); })); } finally { bf_leave = false; bf_enter = false; bf_active_control_leave = false; bf_main_column_value_entered = false; } } col = tmp_active_cell.ColumnIndex; row = tmp_active_cell.RowIndex; decimal dbl_value; string str_value; bool is_dbl; bool change; Get_Control_Value(tmp_active_cell, tmp_active_control, col, close, out dbl_value, out str_value, out is_dbl, out change); if (close) { bi_cell_state_changed = true; try { tmp_active_cell.Selected = false; } finally { bi_cell_state_changed = false; } } change |= force_update; bool allowed = Test_Value(col, row, str_value); change &= allowed; change &= row >= 0; var prev_value = tmp_active_cell.Value ?? ""; // <-- if (change) { bool handled = Handle_Set_Value_Virt(col, row, is_dbl, str_value, dbl_value, prev_value); if (!handled) { bool temp = bf_switch_cell; bf_switch_cell = true; try { var value = is_dbl ? dbl_value : (object)str_value; this[col, row].Value = value; } finally { bf_switch_cell = temp; } } } if (close) { // **************************** // 15/12/2009 - This change was prompted by // a glitch in the scrolling behavior, where // if the user scrolled while a readonly cell // was selected, the cell would lose focus // and the last active normal cell would be selected // It is nevertheless proper. Active_Cell = null; tmp_active_control.Hide(); Active_Control = null; // **************************** tmp_active_control.ResetText(); } } finally { b_commit_value = false; } } public virtual void Close_Cell() { Commit_Value(true, false); } /* Helpers */ protected virtual void Set_Control_Value() { var cell = Active_Cell; Control ctrl = m_active_control; if (ctrl == null || cell == null) return; if (ctrl is Numeric_Box) { var nb = ctrl as Numeric_Box; nb.Text = cell.FormattedValue.ToString(); } else if (ctrl is Our_Combo_Box) { var cb = (ctrl as Our_Combo_Box); cb.Text = (string)(cell.Value ?? ""); cb.Value = (string)(cell.Value ?? ""); } else if (ctrl is TextBox) { var tb = (ctrl as TextBox); ctrl.Text = (string)(cell.Value ?? ""); } else if (ctrl is ComboBox) { var cb = ctrl as ComboBox; int ix = cb.Items.IndexOf(cell.Value.StringOrDefault()); cb.SelectedIndex = ix; if (cb.SelectedIndex == -1) cb.SelectedIndex = 0; } else if (ctrl is Our_Date_Time) { var dt = ctrl as Our_Date_Time; var text = cell.Value.StringOrDefault(); if (text.IsNullOrEmpty()) dt.Value = DateTime.Today; else dt.Value = DateTime.Parse(text); } else { ctrl.Text = cell.Value.StringOrDefault(); } } protected virtual void Get_Control_Value(DataGridViewCell tmp_active_cell, Control tmp_active_control, int col, bool close, out decimal dbl_value, out string str_value, out bool is_dbl, out bool change) { H.assign(out dbl_value, out str_value, out is_dbl, out change); change = true; var type = m_column_types[col]; if (type == ColumnType.AdvancedComboBox) { is_dbl = false; var cb = (Our_Combo_Box)tmp_active_control; str_value = cb.Value; change = (!str_value.IsNullOrEmpty()); if (change) change &= (tmp_active_cell == null || !str_value.Equals(tmp_active_cell.Value)); if (close) { // Closing the shortlist might trigger an event bf_enter = true; try { cb.Clear(); cb.Refresh(); } finally { bf_enter = false; } } } else if (type == ColumnType.NumericBox) { var nb = (Numeric_Box)tmp_active_control; dbl_value = A.DecimalOrZero(nb.Text, m_precisions[col]); is_dbl = true; change &= nb.Has_User_Typed_Text; if (close) { nb.Has_User_Typed_Text = false; nb.Clear(); } } else if (tmp_active_control is Our_Date_Time) { is_dbl = false; str_value = (tmp_active_control as Our_Date_Time).Value.ToString(true); if (close) tmp_active_control.Text = ""; } else { is_dbl = false; str_value = tmp_active_control.Text; if (close) tmp_active_control.Text = ""; } } protected virtual bool Handle_Set_Value_Virt(int col, int row, bool is_dec, string str_value, decimal dec_value, object prev_value) { return false; } protected virtual bool Test_Value(int col, int row, string str_value) { return true; } // **************************** } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Collections.Generic; using System.Runtime.InteropServices; using LifeTimeFX; interface PinnedObject { void CleanUp(); bool IsPinned(); } namespace GCSimulator { class RandomLifeTimeStrategy : LifeTimeStrategy { private int counter = 0; private int mediumLifeTime = 30; private int shortLifeTime = 3; private int mediumDataCount = 1000000; private int shortDataCount = 5000; private Random rand = new Random(123456); public RandomLifeTimeStrategy(int mediumlt, int shortlt, int mdc, int sdc) { mediumLifeTime = mediumlt; shortLifeTime = shortlt; mediumDataCount = mdc; shortDataCount = sdc; } public int MediumLifeTime { set { mediumLifeTime = value; } } public int ShortLifeTime { set { shortLifeTime = value; } } public int NextObject(LifeTimeENUM lifeTime) { switch (lifeTime) { case LifeTimeENUM.Short: return rand.Next() % shortDataCount; case LifeTimeENUM.Medium: return (rand.Next() % mediumDataCount) + shortDataCount; case LifeTimeENUM.Long: return 0; } return 0; } public bool ShouldDie(LifeTime o, int index) { counter++; LifeTimeENUM lifeTime = o.LifeTime; switch (lifeTime) { case LifeTimeENUM.Short: if (counter % shortLifeTime == 0) return true; break; case LifeTimeENUM.Medium: if (counter % mediumLifeTime == 0) return true; break; case LifeTimeENUM.Long: return false; } return false; } } /// <summary> /// we might want to implement a different strategy that decide the life time of the object based on the time /// elapsed since the last object access. /// /// </summary> class TimeBasedLifeTimeStrategy : LifeTimeStrategy { private int lastMediumTickCount = Environment.TickCount; private int lastShortTickCount = Environment.TickCount; private int lastMediumIndex = 0; private int lastShortIndex = 0; public int NextObject(LifeTimeENUM lifeTime) { switch (lifeTime) { case LifeTimeENUM.Short: return lastShortIndex; case LifeTimeENUM.Medium: return lastMediumIndex; case LifeTimeENUM.Long: return 0; } return 0; } public bool ShouldDie(LifeTime o, int index) { LifeTimeENUM lifeTime = o.LifeTime; // short objects will live for 20 seconds, long objects will live for more. switch (lifeTime) { case LifeTimeENUM.Short: if (Environment.TickCount - lastShortTickCount > 1) // this is in accureat enumber, since // we will be finsh iterating throuh the short life time object in less than 1 ms , so we need // to switch either to QueryPeroformanceCounter, or to block the loop for some time through // Thread.Sleep, the other solution is to increase the number of objects a lot. { lastShortTickCount = Environment.TickCount; lastShortIndex = index; return true; } break; case LifeTimeENUM.Medium: if (Environment.TickCount - lastMediumTickCount > 20) { lastMediumTickCount = Environment.TickCount; lastMediumIndex = index; return true; } break; case LifeTimeENUM.Long: break; } return false; } } class ObjectWrapper : LifeTime, PinnedObject { private bool pinned; private bool weakReferenced; private GCHandle gcHandle; private LifeTimeENUM lifeTime; private WeakReference weakRef; private byte[] data; private int dataSize; public int DataSize { set { dataSize = value; data = new byte[dataSize]; if (pinned) { gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned); } if (weakReferenced) { weakRef = new WeakReference(data); } } } public LifeTimeENUM LifeTime { get { return lifeTime; } set { this.lifeTime = value; } } public bool IsPinned() { return pinned; } public bool IsWeak() { return weakReferenced; } public void CleanUp() { if (pinned) { gcHandle.Free(); } } public ObjectWrapper(bool runFinalizer, bool pinned, bool weakReferenced) { this.pinned = pinned; this.weakReferenced = weakReferenced; if (!runFinalizer) { GC.SuppressFinalize(this); } } ~ObjectWrapper() { // DO SOMETHING BAD IN FINALIZER data = new byte[dataSize]; } } class ClientSimulator { [ThreadStatic] private static ObjectLifeTimeManager lifeTimeManager; private static int meanAllocSize = 17; private static int mediumLifeTime = 30; private static int shortLifeTime = 3; private static int mediumDataSize = meanAllocSize; private static int shortDataSize = meanAllocSize; private static int mediumDataCount = 1000000; private static int shortDataCount = 5000; private static int countIters = 500; private static float percentPinned = 0.02F; private static float percentWeak = 0.0F; private static int numThreads = 1; private static bool runFinalizer = false; private static string strategy = "Random"; private static bool noTimer = false; private static string objectGraph = "List"; private static List<Thread> threadList = new List<Thread>(); public static void Main(string[] args) { bool shouldContinue = ParseArgs(args); if (!shouldContinue) { return; } int timer = 0; // Run the test. for (int i = 0; i < numThreads; ++i) { Thread thread = new Thread(RunTest); threadList.Add(thread); thread.Start(); } foreach (Thread t in threadList) { t.Join(); } } public static void RunTest(object threadInfoObj) { // Allocate the objects. lifeTimeManager = new ObjectLifeTimeManager(); LifeTimeStrategy ltStrategy; int threadMediumLifeTime = mediumLifeTime; int threadShortLifeTime = shortLifeTime; int threadMediumDataSize = mediumDataSize; int threadShortDataSize = shortDataSize; int threadMediumDataCount = mediumDataCount; int threadShortDataCount = shortDataCount; float threadPercentPinned = percentPinned; float threadPercentWeak = percentWeak; bool threadRunFinalizer = runFinalizer; string threadStrategy = strategy; string threadObjectGraph = objectGraph; if (threadObjectGraph.ToLower() == "tree") { lifeTimeManager.SetObjectContainer(new BinaryTreeObjectContainer<LifeTime>()); } else { lifeTimeManager.SetObjectContainer(new ArrayObjectContainer<LifeTime>()); } lifeTimeManager.Init(threadShortDataCount + threadMediumDataCount); if (threadStrategy.ToLower()=="random") { ltStrategy = new RandomLifeTimeStrategy(threadMediumLifeTime, threadShortLifeTime, threadMediumDataCount, threadShortDataCount); } else { // may be we need to specify the elapsed time. ltStrategy = new TimeBasedLifeTimeStrategy(); } lifeTimeManager.LifeTimeStrategy = ltStrategy; lifeTimeManager.objectDied += new ObjectDiedEventHandler(objectDied); for (int i=0; i < threadShortDataCount + threadMediumDataCount; ++i) { bool pinned = false; if (threadPercentPinned!=0) { pinned = (i % ((int)(1/threadPercentPinned))==0); } bool weak = false; if (threadPercentWeak!=0) { weak = (i % ((int)(1/threadPercentWeak))==0); } ObjectWrapper oWrapper = new ObjectWrapper(threadRunFinalizer, pinned, weak); if (i < threadShortDataCount) { oWrapper.DataSize = threadShortDataSize; oWrapper.LifeTime = LifeTimeENUM.Short; } else { oWrapper.DataSize = threadMediumDataSize; oWrapper.LifeTime = LifeTimeENUM.Medium; } lifeTimeManager.AddObject(oWrapper, i); } for (int i = 0; i < countIters; ++i) { // Run the test. lifeTimeManager.Run(); } } private static void objectDied(LifeTime lifeTime, int index) { // put a new fresh object instead; LifeTimeENUM lifeTimeEnum; lifeTimeEnum = lifeTime.LifeTime; ObjectWrapper oWrapper = lifeTime as ObjectWrapper; bool weakReferenced = oWrapper.IsWeak(); bool pinned = oWrapper.IsPinned(); if (pinned) { oWrapper.CleanUp(); } oWrapper = new ObjectWrapper(runFinalizer, pinned, weakReferenced); oWrapper.LifeTime = lifeTimeEnum; oWrapper.DataSize = lifeTime.LifeTime == LifeTimeENUM.Short ? shortDataSize : mediumDataSize; lifeTimeManager.AddObject(oWrapper, index); } /// <summary> /// Parse the arguments, no error checking is done yet. /// TODO: Add more error checking. /// /// Populate variables with defaults, then overwrite them with config settings. Finally overwrite them with command line parameters /// </summary> public static bool ParseArgs(string[] args) { for (int i = 0; i < args.Length; ++i) { string currentArg = args[i]; string currentArgValue; if (currentArg.StartsWith("-") || currentArg.StartsWith("/")) { currentArg = currentArg.Substring(1); } else { continue; } if (currentArg.StartsWith("?")) { Usage(); return false; } if (currentArg.StartsWith("iter") || currentArg.Equals("i")) // number of iterations { currentArgValue = args[++i]; countIters = Int32.Parse(currentArgValue); } if (currentArg.StartsWith("datasize") || currentArg.Equals("dz")) { currentArgValue = args[++i]; mediumDataSize = Int32.Parse(currentArgValue); } if (currentArg.StartsWith("sdatasize") || currentArg.Equals("sdz")) { currentArgValue = args[++i]; shortDataSize = Int32.Parse(currentArgValue); } if (currentArg.StartsWith("datacount") || currentArg.Equals("dc")) { currentArgValue = args[++i]; mediumDataCount = Int32.Parse(currentArgValue); } if (currentArg.StartsWith("sdatacount") || currentArg.Equals("sdc")) { currentArgValue = args[++i]; shortDataCount = Int32.Parse(currentArgValue); } if (currentArg.StartsWith("lifetime") || currentArg.Equals("lt")) { currentArgValue = args[++i]; shortLifeTime = Int32.Parse(currentArgValue); mediumLifeTime = shortLifeTime * 10; } if (currentArg.StartsWith("threads") || currentArg.Equals("t")) { currentArgValue = args[++i]; numThreads = Int32.Parse(currentArgValue); } if (currentArg.StartsWith("fin") || currentArg.Equals("f")) { runFinalizer = true; } if (currentArg.StartsWith("datapinned") || currentArg.StartsWith("dp")) // percentage data pinned { currentArgValue = args[++i]; percentPinned = float.Parse(currentArgValue); } if (currentArg.StartsWith("strategy")) //strategy that if the object died or not { currentArgValue = args[++i]; strategy = currentArgValue; } if (currentArg.StartsWith("notimer")) { noTimer = true; } if (currentArg.StartsWith("dataweak") || currentArg.StartsWith("dw") ) { currentArgValue = args[++i]; percentWeak = float.Parse(currentArgValue); } if (currentArg.StartsWith("objectgraph") || currentArg.StartsWith("og") ) { currentArgValue = args[++i]; objectGraph = currentArgValue; } } return true; } public static void Usage() { Console.WriteLine("GCSimulator [-?] [-i <num Iterations>] [-dz <data size in bytes>] [-lt <life time>] [-t <num threads>] [-f] [-dp <percent data pinned>]"); Console.WriteLine("Options"); Console.WriteLine("-? Display the usage and exit"); Console.WriteLine("-i [-iter] <num iterations> : specify number of iterations for the test, default is " + countIters); Console.WriteLine("-dz [-datasize] <data size> : specify the data size in bytes, default is " + mediumDataSize); Console.WriteLine("-sdz [sdatasize] <data size> : specify the short lived data size in bytes, default is " + shortDataSize); Console.WriteLine("-dc [datacount] <data count> : specify the medium lived data count , default is " + mediumDataCount); Console.WriteLine("-sdc [sdatacount] <data count> : specify the short lived data count, default is " + shortDataCount); Console.WriteLine("-lt [-lifetime] <number> : specify the life time of the objects, default is " + shortLifeTime); Console.WriteLine("-t [-threads] <number of threads> : specifiy number of threads , default is " + numThreads); Console.WriteLine("-f [-fin] : specify whether to do allocation in finalizer or not, default is no"); Console.WriteLine("-dp [-datapinned] <percent of data pinned> : specify the percentage of data that we want to pin, default is " + percentPinned); Console.WriteLine("-dw [-dataweak] <percent of data weak referenced> : specify the percentage of data that we want to weak reference, default is " + percentWeak); Console.WriteLine("-strategy < indicate the strategy for deciding when the objects should die, right now we support only Random and Time strategy, default is Random"); Console.WriteLine("-og [-objectgraph] <List|Tree> : specify whether to use a List- or Tree-based object graph, default is " + objectGraph); Console.WriteLine("-notimer < indicate that we do not want to run the performance timer and output any results , default is no"); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Moq; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CommentSelection { public class CommentUncommentSelectionCommandHandlerTests { private class MockCommentUncommentService : AbstractCommentUncommentService { private readonly bool _supportBlockComments; public MockCommentUncommentService(bool supportBlockComments) { _supportBlockComments = supportBlockComments; } public override string SingleLineCommentString { get { return "//"; } } public override bool SupportsBlockComment { get { return _supportBlockComments; } } public override string BlockCommentStartString { get { if (!_supportBlockComments) { throw new NotSupportedException(); } return "/*"; } } public override string BlockCommentEndString { get { if (!_supportBlockComments) { throw new NotSupportedException(); } return "*/"; } } } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Create() { Assert.NotNull( new MockCommentUncommentService( supportBlockComments: true)); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_EmptyLine() { var code = @"|start||end|"; CommentSelection(code, Enumerable.Empty<TextChange>(), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_NoSelectionAtEndOfLine() { var code = @"Some text on a line|start||end|"; CommentSelection(code, new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_Whitespace() { var code = @" |start| |end| "; CommentSelection(code, Enumerable.Empty<TextChange>(), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_SingleLineBlockWithBlockSelection() { var code = @"this is |start| some |end| text"; var expectedChanges = new[] { new TextChange(new TextSpan(8, 0), "/*"), new TextChange(new TextSpan(14, 0), "*/"), }; CommentSelection(code, expectedChanges, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_MultilineWithBlockSelection() { var code = @"this is |start| some text that is |end| on multiple lines"; var expectedChanges = new[] { new TextChange(new TextSpan(0, 0), "//"), new TextChange(new TextSpan(16, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_SingleLineBlockWithNoBlockSelection() { var code = @"this is |start| some |end| text"; CommentSelection(code, new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, supportBlockComments: false); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(563915)] [WorkItem(530300)] public void Comment_MultilineIndented() { var code = @" class Foo { |start|void M() { }|end| } "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection( code, expectedChanges, supportBlockComments: false, expectedSelectedSpans: new[] { Span.FromBounds(16, 48) }); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(527190)] [WorkItem(563924)] public void Comment_ApplyTwice() { var code = @"|start|class C { void M() { } }|end| "; var textView = EditorFactory.CreateView(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, code); var selectedSpans = SetupSelection(textView); var expectedChanges = new[] { new TextChange(new TextSpan(0, 0), "//"), new TextChange(new TextSpan(9, 0), "//"), new TextChange(new TextSpan(12, 0), "//"), new TextChange(new TextSpan(30, 0), "//"), }; CommentSelection( textView, expectedChanges, supportBlockComments: false, expectedSelectedSpans: new[] { new Span(0, 39) }); expectedChanges = new[] { new TextChange(new TextSpan(0, 0), "//"), new TextChange(new TextSpan(11, 0), "//"), new TextChange(new TextSpan(16, 0), "//"), new TextChange(new TextSpan(36, 0), "//"), }; CommentSelection( textView, expectedChanges, supportBlockComments: false, expectedSelectedSpans: new[] { new Span(0, 47) }); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_SelectionEndsAtColumnZero() { var code = @" class Foo { |start| void M() { } |end|} "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: false); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_BoxSelectionAtStartOfLines() { var code = @" class Foo { |start||end| void M() |start||end| { |start||end| } } "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_BoxSelectionIndentedAtStart() { var code = @" class Foo { |start||end|void M() |start||end|{ |start||end|} } "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_BoxSelectionBlock() { var code = @" class Foo { |start|v|end|oid M() |start|{|end| |start|o|end|ther |start|}|end| } "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "/*"), new TextChange(new TextSpan(21, 0), "*/"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "/*"), new TextChange(new TextSpan(42, 0), "*/"), new TextChange(new TextSpan(52, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_BoxSelectionBlockWithoutSupport() { var code = @" class Foo { |start|v|end|oid M() |start|{|end| |start|}|end| } "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: false); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Uncomment_NoSelection() { var code = @"//Foo|start||end|Bar"; UncommentSelection(code, new[] { new TextChange(new TextSpan(0, 2), string.Empty) }, Span.FromBounds(0, 6), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Uncomment_MatchesBlockComment() { var code = @"Before |start|/* Some Commented Text */|end| after"; var expectedChanges = new[] { new TextChange(new TextSpan(7, 2), string.Empty), new TextChange(new TextSpan(30, 2), string.Empty), }; UncommentSelection(code, expectedChanges, Span.FromBounds(7, 28), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Uncomment_InWhitespaceOutsideBlockComment() { var code = @"Before |start| /* Some Commented Text */ |end| after"; var expectedChanges = new[] { new TextChange(new TextSpan(11, 2), string.Empty), new TextChange(new TextSpan(34, 2), string.Empty), }; UncommentSelection(code, expectedChanges, Span.FromBounds(11, 32), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Uncomment_IndentedSingleLineCommentsAndUncommentedLines() { var code = @" class C { |start| //void M() //{ //if (true) //{ SomethingNotCommented(); //} //} |end|}"; var expectedChanges = new[] { new TextChange(new TextSpan(18, 2), string.Empty), new TextChange(new TextSpan(34, 2), string.Empty), new TextChange(new TextSpan(47, 2), string.Empty), new TextChange(new TextSpan(68, 2), string.Empty), new TextChange(new TextSpan(119, 2), string.Empty), new TextChange(new TextSpan(128, 2), string.Empty), }; UncommentSelection(code, expectedChanges, Span.FromBounds(14, 119), supportBlockComments: true); } [Fact(Skip = "563927"), Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(563927)] public void Uncomment_BoxSelection() { var code = @" class Foo { |start|/*v*/|end|oid M() |start|//{ |end| |start|/*o*/|end|ther |start|//} |end| }"; var expectedChanges = new[] { new TextChange(new TextSpan(20, 2), string.Empty), new TextChange(new TextSpan(23, 2), string.Empty), new TextChange(new TextSpan(38, 2), string.Empty), new TextChange(new TextSpan(49, 2), string.Empty), new TextChange(new TextSpan(52, 2), string.Empty), new TextChange(new TextSpan(64, 2), string.Empty), }; var expectedSelectedSpans = new[] { Span.FromBounds(20, 21), Span.FromBounds(34, 34), Span.FromBounds(41, 42), Span.FromBounds(56, 56), }; UncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Uncomment_PartOfMultipleComments() { var code = @" //|start|//namespace N ////{ //|end|//}"; var expectedChanges = new[] { new TextChange(new TextSpan(2, 2), string.Empty), new TextChange(new TextSpan(19, 2), string.Empty), new TextChange(new TextSpan(26, 2), string.Empty), }; UncommentSelection(code, expectedChanges, Span.FromBounds(2, 25), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(530300)] [WorkItem(563924)] public void Comment_NoSelectionAtStartOfLine() { var code = @"|start||end|using System;"; CommentSelection(code, new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, new[] { new Span(0, 15) }, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_NoSelectionInBlockComment() { var code = @"using /* Sy|start||end|stem.*/IO;"; UncommentSelection(code, expectedChanges: new[] { new TextChange(new TextSpan(6, 2), string.Empty), new TextChange(new TextSpan(16, 2), string.Empty) }, expectedSelectedSpan: new Span(6, 8), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_BlockCommentWithPreviousBlockComment() { var code = @"/* comment */using /* Sy|start||end|stem.*/IO;"; UncommentSelection(code, expectedChanges: new[] { new TextChange(new TextSpan(19, 2), string.Empty), new TextChange(new TextSpan(29, 2), string.Empty) }, expectedSelectedSpan: new Span(19, 8), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_InsideEndOfBlockComment() { var code = @"/*using System;*|start||end|/"; UncommentSelection(code, expectedChanges: new[] { new TextChange(new TextSpan(0, 2), string.Empty), new TextChange(new TextSpan(15, 2), string.Empty) }, expectedSelectedSpan: new Span(0, 13), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_AtBeginningOfEndOfBlockComment() { var code = @"/*using System;|start||end|*/"; UncommentSelection(code, expectedChanges: new[] { new TextChange(new TextSpan(0, 2), string.Empty), new TextChange(new TextSpan(15, 2), string.Empty) }, expectedSelectedSpan: new Span(0, 13), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_AtEndOfBlockComment() { var code = @"/*using System;*/|start||end|"; UncommentSelection(code, Enumerable.Empty<TextChange>(), new Span(17, 0), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_BlockCommentWithNoEnd() { var code = @"/*using |start||end|System;"; UncommentSelection(code, Enumerable.Empty<TextChange>(), new Span(8, 0), supportBlockComments: true); } private static void UncommentSelection(string code, IEnumerable<TextChange> expectedChanges, Span expectedSelectedSpan, bool supportBlockComments) { CommentOrUncommentSelection(code, expectedChanges, new[] { expectedSelectedSpan }, supportBlockComments, CommentUncommentSelectionCommandHandler.Operation.Uncomment); } private static void UncommentSelection(string code, IEnumerable<TextChange> expectedChanges, IEnumerable<Span> expectedSelectedSpans, bool supportBlockComments) { CommentOrUncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments, CommentUncommentSelectionCommandHandler.Operation.Uncomment); } private static void CommentSelection(string code, IEnumerable<TextChange> expectedChanges, bool supportBlockComments) { CommentOrUncommentSelection(code, expectedChanges, null /*expectedSelectedSpans*/, supportBlockComments, CommentUncommentSelectionCommandHandler.Operation.Comment); } private static void CommentSelection(string code, IEnumerable<TextChange> expectedChanges, IEnumerable<Span> expectedSelectedSpans, bool supportBlockComments) { CommentOrUncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments, CommentUncommentSelectionCommandHandler.Operation.Comment); } private static void CommentSelection(ITextView textView, IEnumerable<TextChange> expectedChanges, IEnumerable<Span> expectedSelectedSpans, bool supportBlockComments) { CommentOrUncommentSelection(textView, expectedChanges, expectedSelectedSpans, supportBlockComments, CommentUncommentSelectionCommandHandler.Operation.Comment); } private static void CommentOrUncommentSelection( string code, IEnumerable<TextChange> expectedChanges, IEnumerable<Span> expectedSelectedSpans, bool supportBlockComments, CommentUncommentSelectionCommandHandler.Operation operation) { var textView = EditorFactory.CreateView(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, code); var selectedSpans = SetupSelection(textView); CommentOrUncommentSelection(textView, expectedChanges, expectedSelectedSpans, supportBlockComments, operation); } private static void CommentOrUncommentSelection( ITextView textView, IEnumerable<TextChange> expectedChanges, IEnumerable<Span> expectedSelectedSpans, bool supportBlockComments, CommentUncommentSelectionCommandHandler.Operation operation) { var textUndoHistoryRegistry = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<ITextUndoHistoryRegistry>(); var editorOperationsFactory = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<IEditorOperationsFactoryService>(); var commandHandler = new CommentUncommentSelectionCommandHandler(TestWaitIndicator.Default, textUndoHistoryRegistry, editorOperationsFactory); var service = new MockCommentUncommentService(supportBlockComments); var trackingSpans = new List<ITrackingSpan>(); var textChanges = new List<TextChange>(); commandHandler.CollectEdits(service, textView.Selection.GetSnapshotSpansOnBuffer(textView.TextBuffer), textChanges, trackingSpans, operation); AssertEx.SetEqual(expectedChanges, textChanges); // Actually apply the edit to let the tracking spans adjust. using (var edit = textView.TextBuffer.CreateEdit()) { textChanges.Do(tc => edit.Replace(tc.Span.ToSpan(), tc.NewText)); edit.Apply(); } if (trackingSpans.Any()) { textView.SetSelection(trackingSpans.First().GetSpan(textView.TextSnapshot)); } if (expectedSelectedSpans != null) { AssertEx.Equal(expectedSelectedSpans, textView.Selection.SelectedSpans.Select(snapshotSpan => snapshotSpan.Span)); } } private static IEnumerable<Span> SetupSelection(IWpfTextView textView) { var spans = new List<Span>(); while (true) { var startOfSelection = FindAndRemoveMarker(textView, "|start|"); var endOfSelection = FindAndRemoveMarker(textView, "|end|"); if (startOfSelection < 0) { break; } else { spans.Add(Span.FromBounds(startOfSelection, endOfSelection)); } } var snapshot = textView.TextSnapshot; if (spans.Count == 1) { textView.Selection.Select(new SnapshotSpan(snapshot, spans.Single()), isReversed: false); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Single().End)); } else { textView.Selection.Mode = TextSelectionMode.Box; textView.Selection.Select(new VirtualSnapshotPoint(snapshot, spans.First().Start), new VirtualSnapshotPoint(snapshot, spans.Last().End)); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Last().End)); } return spans; } private static int FindAndRemoveMarker(ITextView textView, string marker) { var index = textView.TextSnapshot.GetText().IndexOf(marker, StringComparison.Ordinal); if (index >= 0) { textView.TextBuffer.Delete(new Span(index, marker.Length)); } return index; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A simple coordination data structure that we use for fork/join style parallelism. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Diagnostics; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Threading; using System.Diagnostics.Contracts; namespace System.Threading { /// <summary> /// Represents a synchronization primitive that is signaled when its count reaches zero. /// </summary> /// <remarks> /// All public and protected members of <see cref="CountdownEvent"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="CountdownEvent"/> have /// completed, and Reset, which should only be used when no other threads are /// accessing the event. /// </remarks> [ComVisible(false)] [DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")] [HostProtection(Synchronization = true, ExternalThreading = true)] public class CountdownEvent : IDisposable { // CountdownEvent is a simple synchronization primitive used for fork/join parallelism. We create a // latch with a count of N; threads then signal the latch, which decrements N by 1; other threads can // wait on the latch at any point; when the latch count reaches 0, all threads are woken and // subsequent waiters return without waiting. The implementation internally lazily creates a true // Win32 event as needed. We also use some amount of spinning on MP machines before falling back to a // wait. private int m_initialCount; // The original # of signals the latch was instantiated with. private volatile int m_currentCount; // The # of outstanding signals before the latch transitions to a signaled state. private ManualResetEventSlim m_event; // An event used to manage blocking and signaling. private volatile bool m_disposed; // Whether the latch has been disposed. /// <summary> /// Initializes a new instance of <see cref="T:System.Threading.CountdownEvent"/> class with the /// specified count. /// </summary> /// <param name="initialCount">The number of signals required to set the <see /// cref="T:System.Threading.CountdownEvent"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="initialCount"/> is less /// than 0.</exception> public CountdownEvent(int initialCount) { if (initialCount < 0) { throw new ArgumentOutOfRangeException("initialCount"); } m_initialCount = initialCount; m_currentCount = initialCount; // Allocate a thin event, which internally defers creation of an actual Win32 event. m_event = new ManualResetEventSlim(); // If the latch was created with a count of 0, then it's already in the signaled state. if (initialCount == 0) { m_event.Set(); } } /// <summary> /// Gets the number of remaining signals required to set the event. /// </summary> /// <value> /// The number of remaining signals required to set the event. /// </value> public int CurrentCount { get { int observedCount = m_currentCount; return observedCount < 0 ? 0 : observedCount; } } /// <summary> /// Gets the numbers of signals initially required to set the event. /// </summary> /// <value> /// The number of signals initially required to set the event. /// </value> public int InitialCount { get { return m_initialCount; } } /// <summary> /// Determines whether the event is set. /// </summary> /// <value>true if the event is set; otherwise, false.</value> public bool IsSet { get { // The latch is "completed" if its current count has reached 0. Note that this is NOT // the same thing is checking the event's IsCompleted property. There is a tiny window // of time, after the final decrement of the current count to 0 and before setting the // event, where the two values are out of sync. return (m_currentCount <= 0); } } /// <summary> /// Gets a <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set. /// </summary> /// <value>A <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set.</value> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been disposed.</exception> /// <remarks> /// <see cref="WaitHandle"/> should only be used if it's needed for integration with code bases /// that rely on having a WaitHandle. If all that's needed is to wait for the <see cref="CountdownEvent"/> /// to be set, the <see cref="Wait()"/> method should be preferred. /// </remarks> public WaitHandle WaitHandle { get { ThrowIfDisposed(); return m_event.WaitHandle; } } /// <summary> /// Releases all resources used by the current instance of <see cref="T:System.Threading.CountdownEvent"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Dispose() { // Gets rid of this latch's associated resources. This can consist of a Win32 event // which is (lazily) allocated by the underlying thin event. This method is not safe to // call concurrently -- i.e. a caller must coordinate to ensure only one thread is using // the latch at the time of the call to Dispose. Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="T:System.Threading.CountdownEvent"/>, and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release /// only unmanaged resources.</param> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if (disposing) { m_event.Dispose(); m_disposed = true; } } /// <summary> /// Registers a signal with the <see cref="T:System.Threading.CountdownEvent"/>, decrementing its /// count. /// </summary> /// <returns>true if the signal caused the count to reach zero and the event was set; otherwise, /// false.</returns> /// <exception cref="T:System.InvalidOperationException">The current instance is already set. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Signal() { ThrowIfDisposed(); Contract.Assert(m_event != null); if (m_currentCount <= 0) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero")); } #pragma warning disable 0420 int newCount = Interlocked.Decrement(ref m_currentCount); #pragma warning restore 0420 if (newCount == 0) { m_event.Set(); return true; } else if (newCount < 0) { //if the count is decremented below zero, then throw, it's OK to keep the count negative, and we shouldn't set the event here //because there was a thread already which decremented it to zero and set the event throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero")); } return false; } /// <summary> /// Registers multiple signals with the <see cref="T:System.Threading.CountdownEvent"/>, /// decrementing its count by the specified amount. /// </summary> /// <param name="signalCount">The number of signals to register.</param> /// <returns>true if the signals caused the count to reach zero and the event was set; otherwise, /// false.</returns> /// <exception cref="T:System.InvalidOperationException"> /// The current instance is already set. -or- Or <paramref name="signalCount"/> is greater than <see /// cref="CurrentCount"/>. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less /// than 1.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Signal(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException("signalCount"); } ThrowIfDisposed(); Contract.Assert(m_event != null); int observedCount; SpinWait spin = new SpinWait(); while (true) { observedCount = m_currentCount; // If the latch is already signaled, we will fail. if (observedCount < signalCount) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero")); } // This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning // for this statement. This warning is clearly senseless for Interlocked operations. #pragma warning disable 0420 if (Interlocked.CompareExchange(ref m_currentCount, observedCount - signalCount, observedCount) == observedCount) #pragma warning restore 0420 { break; } // The CAS failed. Spin briefly and try again. spin.SpinOnce(); } // If we were the last to signal, set the event. if (observedCount == signalCount) { m_event.Set(); return true; } Contract.Assert(m_currentCount >= 0, "latch was decremented below zero"); return false; } /// <summary> /// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one. /// </summary> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException"> /// The current instance has already been disposed. /// </exception> public void AddCount() { AddCount(1); } /// <summary> /// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one. /// </summary> /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is /// already at zero. this will return false.</returns> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool TryAddCount() { return TryAddCount(1); } /// <summary> /// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a specified /// value. /// </summary> /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less than /// 0.</exception> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void AddCount(int signalCount) { if (!TryAddCount(signalCount)) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Increment_AlreadyZero")); } } /// <summary> /// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a /// specified value. /// </summary> /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param> /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is /// already at zero this will return false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less /// than 0.</exception> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool TryAddCount(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException("signalCount"); } ThrowIfDisposed(); // Loop around until we successfully increment the count. int observedCount; SpinWait spin = new SpinWait(); while (true) { observedCount = m_currentCount; if (observedCount <= 0) { return false; } else if (observedCount > (Int32.MaxValue - signalCount)) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Increment_AlreadyMax")); } // This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning // for this statement. This warning is clearly senseless for Interlocked operations. #pragma warning disable 0420 if (Interlocked.CompareExchange(ref m_currentCount, observedCount + signalCount, observedCount) == observedCount) #pragma warning restore 0420 { break; } // The CAS failed. Spin briefly and try again. spin.SpinOnce(); } return true; } /// <summary> /// Resets the <see cref="CurrentCount"/> to the value of <see cref="InitialCount"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed..</exception> public void Reset() { Reset(m_initialCount); } /// <summary> /// Resets the <see cref="CurrentCount"/> to a specified value. /// </summary> /// <param name="count">The number of signals required to set the <see /// cref="T:System.Threading.CountdownEvent"/>.</param> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="count"/> is /// less than 0.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has alread been disposed.</exception> public void Reset(int count) { ThrowIfDisposed(); if (count < 0) { throw new ArgumentOutOfRangeException("count"); } m_currentCount = count; m_initialCount = count; if (count == 0) { m_event.Set(); } else { m_event.Reset(); } } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set. /// </summary> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void Wait() { Wait(Timeout.Infinite, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, while /// observing a <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. If the /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> being observed /// is canceled during the wait operation, an <see cref="T:System.OperationCanceledException"/> /// will be thrown. /// </remarks> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been /// canceled.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } return Wait((int)totalMilliseconds, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using /// a <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a /// <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has /// been canceled.</exception> public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } return Wait((int)totalMilliseconds, cancellationToken); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// 32-bit signed integer to measure the time interval, while observing a /// <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has /// been canceled.</exception> public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout"); } ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); bool returnValue = IsSet; // If not completed yet, wait on the event. if (!returnValue) { // ** the actual wait returnValue = m_event.Wait(millisecondsTimeout, cancellationToken); //the Wait will throw OCE itself if the token is canceled. } return returnValue; } // -------------------------------------- // Private methods /// <summary> /// Throws an exception if the latch has been disposed. /// </summary> private void ThrowIfDisposed() { if (m_disposed) { throw new ObjectDisposedException("CountdownEvent"); } } } }
using System; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.IO; using Alvas.Audio; using System.Diagnostics; namespace AudioExCS { public class ConvertPanel : UserControl { public ConvertPanel() { InitializeComponent(); ofdFile.Filter = "*.wav|*.wav|*.mp3|*.mp3|*.avi|*.avi|*.wma;*.wmv;*.asf;*.mpg;*.aif;*.au;*.snd;*.mid;*.rmi;*.ogg;*.flac;*.cda;*.ac3;*.dts;*.mka;*.mkv;*.mpc;*.m4a;*.aac;*.mpa;*.mp2;*.m1a;*.m2a|*.wma;*.wmv;*.asf;*.mpg;*.aif;*.au;*.snd;*.mid;*.rmi;*.ogg;*.flac;*.cda;*.ac3;*.dts;*.mka;*.mkv;*.mpc;*.m4a;*.aac;*.mpa;*.mp2;*.m1a;*.m2a|*.*|*.*"; } private OpenFileDialog ofdFile; private GroupBox groupBox1; private Label lblFileFormat; private TextBox tbFile2; private Button btnFile2; private Button btnMakeMp3; private GroupBox gbConvert; private Button btnDialog; private RadioButton rbDialog; private RadioButton rbCombobox; private Button btnConvert; private ComboBox cbFormatConverted; private ProgressBar pbConvert; /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.ofdFile = new System.Windows.Forms.OpenFileDialog(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.lblFileFormat = new System.Windows.Forms.Label(); this.tbFile2 = new System.Windows.Forms.TextBox(); this.btnFile2 = new System.Windows.Forms.Button(); this.btnMakeMp3 = new System.Windows.Forms.Button(); this.gbConvert = new System.Windows.Forms.GroupBox(); this.btnDialog = new System.Windows.Forms.Button(); this.rbDialog = new System.Windows.Forms.RadioButton(); this.rbCombobox = new System.Windows.Forms.RadioButton(); this.btnConvert = new System.Windows.Forms.Button(); this.cbFormatConverted = new System.Windows.Forms.ComboBox(); this.pbConvert = new System.Windows.Forms.ProgressBar(); this.groupBox1.SuspendLayout(); this.gbConvert.SuspendLayout(); this.SuspendLayout(); // // ofdFile // this.ofdFile.DefaultExt = "wav"; this.ofdFile.Filter = "*.wav;*.avi;*.mp3|*.wav;*.avi;*.mp3|*.wav|*.wav|*.avi|*.avi|*.mp3|*.mp3"; // // groupBox1 // this.groupBox1.Controls.Add(this.lblFileFormat); this.groupBox1.Controls.Add(this.tbFile2); this.groupBox1.Controls.Add(this.btnFile2); this.groupBox1.Location = new System.Drawing.Point(3, 3); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(215, 66); this.groupBox1.TabIndex = 34; this.groupBox1.TabStop = false; this.groupBox1.Text = "Select source file name"; // // lblFileFormat // this.lblFileFormat.AutoSize = true; this.lblFileFormat.Location = new System.Drawing.Point(6, 42); this.lblFileFormat.Name = "lblFileFormat"; this.lblFileFormat.Size = new System.Drawing.Size(0, 13); this.lblFileFormat.TabIndex = 29; // // tbFile2 // this.tbFile2.BackColor = System.Drawing.SystemColors.Window; this.tbFile2.Location = new System.Drawing.Point(6, 19); this.tbFile2.Name = "tbFile2"; this.tbFile2.ReadOnly = true; this.tbFile2.Size = new System.Drawing.Size(183, 20); this.tbFile2.TabIndex = 22; // // btnFile2 // this.btnFile2.Location = new System.Drawing.Point(188, 19); this.btnFile2.Name = "btnFile2"; this.btnFile2.Size = new System.Drawing.Size(23, 20); this.btnFile2.TabIndex = 23; this.btnFile2.Text = "..."; this.btnFile2.Click += new System.EventHandler(this.btnFile2_Click); // // btnMakeMp3 // this.btnMakeMp3.Enabled = false; this.btnMakeMp3.Location = new System.Drawing.Point(10, 188); this.btnMakeMp3.Name = "btnMakeMp3"; this.btnMakeMp3.Size = new System.Drawing.Size(203, 23); this.btnMakeMp3.TabIndex = 33; this.btnMakeMp3.Text = "Convert *.wav to *.mp3"; this.btnMakeMp3.Click += new System.EventHandler(this.btnMakeMp3_Click); // // gbConvert // this.gbConvert.Controls.Add(this.btnDialog); this.gbConvert.Controls.Add(this.rbDialog); this.gbConvert.Controls.Add(this.rbCombobox); this.gbConvert.Controls.Add(this.btnConvert); this.gbConvert.Controls.Add(this.cbFormatConverted); this.gbConvert.Enabled = false; this.gbConvert.Location = new System.Drawing.Point(3, 75); this.gbConvert.Name = "gbConvert"; this.gbConvert.Size = new System.Drawing.Size(215, 107); this.gbConvert.TabIndex = 32; this.gbConvert.TabStop = false; this.gbConvert.Text = "Select destination format"; // // btnDialog // this.btnDialog.Enabled = false; this.btnDialog.Location = new System.Drawing.Point(26, 46); this.btnDialog.Name = "btnDialog"; this.btnDialog.Size = new System.Drawing.Size(183, 23); this.btnDialog.TabIndex = 29; this.btnDialog.Text = "Select destination format"; this.btnDialog.Click += new System.EventHandler(this.btnDialog_Click); // // rbDialog // this.rbDialog.Location = new System.Drawing.Point(6, 52); this.rbDialog.Name = "rbDialog"; this.rbDialog.Size = new System.Drawing.Size(14, 13); this.rbDialog.TabIndex = 28; this.rbDialog.Click += new System.EventHandler(this.rbDialog_CheckedChanged); // // rbCombobox // this.rbCombobox.Checked = true; this.rbCombobox.Location = new System.Drawing.Point(6, 22); this.rbCombobox.Name = "rbCombobox"; this.rbCombobox.Size = new System.Drawing.Size(14, 13); this.rbCombobox.TabIndex = 27; this.rbCombobox.TabStop = true; // // btnConvert // this.btnConvert.Location = new System.Drawing.Point(7, 75); this.btnConvert.Name = "btnConvert"; this.btnConvert.Size = new System.Drawing.Size(202, 23); this.btnConvert.TabIndex = 27; this.btnConvert.Text = "Convert"; this.btnConvert.Click += new System.EventHandler(this.btnConvert_Click); // // cbFormatConverted // this.cbFormatConverted.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbFormatConverted.Location = new System.Drawing.Point(26, 19); this.cbFormatConverted.Name = "cbFormatConverted"; this.cbFormatConverted.Size = new System.Drawing.Size(183, 21); this.cbFormatConverted.TabIndex = 25; this.cbFormatConverted.SelectedIndexChanged += new System.EventHandler(this.cbFormatConverted_SelectedIndexChanged); // // pbConvert // this.pbConvert.Dock = System.Windows.Forms.DockStyle.Bottom; this.pbConvert.Location = new System.Drawing.Point(0, 222); this.pbConvert.Name = "pbConvert"; this.pbConvert.Size = new System.Drawing.Size(227, 23); this.pbConvert.TabIndex = 35; // // ConvertPanel // this.Controls.Add(this.pbConvert); this.Controls.Add(this.groupBox1); this.Controls.Add(this.btnMakeMp3); this.Controls.Add(this.gbConvert); this.Name = "ConvertPanel"; this.Size = new System.Drawing.Size(227, 222); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.gbConvert.ResumeLayout(false); this.ResumeLayout(false); } #endregion //private FileStream fs = null; private IntPtr oldFormat = IntPtr.Zero; private IntPtr newFormat = IntPtr.Zero; //private byte[] data = null; IAudioReader ar = null; private void GetFormatsConverted(IntPtr format) { newFormat = IntPtr.Zero; //cbFormatConverted.DataSource = AudioCompressionManager.GetCompatibleFormatList(format); cbFormatConverted.Items.Clear(); FormatDetails[] fdArr = AudioCompressionManager.GetCompatibleFormatList(format); for (int i = 0; i < fdArr.Length; i++) { FormatDetails fd = fdArr[i]; fd.ShowFormatTag = true; cbFormatConverted.Items.Add(fd); } } private void btnFile2_Click(object sender, EventArgs e) { if (ofdFile.ShowDialog(this) == DialogResult.OK) { tbFile2.Text = ofdFile.FileName; int lenExt = 4; string ext = ofdFile.FileName.Substring(ofdFile.FileName.Length - lenExt, lenExt).ToLower(); switch (ext) { case ".au": case ".snd": ar = new AuReader(File.OpenRead(ofdFile.FileName)); break; case ".wav": ar = new WaveReader(File.OpenRead(ofdFile.FileName)); break; case ".avi" : ar = new AviReader(File.OpenRead(ofdFile.FileName)); if (!((AviReader)ar).HasAudio) { MessageBox.Show("Avi stream has not audio track"); return; } break; case ".mp3" : ar = new Mp3Reader(File.OpenRead(ofdFile.FileName)); break; default: ar = new DsReader(ofdFile.FileName); if (!((DsReader)ar).HasAudio) { MessageBox.Show("DirectShow stream has not audio track"); return; } break; } oldFormat = ar.ReadFormat(); FormatDetails fd = AudioCompressionManager.GetFormatDetails(oldFormat); lblFileFormat.Text = string.Format("{0} {1}", AudioCompressionManager.GetFormatTagDetails(fd.FormatTag).FormatTagName, fd.FormatName); GetFormatsConverted(oldFormat); gbConvert.Enabled = true; btnMakeMp3.Enabled = false; } } private void btnConvert_Click(object sender, EventArgs e) { if (newFormat == IntPtr.Zero) { MessageBox.Show("Please, specify destination format for converting"); return; } string fileName = tbFile2.Text + ".wav"; int size = ar.Milliseconds2Bytes(1000); int len = ar.GetLengthInBytes(); AcmConverter ac = new AcmConverter(oldFormat, newFormat, false); FileStream fs = new FileStream(fileName, FileMode.Create); WaveWriter ww = new WaveWriter(fs, AudioCompressionManager.FormatBytes(newFormat)); pbConvert.Maximum = len; int y = 0; while (y < len) { pbConvert.Value = y; byte[] data = ar.ReadDataInBytes(y, size); if (data.Length == 0) { break; } y += data.Length; byte[] newData = ac.Convert(data); ww.WriteData(newData); } ww.Close(); ar.Close(); gbConvert.Enabled = false; btnMakeMp3.Enabled = tbFile2.Text.ToLower().EndsWith(".wav"); OpenContainingFolder(fileName); } private void OpenContainingFolder(string fileName) { MessageBox.Show(string.Format("The result is stored in the file '{0}'. Choose next file for the converting.", fileName), "The conversion was executed successfully"); Process.Start(Path.GetDirectoryName(fileName)); } private void NewFormatFromComboBox() { newFormat = (cbFormatConverted.SelectedIndex >= 0) ? ((FormatDetails)cbFormatConverted.SelectedItem).FormatHandle : IntPtr.Zero; } private void cbFormatConverted_SelectedIndexChanged(object sender, EventArgs e) { NewFormatFromComboBox(); } private void ConvertDialog() { FormatChooseResult res = AudioCompressionManager.ChooseCompatibleFormat(this.Handle, oldFormat); if (res.Result != 0) { btnDialog.Text = "Select destination format"; } else { newFormat = res.Format; btnDialog.Text = string.Format("{0} {1}", res.FormatTagName, res.FormatName); cbFormatConverted.Enabled = false; } } private void rbDialog_CheckedChanged(object sender, EventArgs e) { btnDialog.Enabled = rbDialog.Checked; cbFormatConverted.Enabled = !rbDialog.Checked; if (!rbDialog.Checked) { NewFormatFromComboBox(); } } private void btnMakeMp3_Click(object sender, EventArgs e) { string fileName = tbFile2.Text + ".mp3"; AudioCompressionManager.Wave2Mp3(tbFile2.Text, fileName); btnMakeMp3.Enabled = false; OpenContainingFolder(fileName); } private void btnDialog_Click(object sender, EventArgs e) { ConvertDialog(); } } }
using System; using System.Collections.Generic; using System.Composition.Hosting; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyModel; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OmniSharp.Eventing; using OmniSharp.FileWatching; using OmniSharp.Host.Internal; using OmniSharp.Mef; using OmniSharp.Middleware; using OmniSharp.Options; using OmniSharp.Roslyn; using OmniSharp.Roslyn.Options; using OmniSharp.Services; using OmniSharp.Stdio.Logging; using OmniSharp.Stdio.Services; using OmniSharp.Utilities; namespace OmniSharp { public class Startup { private readonly IOmniSharpEnvironment _env; public IConfiguration Configuration { get; } public OmniSharpWorkspace Workspace { get; private set; } public CompositionHost PluginHost { get; private set; } public Startup(IOmniSharpEnvironment env) { _env = env; var configBuilder = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile(Constants.ConfigFile, optional: true) .AddEnvironmentVariables("OMNISHARP_"); if (env.AdditionalArguments?.Length > 0) { configBuilder.AddCommandLine(env.AdditionalArguments); } // Use the global omnisharp config if there's any in the shared path configBuilder.CreateAndAddGlobalOptionsFile(env); // Use the local omnisharp config if there's any in the root path configBuilder.AddJsonFile( new PhysicalFileProvider(env.TargetDirectory).WrapForPolling(), Constants.OptionsFile, optional: true, reloadOnChange: true); Configuration = configBuilder.Build(); } public void ConfigureServices(IServiceCollection services) { // Add the omnisharp workspace to the container services.AddSingleton(typeof(OmniSharpWorkspace), _ => Workspace); services.AddSingleton(typeof(CompositionHost), _ => PluginHost); // Caching services.AddSingleton<IMemoryCache, MemoryCache>(); services.AddOptions(); // Setup the options from configuration services.Configure<OmniSharpOptions>(Configuration); } public static CompositionHost CreateCompositionHost(IServiceProvider serviceProvider, OmniSharpOptions options, IEnumerable<Assembly> assemblies) { var config = new ContainerConfiguration(); assemblies = assemblies .Concat(new[] { typeof(OmniSharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly }) .Distinct(); foreach (var assembly in assemblies) { config = config.WithAssembly(assembly); } var memoryCache = serviceProvider.GetService<IMemoryCache>(); var loggerFactory = serviceProvider.GetService<ILoggerFactory>(); var env = serviceProvider.GetService<IOmniSharpEnvironment>(); var writer = serviceProvider.GetService<ISharedTextWriter>(); var loader = serviceProvider.GetService<IAssemblyLoader>(); var fileSystemWatcher = new ManualFileSystemWatcher(); var metadataHelper = new MetadataHelper(loader); config = config .WithProvider(MefValueProvider.From(serviceProvider)) .WithProvider(MefValueProvider.From<IFileSystemWatcher>(fileSystemWatcher)) .WithProvider(MefValueProvider.From(memoryCache)) .WithProvider(MefValueProvider.From(loggerFactory)) .WithProvider(MefValueProvider.From(env)) .WithProvider(MefValueProvider.From(writer)) .WithProvider(MefValueProvider.From(options)) .WithProvider(MefValueProvider.From(options.FormattingOptions)) .WithProvider(MefValueProvider.From(loader)) .WithProvider(MefValueProvider.From(metadataHelper)); if (env.TransportType == TransportType.Stdio) { config = config .WithProvider(MefValueProvider.From<IEventEmitter>(new StdioEventEmitter(writer))); } else { config = config .WithProvider(MefValueProvider.From(NullEventEmitter.Instance)); } return config.CreateContainer(); } public void Configure( IApplicationBuilder app, IServiceProvider serviceProvider, ILoggerFactory loggerFactory, ISharedTextWriter writer, IAssemblyLoader loader, IOptionsMonitor<OmniSharpOptions> options) { if (_env.TransportType == TransportType.Stdio) { loggerFactory.AddStdio(writer, (category, level) => LogFilter(category, level, _env)); } else { loggerFactory.AddConsole((category, level) => LogFilter(category, level, _env)); } var logger = loggerFactory.CreateLogger<Startup>(); var assemblies = DiscoverOmniSharpAssemblies(loader, logger); PluginHost = CreateCompositionHost(serviceProvider, options.CurrentValue, assemblies); Workspace = PluginHost.GetExport<OmniSharpWorkspace>(); app.UseRequestLogging(); app.UseExceptionHandler("/error"); app.UseMiddleware<EndpointMiddleware>(); app.UseMiddleware<StatusMiddleware>(); app.UseMiddleware<StopServerMiddleware>(); if (_env.TransportType == TransportType.Stdio) { logger.LogInformation($"Omnisharp server running using {nameof(TransportType.Stdio)} at location '{_env.TargetDirectory}' on host {_env.HostProcessId}."); } else { logger.LogInformation($"Omnisharp server running on port '{_env.Port}' at location '{_env.TargetDirectory}' on host {_env.HostProcessId}."); } var workspaceHelper = new WorkspaceHelper(PluginHost, Configuration, options.CurrentValue, loggerFactory); workspaceHelper.Initialize(Workspace); // when configuration options change // run workspace options providers automatically options.OnChange(o => { workspaceHelper.ProvideOptions(Workspace, o); }); logger.LogInformation("Configuration finished."); } private static List<Assembly> DiscoverOmniSharpAssemblies(IAssemblyLoader loader, ILogger logger) { // Iterate through all runtime libraries in the dependency context and // load them if they depend on OmniSharp. var assemblies = new List<Assembly>(); var dependencyContext = DependencyContext.Default; foreach (var runtimeLibrary in dependencyContext.RuntimeLibraries) { if (DependsOnOmniSharp(runtimeLibrary)) { foreach (var name in runtimeLibrary.GetDefaultAssemblyNames(dependencyContext)) { var assembly = loader.Load(name); if (assembly != null) { assemblies.Add(assembly); logger.LogDebug($"Loaded {assembly.FullName}"); } } } } return assemblies; } private static bool DependsOnOmniSharp(RuntimeLibrary runtimeLibrary) { foreach (var dependency in runtimeLibrary.Dependencies) { if (dependency.Name == "OmniSharp.Abstractions" || dependency.Name == "OmniSharp.Roslyn") { return true; } } return false; } private static bool LogFilter(string category, LogLevel level, IOmniSharpEnvironment environment) { if (environment.LogLevel > level) { return false; } if (string.Equals(category, typeof(ExceptionHandlerMiddleware).FullName, StringComparison.OrdinalIgnoreCase)) { return true; } if (!category.StartsWith("OmniSharp", StringComparison.OrdinalIgnoreCase)) { return false; } if (string.Equals(category, typeof(WorkspaceInformationService).FullName, StringComparison.OrdinalIgnoreCase)) { return false; } if (string.Equals(category, typeof(ProjectEventForwarder).FullName, StringComparison.OrdinalIgnoreCase)) { return false; } return true; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// ServiceResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Verify.V2 { public class ServiceResource : Resource { private static Request BuildCreateRequest(CreateServiceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Verify, "/v2/Services", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Create a new Verification Service. /// </summary> /// <param name="options"> Create Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Create(CreateServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Create a new Verification Service. /// </summary> /// <param name="options"> Create Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> CreateAsync(CreateServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Create a new Verification Service. /// </summary> /// <param name="friendlyName"> A string to describe the verification service </param> /// <param name="codeLength"> The length of the verification code to generate </param> /// <param name="lookupEnabled"> Whether to perform a lookup with each verification </param> /// <param name="skipSmsToLandlines"> Whether to skip sending SMS verifications to landlines </param> /// <param name="dtmfInputRequired"> Whether to ask the user to press a number before delivering the verify code in a /// phone call </param> /// <param name="ttsName"> The name of an alternative text-to-speech service to use in phone calls </param> /// <param name="psd2Enabled"> Whether to pass PSD2 transaction parameters when starting a verification </param> /// <param name="doNotShareWarningEnabled"> Whether to add a security warning at the end of an SMS. </param> /// <param name="customCodeEnabled"> Whether to allow sending verifications with a custom code. </param> /// <param name="pushIncludeDate"> Optional. Include the date in the Challenge's reponse. Default: true </param> /// <param name="pushApnCredentialSid"> Optional. Set APN Credential for this service. </param> /// <param name="pushFcmCredentialSid"> Optional. Set FCM Credential for this service. </param> /// <param name="totpIssuer"> Optional. Set TOTP Issuer for this service. </param> /// <param name="totpTimeStep"> Optional. How often, in seconds, are TOTP codes generated </param> /// <param name="totpCodeLength"> Optional. Number of digits for generated TOTP codes </param> /// <param name="totpSkew"> Optional. The number of past and future time-steps valid at a given time </param> /// <param name="defaultTemplateSid"> The verification template SMS messages. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Create(string friendlyName, int? codeLength = null, bool? lookupEnabled = null, bool? skipSmsToLandlines = null, bool? dtmfInputRequired = null, string ttsName = null, bool? psd2Enabled = null, bool? doNotShareWarningEnabled = null, bool? customCodeEnabled = null, bool? pushIncludeDate = null, string pushApnCredentialSid = null, string pushFcmCredentialSid = null, string totpIssuer = null, int? totpTimeStep = null, int? totpCodeLength = null, int? totpSkew = null, string defaultTemplateSid = null, ITwilioRestClient client = null) { var options = new CreateServiceOptions(friendlyName){CodeLength = codeLength, LookupEnabled = lookupEnabled, SkipSmsToLandlines = skipSmsToLandlines, DtmfInputRequired = dtmfInputRequired, TtsName = ttsName, Psd2Enabled = psd2Enabled, DoNotShareWarningEnabled = doNotShareWarningEnabled, CustomCodeEnabled = customCodeEnabled, PushIncludeDate = pushIncludeDate, PushApnCredentialSid = pushApnCredentialSid, PushFcmCredentialSid = pushFcmCredentialSid, TotpIssuer = totpIssuer, TotpTimeStep = totpTimeStep, TotpCodeLength = totpCodeLength, TotpSkew = totpSkew, DefaultTemplateSid = defaultTemplateSid}; return Create(options, client); } #if !NET35 /// <summary> /// Create a new Verification Service. /// </summary> /// <param name="friendlyName"> A string to describe the verification service </param> /// <param name="codeLength"> The length of the verification code to generate </param> /// <param name="lookupEnabled"> Whether to perform a lookup with each verification </param> /// <param name="skipSmsToLandlines"> Whether to skip sending SMS verifications to landlines </param> /// <param name="dtmfInputRequired"> Whether to ask the user to press a number before delivering the verify code in a /// phone call </param> /// <param name="ttsName"> The name of an alternative text-to-speech service to use in phone calls </param> /// <param name="psd2Enabled"> Whether to pass PSD2 transaction parameters when starting a verification </param> /// <param name="doNotShareWarningEnabled"> Whether to add a security warning at the end of an SMS. </param> /// <param name="customCodeEnabled"> Whether to allow sending verifications with a custom code. </param> /// <param name="pushIncludeDate"> Optional. Include the date in the Challenge's reponse. Default: true </param> /// <param name="pushApnCredentialSid"> Optional. Set APN Credential for this service. </param> /// <param name="pushFcmCredentialSid"> Optional. Set FCM Credential for this service. </param> /// <param name="totpIssuer"> Optional. Set TOTP Issuer for this service. </param> /// <param name="totpTimeStep"> Optional. How often, in seconds, are TOTP codes generated </param> /// <param name="totpCodeLength"> Optional. Number of digits for generated TOTP codes </param> /// <param name="totpSkew"> Optional. The number of past and future time-steps valid at a given time </param> /// <param name="defaultTemplateSid"> The verification template SMS messages. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> CreateAsync(string friendlyName, int? codeLength = null, bool? lookupEnabled = null, bool? skipSmsToLandlines = null, bool? dtmfInputRequired = null, string ttsName = null, bool? psd2Enabled = null, bool? doNotShareWarningEnabled = null, bool? customCodeEnabled = null, bool? pushIncludeDate = null, string pushApnCredentialSid = null, string pushFcmCredentialSid = null, string totpIssuer = null, int? totpTimeStep = null, int? totpCodeLength = null, int? totpSkew = null, string defaultTemplateSid = null, ITwilioRestClient client = null) { var options = new CreateServiceOptions(friendlyName){CodeLength = codeLength, LookupEnabled = lookupEnabled, SkipSmsToLandlines = skipSmsToLandlines, DtmfInputRequired = dtmfInputRequired, TtsName = ttsName, Psd2Enabled = psd2Enabled, DoNotShareWarningEnabled = doNotShareWarningEnabled, CustomCodeEnabled = customCodeEnabled, PushIncludeDate = pushIncludeDate, PushApnCredentialSid = pushApnCredentialSid, PushFcmCredentialSid = pushFcmCredentialSid, TotpIssuer = totpIssuer, TotpTimeStep = totpTimeStep, TotpCodeLength = totpCodeLength, TotpSkew = totpSkew, DefaultTemplateSid = defaultTemplateSid}; return await CreateAsync(options, client); } #endif private static Request BuildFetchRequest(FetchServiceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Verify, "/v2/Services/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch specific Verification Service Instance. /// </summary> /// <param name="options"> Fetch Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Fetch(FetchServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch specific Verification Service Instance. /// </summary> /// <param name="options"> Fetch Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> FetchAsync(FetchServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch specific Verification Service Instance. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchServiceOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch specific Verification Service Instance. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchServiceOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteServiceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Verify, "/v2/Services/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a specific Verification Service Instance. /// </summary> /// <param name="options"> Delete Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static bool Delete(DeleteServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a specific Verification Service Instance. /// </summary> /// <param name="options"> Delete Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a specific Verification Service Instance. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static bool Delete(string pathSid, ITwilioRestClient client = null) { var options = new DeleteServiceOptions(pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// Delete a specific Verification Service Instance. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null) { var options = new DeleteServiceOptions(pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildReadRequest(ReadServiceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Verify, "/v2/Services", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all Verification Services for an account. /// </summary> /// <param name="options"> Read Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ResourceSet<ServiceResource> Read(ReadServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<ServiceResource>.FromJson("services", response.Content); return new ResourceSet<ServiceResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Verification Services for an account. /// </summary> /// <param name="options"> Read Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ResourceSet<ServiceResource>> ReadAsync(ReadServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<ServiceResource>.FromJson("services", response.Content); return new ResourceSet<ServiceResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all Verification Services for an account. /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ResourceSet<ServiceResource> Read(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadServiceOptions(){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Verification Services for an account. /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ResourceSet<ServiceResource>> ReadAsync(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadServiceOptions(){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<ServiceResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<ServiceResource>.FromJson("services", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<ServiceResource> NextPage(Page<ServiceResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Verify) ); var response = client.Request(request); return Page<ServiceResource>.FromJson("services", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<ServiceResource> PreviousPage(Page<ServiceResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Verify) ); var response = client.Request(request); return Page<ServiceResource>.FromJson("services", response.Content); } private static Request BuildUpdateRequest(UpdateServiceOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Verify, "/v2/Services/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Update a specific Verification Service. /// </summary> /// <param name="options"> Update Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Update(UpdateServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Update a specific Verification Service. /// </summary> /// <param name="options"> Update Service parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> UpdateAsync(UpdateServiceOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Update a specific Verification Service. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="friendlyName"> A string to describe the verification service </param> /// <param name="codeLength"> The length of the verification code to generate </param> /// <param name="lookupEnabled"> Whether to perform a lookup with each verification </param> /// <param name="skipSmsToLandlines"> Whether to skip sending SMS verifications to landlines </param> /// <param name="dtmfInputRequired"> Whether to ask the user to press a number before delivering the verify code in a /// phone call </param> /// <param name="ttsName"> The name of an alternative text-to-speech service to use in phone calls </param> /// <param name="psd2Enabled"> Whether to pass PSD2 transaction parameters when starting a verification </param> /// <param name="doNotShareWarningEnabled"> Whether to add a privacy warning at the end of an SMS. </param> /// <param name="customCodeEnabled"> Whether to allow sending verifications with a custom code. </param> /// <param name="pushIncludeDate"> Optional. Include the date in the Challenge's reponse. Default: true </param> /// <param name="pushApnCredentialSid"> Optional. Set APN Credential for this service. </param> /// <param name="pushFcmCredentialSid"> Optional. Set FCM Credential for this service. </param> /// <param name="totpIssuer"> Optional. Set TOTP Issuer for this service. </param> /// <param name="totpTimeStep"> Optional. How often, in seconds, are TOTP codes generated </param> /// <param name="totpCodeLength"> Optional. Number of digits for generated TOTP codes </param> /// <param name="totpSkew"> Optional. The number of past and future time-steps valid at a given time </param> /// <param name="defaultTemplateSid"> The verification template SMS messages. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Service </returns> public static ServiceResource Update(string pathSid, string friendlyName = null, int? codeLength = null, bool? lookupEnabled = null, bool? skipSmsToLandlines = null, bool? dtmfInputRequired = null, string ttsName = null, bool? psd2Enabled = null, bool? doNotShareWarningEnabled = null, bool? customCodeEnabled = null, bool? pushIncludeDate = null, string pushApnCredentialSid = null, string pushFcmCredentialSid = null, string totpIssuer = null, int? totpTimeStep = null, int? totpCodeLength = null, int? totpSkew = null, string defaultTemplateSid = null, ITwilioRestClient client = null) { var options = new UpdateServiceOptions(pathSid){FriendlyName = friendlyName, CodeLength = codeLength, LookupEnabled = lookupEnabled, SkipSmsToLandlines = skipSmsToLandlines, DtmfInputRequired = dtmfInputRequired, TtsName = ttsName, Psd2Enabled = psd2Enabled, DoNotShareWarningEnabled = doNotShareWarningEnabled, CustomCodeEnabled = customCodeEnabled, PushIncludeDate = pushIncludeDate, PushApnCredentialSid = pushApnCredentialSid, PushFcmCredentialSid = pushFcmCredentialSid, TotpIssuer = totpIssuer, TotpTimeStep = totpTimeStep, TotpCodeLength = totpCodeLength, TotpSkew = totpSkew, DefaultTemplateSid = defaultTemplateSid}; return Update(options, client); } #if !NET35 /// <summary> /// Update a specific Verification Service. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="friendlyName"> A string to describe the verification service </param> /// <param name="codeLength"> The length of the verification code to generate </param> /// <param name="lookupEnabled"> Whether to perform a lookup with each verification </param> /// <param name="skipSmsToLandlines"> Whether to skip sending SMS verifications to landlines </param> /// <param name="dtmfInputRequired"> Whether to ask the user to press a number before delivering the verify code in a /// phone call </param> /// <param name="ttsName"> The name of an alternative text-to-speech service to use in phone calls </param> /// <param name="psd2Enabled"> Whether to pass PSD2 transaction parameters when starting a verification </param> /// <param name="doNotShareWarningEnabled"> Whether to add a privacy warning at the end of an SMS. </param> /// <param name="customCodeEnabled"> Whether to allow sending verifications with a custom code. </param> /// <param name="pushIncludeDate"> Optional. Include the date in the Challenge's reponse. Default: true </param> /// <param name="pushApnCredentialSid"> Optional. Set APN Credential for this service. </param> /// <param name="pushFcmCredentialSid"> Optional. Set FCM Credential for this service. </param> /// <param name="totpIssuer"> Optional. Set TOTP Issuer for this service. </param> /// <param name="totpTimeStep"> Optional. How often, in seconds, are TOTP codes generated </param> /// <param name="totpCodeLength"> Optional. Number of digits for generated TOTP codes </param> /// <param name="totpSkew"> Optional. The number of past and future time-steps valid at a given time </param> /// <param name="defaultTemplateSid"> The verification template SMS messages. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Service </returns> public static async System.Threading.Tasks.Task<ServiceResource> UpdateAsync(string pathSid, string friendlyName = null, int? codeLength = null, bool? lookupEnabled = null, bool? skipSmsToLandlines = null, bool? dtmfInputRequired = null, string ttsName = null, bool? psd2Enabled = null, bool? doNotShareWarningEnabled = null, bool? customCodeEnabled = null, bool? pushIncludeDate = null, string pushApnCredentialSid = null, string pushFcmCredentialSid = null, string totpIssuer = null, int? totpTimeStep = null, int? totpCodeLength = null, int? totpSkew = null, string defaultTemplateSid = null, ITwilioRestClient client = null) { var options = new UpdateServiceOptions(pathSid){FriendlyName = friendlyName, CodeLength = codeLength, LookupEnabled = lookupEnabled, SkipSmsToLandlines = skipSmsToLandlines, DtmfInputRequired = dtmfInputRequired, TtsName = ttsName, Psd2Enabled = psd2Enabled, DoNotShareWarningEnabled = doNotShareWarningEnabled, CustomCodeEnabled = customCodeEnabled, PushIncludeDate = pushIncludeDate, PushApnCredentialSid = pushApnCredentialSid, PushFcmCredentialSid = pushFcmCredentialSid, TotpIssuer = totpIssuer, TotpTimeStep = totpTimeStep, TotpCodeLength = totpCodeLength, TotpSkew = totpSkew, DefaultTemplateSid = defaultTemplateSid}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ServiceResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ServiceResource object represented by the provided JSON </returns> public static ServiceResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ServiceResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The string that you assigned to describe the verification service /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The length of the verification code /// </summary> [JsonProperty("code_length")] public int? CodeLength { get; private set; } /// <summary> /// Whether to perform a lookup with each verification /// </summary> [JsonProperty("lookup_enabled")] public bool? LookupEnabled { get; private set; } /// <summary> /// Whether to pass PSD2 transaction parameters when starting a verification /// </summary> [JsonProperty("psd2_enabled")] public bool? Psd2Enabled { get; private set; } /// <summary> /// Whether to skip sending SMS verifications to landlines /// </summary> [JsonProperty("skip_sms_to_landlines")] public bool? SkipSmsToLandlines { get; private set; } /// <summary> /// Whether to ask the user to press a number before delivering the verify code in a phone call /// </summary> [JsonProperty("dtmf_input_required")] public bool? DtmfInputRequired { get; private set; } /// <summary> /// The name of an alternative text-to-speech service to use in phone calls /// </summary> [JsonProperty("tts_name")] public string TtsName { get; private set; } /// <summary> /// Whether to add a security warning at the end of an SMS. /// </summary> [JsonProperty("do_not_share_warning_enabled")] public bool? DoNotShareWarningEnabled { get; private set; } /// <summary> /// Whether to allow sending verifications with a custom code. /// </summary> [JsonProperty("custom_code_enabled")] public bool? CustomCodeEnabled { get; private set; } /// <summary> /// The service level configuration of factor push type. /// </summary> [JsonProperty("push")] public object Push { get; private set; } /// <summary> /// The service level configuration of factor TOTP type. /// </summary> [JsonProperty("totp")] public object Totp { get; private set; } /// <summary> /// The default_template_sid /// </summary> [JsonProperty("default_template_sid")] public string DefaultTemplateSid { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The URLs of related resources /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private ServiceResource() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace System.Net.Sockets { public partial class SocketAsyncEventArgs : EventArgs, IDisposable { private int _acceptedFileDescriptor; private int _socketAddressSize; private SocketFlags _receivedFlags; internal int? SendPacketsDescriptorCount { get { return null; } } private void InitializeInternals() { // No-op for *nix. } private void FreeInternals(bool calledFromFinalizer) { // No-op for *nix. } private void SetupSingleBuffer() { // No-op for *nix. } private void SetupMultipleBuffers() { // No-op for *nix. } private void SetupSendPacketsElements() { // No-op for *nix. } private void InnerComplete() { // No-op for *nix. } private void InnerStartOperationAccept(bool userSuppliedBuffer) { _acceptedFileDescriptor = -1; } private void AcceptCompletionCallback(int acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError) { // TODO: receive bytes on socket if requested _acceptedFileDescriptor = acceptedFileDescriptor; Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer); _acceptAddressBufferCount = socketAddressSize; CompletionCallback(0, socketError); } internal unsafe SocketError DoOperationAccept(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, out int bytesTransferred) { Debug.Assert(acceptHandle == null); bytesTransferred = 0; return handle.AsyncContext.AcceptAsync(_buffer ?? _acceptBuffer, _acceptAddressBufferCount / 2, AcceptCompletionCallback); } private void InnerStartOperationConnect() { // No-op for *nix. } private void ConnectCompletionCallback(SocketError socketError) { CompletionCallback(0, socketError); } internal unsafe SocketError DoOperationConnect(Socket socket, SafeCloseSocket handle, out int bytesTransferred) { bytesTransferred = 0; return handle.AsyncContext.ConnectAsync(_socketAddress.Buffer, _socketAddress.Size, ConnectCompletionCallback); } private void InnerStartOperationDisconnect() { throw new PlatformNotSupportedException(); } private void TransferCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError) { Debug.Assert(socketAddress == null || socketAddress == _socketAddress.Buffer); _socketAddressSize = socketAddressSize; _receivedFlags = receivedFlags; CompletionCallback(bytesTransferred, socketError); } private void InnerStartOperationReceive() { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; } internal unsafe SocketError DoOperationReceive(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred) { SocketError errorCode; if (_buffer != null) { errorCode = handle.AsyncContext.ReceiveAsync(_buffer, _offset, _count, _socketFlags, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.ReceiveAsync(_bufferList, _socketFlags, TransferCompletionCallback); } flags = _socketFlags; bytesTransferred = 0; return errorCode; } private void InnerStartOperationReceiveFrom() { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; } internal unsafe SocketError DoOperationReceiveFrom(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred) { SocketError errorCode; if (_buffer != null) { errorCode = handle.AsyncContext.ReceiveFromAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferList, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback); } flags = _socketFlags; bytesTransferred = 0; return errorCode; } private void InnerStartOperationReceiveMessageFrom() { _receiveMessageFromPacketInfo = default(IPPacketInformation); _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; } private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode) { Debug.Assert(_socketAddress != null); Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress); _socketAddressSize = socketAddressSize; _receivedFlags = receivedFlags; _receiveMessageFromPacketInfo = ipPacketInformation; CompletionCallback(bytesTransferred, errorCode); } internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle, out int bytesTransferred) { bool isIPv4, isIPv6; Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress, out isIPv4, out isIPv6); bytesTransferred = 0; return handle.AsyncContext.ReceiveMessageFromAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, isIPv4, isIPv6, ReceiveMessageFromCompletionCallback); } private void InnerStartOperationSend() { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; } internal unsafe SocketError DoOperationSend(SafeCloseSocket handle, out int bytesTransferred) { SocketError errorCode; if (_buffer != null) { errorCode = handle.AsyncContext.SendAsync(_buffer, _offset, _count, _socketFlags, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.SendAsync(_bufferList, _socketFlags, TransferCompletionCallback); } bytesTransferred = 0; return errorCode; } private void InnerStartOperationSendPackets() { throw new PlatformNotSupportedException(); } internal SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle) { throw new PlatformNotSupportedException(); } private void InnerStartOperationSendTo() { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; } internal SocketError DoOperationSendTo(SafeCloseSocket handle, out int bytesTransferred) { SocketError errorCode; if (_buffer != null) { errorCode = handle.AsyncContext.SendToAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.SendToAsync(_bufferList, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback); } bytesTransferred = 0; return errorCode; } internal void LogBuffer(int size) { // TODO: implement? } internal void LogSendPacketsBuffers(int size) { throw new PlatformNotSupportedException(); } private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress) { System.Buffer.BlockCopy(_acceptBuffer, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount); _acceptSocket = _currentSocket.CreateAcceptSocket( SafeCloseSocket.CreateSocket(_acceptedFileDescriptor), _currentSocket._rightEndPoint.Create(remoteSocketAddress)); return SocketError.Success; } private SocketError FinishOperationConnect() { // No-op for *nix. return SocketError.Success; } private unsafe int GetSocketAddressSize() { return _socketAddressSize; } private unsafe void FinishOperationReceiveMessageFrom() { // No-op for *nix. } private void FinishOperationSendPackets() { throw new PlatformNotSupportedException(); } private void CompletionCallback(int bytesTransferred, SocketError socketError) { // TODO: plumb SocketFlags through TransferOperation if (socketError == SocketError.Success) { FinishOperationSuccess(socketError, bytesTransferred, _receivedFlags); } else { if (_currentSocket.CleanedUp) { socketError = SocketError.OperationAborted; } FinishOperationAsyncFailure(socketError, bytesTransferred, _receivedFlags); } } } }
using System; using System.Text; using System.Runtime.Serialization; using Newtonsoft.Json; namespace HETSAPI.ViewModels { /// <summary> /// Notification View Model /// </summary> [DataContract] public sealed class NotificationViewModel : IEquatable<NotificationViewModel> { /// <summary> /// Notification View Model Constructor /// </summary> public NotificationViewModel() { } /// <summary> /// Initializes a new instance of the <see cref="NotificationViewModel" /> class. /// </summary> /// <param name="id">Id.</param> /// <param name="eventId">EventId.</param> /// <param name="event2Id">Event2Id.</param> /// <param name="hasBeenViewed">HasBeenViewed.</param> /// <param name="isWatchNotification">IsWatchNotification.</param> /// <param name="isExpired">IsExpired.</param> /// <param name="isAllDay">IsAllDay.</param> /// <param name="priorityCode">PriorityCode.</param> /// <param name="userId">UserId.</param> public NotificationViewModel(int id, int? eventId = null, int? event2Id = null, bool? hasBeenViewed = null, bool? isWatchNotification = null, bool? isExpired = null, bool? isAllDay = null, string priorityCode = null, int? userId = null) { Id = id; EventId = eventId; Event2Id = event2Id; HasBeenViewed = hasBeenViewed; IsWatchNotification = isWatchNotification; IsExpired = isExpired; IsAllDay = isAllDay; PriorityCode = priorityCode; UserId = userId; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id")] public int? Id { get; set; } /// <summary> /// Gets or Sets EventId /// </summary> [DataMember(Name="eventId")] public int? EventId { get; set; } /// <summary> /// Gets or Sets Event2Id /// </summary> [DataMember(Name="event2Id")] public int? Event2Id { get; set; } /// <summary> /// Gets or Sets HasBeenViewed /// </summary> [DataMember(Name="hasBeenViewed")] public bool? HasBeenViewed { get; set; } /// <summary> /// Gets or Sets IsWatchNotification /// </summary> [DataMember(Name="isWatchNotification")] public bool? IsWatchNotification { get; set; } /// <summary> /// Gets or Sets IsExpired /// </summary> [DataMember(Name="isExpired")] public bool? IsExpired { get; set; } /// <summary> /// Gets or Sets IsAllDay /// </summary> [DataMember(Name="isAllDay")] public bool? IsAllDay { get; set; } /// <summary> /// Gets or Sets PriorityCode /// </summary> [DataMember(Name="priorityCode")] public string PriorityCode { get; set; } /// <summary> /// Gets or Sets UserId /// </summary> [DataMember(Name="userId")] public int? UserId { 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 NotificationViewModel {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" EventId: ").Append(EventId).Append("\n"); sb.Append(" Event2Id: ").Append(Event2Id).Append("\n"); sb.Append(" HasBeenViewed: ").Append(HasBeenViewed).Append("\n"); sb.Append(" IsWatchNotification: ").Append(IsWatchNotification).Append("\n"); sb.Append(" IsExpired: ").Append(IsExpired).Append("\n"); sb.Append(" IsAllDay: ").Append(IsAllDay).Append("\n"); sb.Append(" PriorityCode: ").Append(PriorityCode).Append("\n"); sb.Append(" UserId: ").Append(UserId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((NotificationViewModel)obj); } /// <summary> /// Returns true if NotificationViewModel instances are equal /// </summary> /// <param name="other">Instance of NotificationViewModel to be compared</param> /// <returns>Boolean</returns> public bool Equals(NotificationViewModel other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( Id == other.Id || Id != null && Id.Equals(other.Id) ) && ( EventId == other.EventId || EventId != null && EventId.Equals(other.EventId) ) && ( Event2Id == other.Event2Id || Event2Id != null && Event2Id.Equals(other.Event2Id) ) && ( HasBeenViewed == other.HasBeenViewed || HasBeenViewed != null && HasBeenViewed.Equals(other.HasBeenViewed) ) && ( IsWatchNotification == other.IsWatchNotification || IsWatchNotification != null && IsWatchNotification.Equals(other.IsWatchNotification) ) && ( IsExpired == other.IsExpired || IsExpired != null && IsExpired.Equals(other.IsExpired) ) && ( IsAllDay == other.IsAllDay || IsAllDay != null && IsAllDay.Equals(other.IsAllDay) ) && ( PriorityCode == other.PriorityCode || PriorityCode != null && PriorityCode.Equals(other.PriorityCode) ) && ( UserId == other.UserId || UserId != null && UserId.Equals(other.UserId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks if (Id != null) { hash = hash * 59 + Id.GetHashCode(); } if (EventId != null) { hash = hash * 59 + EventId.GetHashCode(); } if (Event2Id != null) { hash = hash * 59 + Event2Id.GetHashCode(); } if (HasBeenViewed != null) { hash = hash * 59 + HasBeenViewed.GetHashCode(); } if (IsWatchNotification != null) { hash = hash * 59 + IsWatchNotification.GetHashCode(); } if (IsExpired != null) { hash = hash * 59 + IsExpired.GetHashCode(); } if (IsAllDay != null) { hash = hash * 59 + IsAllDay.GetHashCode(); } if (PriorityCode != null) { hash = hash * 59 + PriorityCode.GetHashCode(); } if (UserId != null) { hash = hash * 59 + UserId.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(NotificationViewModel left, NotificationViewModel right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(NotificationViewModel left, NotificationViewModel right) { return !Equals(left, right); } #endregion Operators } }
using Content.Server.Actions; using Content.Server.Light.Components; using Content.Server.Popups; using Content.Server.PowerCell; using Content.Shared.Actions; using Content.Shared.Examine; using Content.Shared.Interaction; using Content.Shared.Item; using Content.Shared.Light.Component; using Content.Shared.Rounding; using Content.Shared.Toggleable; using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameStates; using Robust.Shared.Player; using Robust.Shared.Utility; namespace Content.Server.Light.EntitySystems { [UsedImplicitly] public sealed class HandheldLightSystem : EntitySystem { [Dependency] private readonly PopupSystem _popup = default!; [Dependency] private readonly PowerCellSystem _powerCell = default!; [Dependency] private readonly ActionsSystem _actionSystem = default!; // TODO: Ideally you'd be able to subscribe to power stuff to get events at certain percentages.. or something? // But for now this will be better anyway. private readonly HashSet<HandheldLightComponent> _activeLights = new(); public override void Initialize() { base.Initialize(); SubscribeLocalEvent<HandheldLightComponent, ComponentInit>(OnInit); SubscribeLocalEvent<HandheldLightComponent, ComponentRemove>(OnRemove); SubscribeLocalEvent<HandheldLightComponent, ComponentGetState>(OnGetState); SubscribeLocalEvent<HandheldLightComponent, ExaminedEvent>(OnExamine); SubscribeLocalEvent<HandheldLightComponent, GetVerbsEvent<ActivationVerb>>(AddToggleLightVerb); SubscribeLocalEvent<HandheldLightComponent, ActivateInWorldEvent>(OnActivate); SubscribeLocalEvent<HandheldLightComponent, GetActionsEvent>(OnGetActions); SubscribeLocalEvent<HandheldLightComponent, ToggleActionEvent>(OnToggleAction); } private void OnGetActions(EntityUid uid, HandheldLightComponent component, GetActionsEvent args) { args.Actions.Add(component.ToggleAction); } private void OnToggleAction(EntityUid uid, HandheldLightComponent component, ToggleActionEvent args) { if (args.Handled) return; if (component.Activated) TurnOff(component); else TurnOn(args.Performer, component); args.Handled = true; } private void OnGetState(EntityUid uid, HandheldLightComponent component, ref ComponentGetState args) { args.State = new SharedHandheldLightComponent.HandheldLightComponentState(GetLevel(component)); } private byte? GetLevel(HandheldLightComponent component) { // Curently every single flashlight has the same number of levels for status and that's all it uses the charge for // Thus we'll just check if the level changes. if (!_powerCell.TryGetBatteryFromSlot(component.Owner, out var battery)) return null; if (MathHelper.CloseToPercent(battery.CurrentCharge, 0) || component.Wattage > battery.CurrentCharge) return 0; return (byte?) ContentHelpers.RoundToNearestLevels(battery.CurrentCharge / battery.MaxCharge * 255, 255, SharedHandheldLightComponent.StatusLevels); } private void OnInit(EntityUid uid, HandheldLightComponent component, ComponentInit args) { EntityManager.EnsureComponent<PointLightComponent>(uid); // Want to make sure client has latest data on level so battery displays properly. component.Dirty(EntityManager); } private void OnRemove(EntityUid uid, HandheldLightComponent component, ComponentRemove args) { _activeLights.Remove(component); } private void OnActivate(EntityUid uid, HandheldLightComponent component, ActivateInWorldEvent args) { if (args.Handled) return; if (ToggleStatus(args.User, component)) args.Handled = true; } /// <summary> /// Illuminates the light if it is not active, extinguishes it if it is active. /// </summary> /// <returns>True if the light's status was toggled, false otherwise.</returns> public bool ToggleStatus(EntityUid user, HandheldLightComponent component) { return component.Activated ? TurnOff(component) : TurnOn(user, component); } private void OnExamine(EntityUid uid, HandheldLightComponent component, ExaminedEvent args) { args.PushMarkup(component.Activated ? Loc.GetString("handheld-light-component-on-examine-is-on-message") : Loc.GetString("handheld-light-component-on-examine-is-off-message")); } public override void Shutdown() { base.Shutdown(); _activeLights.Clear(); } public override void Update(float frameTime) { var toRemove = new RemQueue<HandheldLightComponent>(); foreach (var handheld in _activeLights) { if (handheld.Deleted) { toRemove.Add(handheld); continue; } if (Paused(handheld.Owner)) continue; TryUpdate(handheld, frameTime); } foreach (var light in toRemove) { _activeLights.Remove(light); } } private void AddToggleLightVerb(EntityUid uid, HandheldLightComponent component, GetVerbsEvent<ActivationVerb> args) { if (!args.CanAccess || !args.CanInteract) return; ActivationVerb verb = new() { Text = Loc.GetString("verb-common-toggle-light"), IconTexture = "/Textures/Interface/VerbIcons/light.svg.192dpi.png", Act = component.Activated ? () => TurnOff(component) : () => TurnOn(args.User, component) }; args.Verbs.Add(verb); } public bool TurnOff(HandheldLightComponent component, bool makeNoise = true) { if (!component.Activated) return false; SetState(component, false); component.Activated = false; _activeLights.Remove(component); component.LastLevel = null; component.Dirty(EntityManager); if (makeNoise) SoundSystem.Play(Filter.Pvs(component.Owner), component.TurnOffSound.GetSound(), component.Owner); return true; } public bool TurnOn(EntityUid user, HandheldLightComponent component) { if (component.Activated) return false; if (!_powerCell.TryGetBatteryFromSlot(component.Owner, out var battery)) { SoundSystem.Play(Filter.Pvs(component.Owner), component.TurnOnFailSound.GetSound(), component.Owner); _popup.PopupEntity(Loc.GetString("handheld-light-component-cell-missing-message"), component.Owner, Filter.Entities(user)); return false; } // To prevent having to worry about frame time in here. // Let's just say you need a whole second of charge before you can turn it on. // Simple enough. if (component.Wattage > battery.CurrentCharge) { SoundSystem.Play(Filter.Pvs(component.Owner), component.TurnOnFailSound.GetSound(), component.Owner); _popup.PopupEntity(Loc.GetString("handheld-light-component-cell-dead-message"), component.Owner, Filter.Entities(user)); return false; } component.Activated = true; SetState(component, true); _activeLights.Add(component); component.LastLevel = GetLevel(component); component.Dirty(EntityManager); SoundSystem.Play(Filter.Pvs(component.Owner), component.TurnOnSound.GetSound(), component.Owner); return true; } private void SetState(HandheldLightComponent component, bool on) { // TODO: Oh dear if (EntityManager.TryGetComponent(component.Owner, out SpriteComponent? sprite)) { sprite.LayerSetVisible(1, on); } if (EntityManager.TryGetComponent(component.Owner, out PointLightComponent? light)) { light.Enabled = on; } if (EntityManager.TryGetComponent(component.Owner, out SharedItemComponent? item)) { item.EquippedPrefix = on ? "on" : "off"; } _actionSystem.SetToggled(component.ToggleAction, on); } public void TryUpdate(HandheldLightComponent component, float frameTime) { if (!_powerCell.TryGetBatteryFromSlot(component.Owner, out var battery)) { TurnOff(component, false); return; } var appearanceComponent = EntityManager.GetComponent<AppearanceComponent>(component.Owner); var fraction = battery.CurrentCharge / battery.MaxCharge; if (fraction >= 0.30) { appearanceComponent.SetData(HandheldLightVisuals.Power, HandheldLightPowerStates.FullPower); } else if (fraction >= 0.10) { appearanceComponent.SetData(HandheldLightVisuals.Power, HandheldLightPowerStates.LowPower); } else { appearanceComponent.SetData(HandheldLightVisuals.Power, HandheldLightPowerStates.Dying); } if (component.Activated && !battery.TryUseCharge(component.Wattage * frameTime)) TurnOff(component, false); var level = GetLevel(component); if (level != component.LastLevel) { component.LastLevel = level; component.Dirty(EntityManager); } } } }
using System; using System.Web.UI; using System.Web.UI.WebControls; using umbraco.interfaces; using umbraco.BusinessLogic; using umbraco.DataLayer; namespace umbraco.editorControls { [Obsolete("IDataType and all other references to the legacy property editors are no longer used this will be removed from the codebase in future versions")] public class DefaultPrevalueEditor : PlaceHolder, IDataPrevalue { // UI controls private TextBox _textbox; private DropDownList _dropdownlist; // referenced datatype private cms.businesslogic.datatype.BaseDataType _datatype; private BaseDataType _datatypeOld; private bool _isEnsured = false; private string _prevalue; private bool _displayTextBox; public static ISqlHelper SqlHelper { get { return Application.SqlHelper; } } /// <summary> /// The default editor for editing the build-in pre values in umbraco /// </summary> /// <param name="DataType">The DataType to be parsed</param> /// <param name="DisplayTextBox">Whether to use the default text box</param> public DefaultPrevalueEditor(cms.businesslogic.datatype.BaseDataType DataType, bool DisplayTextBox) { // state it knows its datatypedefinitionid _displayTextBox = DisplayTextBox; _datatype = DataType; setupChildControls(); } /// <summary> /// For backwards compatibility, should be replaced in your extension with the constructor that /// uses the BaseDataType from the cms.businesslogic.datatype namespace /// </summary> /// <param name="DataType">The DataType to be parsed (note: the BaseDataType from editorControls is obsolete)</param> /// <param name="DisplayTextBox">Whether to use the default text box</param> public DefaultPrevalueEditor(BaseDataType DataType, bool DisplayTextBox) { // state it knows its datatypedefinitionid _displayTextBox = DisplayTextBox; _datatypeOld = DataType; setupChildControls(); } private void setupChildControls() { _dropdownlist = new DropDownList(); _dropdownlist.ID = "dbtype"; _textbox = new TextBox(); _textbox.ID = "prevalues"; _textbox.Visible = _displayTextBox; // put the childcontrols in context - ensuring that // the viewstate is persisted etc. Controls.Add(_textbox); Controls.Add(_dropdownlist); _dropdownlist.Items.Add(DBTypes.Date.ToString()); _dropdownlist.Items.Add(DBTypes.Integer.ToString()); _dropdownlist.Items.Add(DBTypes.Ntext.ToString()); _dropdownlist.Items.Add(DBTypes.Nvarchar.ToString()); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { if (_datatype != null) _dropdownlist.SelectedValue = _datatype.DBType.ToString(); else _dropdownlist.SelectedValue = _datatypeOld.DBType.ToString(); _textbox.Text = Prevalue; } } public string Prevalue { get { ensurePrevalue(); if (_prevalue == null) { int defId; if (_datatype != null) defId = _datatype.DataTypeDefinitionId; else if (_datatypeOld != null) defId = _datatypeOld.DataTypeDefinitionId; else throw new ArgumentException("Datatype is not initialized"); _prevalue = SqlHelper.ExecuteScalar<string>("Select [value] from cmsDataTypePreValues where DataTypeNodeId = " + defId); } return _prevalue; } set { int defId; if (_datatype != null) defId = _datatype.DataTypeDefinitionId; else if (_datatypeOld != null) defId = _datatypeOld.DataTypeDefinitionId; else throw new ArgumentException("Datatype is not initialized"); _prevalue = value; ensurePrevalue(); IParameter[] SqlParams = new IParameter[] { SqlHelper.CreateParameter("@value", _textbox.Text), SqlHelper.CreateParameter("@dtdefid", defId) }; // update prevalue SqlHelper.ExecuteNonQuery("update cmsDataTypePreValues set [value] = @value where datatypeNodeId = @dtdefid", SqlParams); } } private void ensurePrevalue() { if (!_isEnsured) { int defId; if (_datatype != null) defId = _datatype.DataTypeDefinitionId; else if (_datatypeOld != null) defId = _datatypeOld.DataTypeDefinitionId; else throw new ArgumentException("Datatype is not initialized"); bool hasPrevalue = (SqlHelper.ExecuteScalar<int>("select count(id) from cmsDataTypePreValues where dataTypeNodeId = " + defId) > 0); IParameter[] SqlParams = new IParameter[] { SqlHelper.CreateParameter("@value", _textbox.Text), SqlHelper.CreateParameter("@dtdefid", defId) }; if (!hasPrevalue) { SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'')", SqlParams); } _isEnsured = true; } } public Control Editor { get { return this; } } public void Save() { // save the prevalue data and get on with you life ;) if (_datatype != null) _datatype.DBType = (cms.businesslogic.datatype.DBTypes)Enum.Parse(typeof (cms.businesslogic.datatype.DBTypes), _dropdownlist.SelectedValue, true); else if (_datatypeOld != null) _datatypeOld.DBType = (DBTypes)Enum.Parse(typeof (DBTypes), _dropdownlist.SelectedValue, true); if (_displayTextBox) { // If the prevalue editor has an prevalue textbox - save the textbox value as the prevalue Prevalue = _textbox.Text; } } protected override void Render(HtmlTextWriter writer) { writer.Write("<div class='propertyItem'><div class='propertyItemheader'>" + ui.Text("dataBaseDatatype") + "</div>"); _dropdownlist.RenderControl(writer); writer.Write("<br style='clear: both'/></div>"); if (_displayTextBox) { writer.Write("<div class='propertyItem'><div class='propertyItemheader'>" + ui.Text("prevalue") + "</div>"); _textbox.RenderControl(writer); writer.Write("<br style='clear: both'/></div>"); } /* writer.WriteLine("<div class='propertyItem'>"); writer.WriteLine("<tr><td>Database datatype</td><td>"); _dropdownlist.RenderControl(writer); writer.Write("</td></tr>"); if (_displayTextBox) writer.WriteLine("<tr><td>Prevalue: </td><td>"); _textbox.RenderControl(writer); writer.WriteLine("</td></tr>"); writer.Write("</div>"); */ } public static string GetPrevalueFromId(int Id) { return SqlHelper.ExecuteScalar<string>("Select [value] from cmsDataTypePreValues where id = @id", SqlHelper.CreateParameter("@id", Id)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // // zlib.h -- interface of the 'zlib' general purpose compression library // version 1.2.1, November 17th, 2003 // // Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // using System; using System.Diagnostics; namespace System.IO.Compression { internal class Inflater { // const tables used in decoding: // Extra bits for length code 257 - 285. private static readonly byte[] s_extraLengthBits = { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; // The base length for length code 257 - 285. // The formula to get the real length for a length code is lengthBase[code - 257] + (value stored in extraBits) private static readonly int[] s_lengthBase = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258}; // The base distance for distance code 0 - 29 // The real distance for a distance code is distanceBasePosition[code] + (value stored in extraBits) private static readonly int[] s_distanceBasePosition = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; // code lengths for code length alphabet is stored in following order private static readonly byte[] s_codeOrder = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; private static readonly byte[] s_staticDistanceTreeTable = { 0x00,0x10,0x08,0x18,0x04,0x14,0x0c,0x1c,0x02,0x12,0x0a,0x1a, 0x06,0x16,0x0e,0x1e,0x01,0x11,0x09,0x19,0x05,0x15,0x0d,0x1d, 0x03,0x13,0x0b,0x1b,0x07,0x17,0x0f,0x1f, }; private OutputWindow _output; private InputBuffer _input; private HuffmanTree _literalLengthTree; private HuffmanTree _distanceTree; private InflaterState _state; private bool _hasFormatReader; private int _bfinal; private BlockType _blockType; // uncompressed block private byte[] _blockLengthBuffer = new byte[4]; private int _blockLength; // compressed block private int _length; private int _distanceCode; private int _extraBits; private int _loopCounter; private int _literalLengthCodeCount; private int _distanceCodeCount; private int _codeLengthCodeCount; private int _codeArraySize; private int _lengthCode; private byte[] _codeList; // temporary array to store the code length for literal/Length and distance private byte[] _codeLengthTreeCodeLength; private HuffmanTree _codeLengthTree; private IFileFormatReader _formatReader; // class to decode header and footer (e.g. gzip) public Inflater() { _output = new OutputWindow(); _input = new InputBuffer(); _codeList = new byte[HuffmanTree.MaxLiteralTreeElements + HuffmanTree.MaxDistTreeElements]; _codeLengthTreeCodeLength = new byte[HuffmanTree.NumberOfCodeLengthTreeElements]; Reset(); } internal void SetFileFormatReader(IFileFormatReader reader) { _formatReader = reader; _hasFormatReader = true; Reset(); } private void Reset() { if (_hasFormatReader) { _state = InflaterState.ReadingHeader; // start by reading Header info } else { _state = InflaterState.ReadingBFinal; // start by reading BFinal bit } } public void SetInput(byte[] inputBytes, int offset, int length) { _input.SetInput(inputBytes, offset, length); // append the bytes } public bool Finished() { return (_state == InflaterState.Done || _state == InflaterState.VerifyingFooter); } public int AvailableOutput { get { return _output.AvailableBytes; } } public bool NeedsInput() { return _input.NeedsInput(); } public int Inflate(byte[] bytes, int offset, int length) { // copy bytes from output to outputbytes if we have aviable bytes // if buffer is not filled up. keep decoding until no input are available // if decodeBlock returns false. Throw an exception. int count = 0; do { int copied = _output.CopyTo(bytes, offset, length); if (copied > 0) { if (_hasFormatReader) { _formatReader.UpdateWithBytesRead(bytes, offset, copied); } offset += copied; count += copied; length -= copied; } if (length == 0) { // filled in the bytes array break; } // Decode will return false when more input is needed } while (!Finished() && Decode()); if (_state == InflaterState.VerifyingFooter) { // finished reading CRC // In this case finished is true and output window has all the data. // But some data in output window might not be copied out. if (_output.AvailableBytes == 0) { _formatReader.Validate(); } } return count; } //Each block of compressed data begins with 3 header bits // containing the following data: // first bit BFINAL // next 2 bits BTYPE // Note that the header bits do not necessarily begin on a byte // boundary, since a block does not necessarily occupy an integral // number of bytes. // BFINAL is set if and only if this is the last block of the data // set. // BTYPE specifies how the data are compressed, as follows: // 00 - no compression // 01 - compressed with fixed Huffman codes // 10 - compressed with dynamic Huffman codes // 11 - reserved (error) // The only difference between the two compressed cases is how the // Huffman codes for the literal/length and distance alphabets are // defined. // // This function returns true for success (end of block or output window is full,) // false if we are short of input // private bool Decode() { bool eob = false; bool result = false; if (Finished()) { return true; } if (_hasFormatReader) { if (_state == InflaterState.ReadingHeader) { if (!_formatReader.ReadHeader(_input)) { return false; } _state = InflaterState.ReadingBFinal; } else if (_state == InflaterState.StartReadingFooter || _state == InflaterState.ReadingFooter) { if (!_formatReader.ReadFooter(_input)) return false; _state = InflaterState.VerifyingFooter; return true; } } if (_state == InflaterState.ReadingBFinal) { // reading bfinal bit // Need 1 bit if (!_input.EnsureBitsAvailable(1)) return false; _bfinal = _input.GetBits(1); _state = InflaterState.ReadingBType; } if (_state == InflaterState.ReadingBType) { // Need 2 bits if (!_input.EnsureBitsAvailable(2)) { _state = InflaterState.ReadingBType; return false; } _blockType = (BlockType)_input.GetBits(2); if (_blockType == BlockType.Dynamic) { _state = InflaterState.ReadingNumLitCodes; } else if (_blockType == BlockType.Static) { _literalLengthTree = HuffmanTree.StaticLiteralLengthTree; _distanceTree = HuffmanTree.StaticDistanceTree; _state = InflaterState.DecodeTop; } else if (_blockType == BlockType.Uncompressed) { _state = InflaterState.UncompressedAligning; } else { throw new InvalidDataException(SR.UnknownBlockType); } } if (_blockType == BlockType.Dynamic) { if (_state < InflaterState.DecodeTop) { // we are reading the header result = DecodeDynamicBlockHeader(); } else { result = DecodeBlock(out eob); // this can returns true when output is full } } else if (_blockType == BlockType.Static) { result = DecodeBlock(out eob); } else if (_blockType == BlockType.Uncompressed) { result = DecodeUncompressedBlock(out eob); } else { throw new InvalidDataException(SR.UnknownBlockType); } // // If we reached the end of the block and the block we were decoding had // bfinal=1 (final block) // if (eob && (_bfinal != 0)) { if (_hasFormatReader) _state = InflaterState.StartReadingFooter; else _state = InflaterState.Done; } return result; } // Format of Non-compressed blocks (BTYPE=00): // // Any bits of input up to the next byte boundary are ignored. // The rest of the block consists of the following information: // // 0 1 2 3 4... // +---+---+---+---+================================+ // | LEN | NLEN |... LEN bytes of literal data...| // +---+---+---+---+================================+ // // LEN is the number of data bytes in the block. NLEN is the // one's complement of LEN. private bool DecodeUncompressedBlock(out bool end_of_block) { end_of_block = false; while (true) { switch (_state) { case InflaterState.UncompressedAligning: // intial state when calling this function // we must skip to a byte boundary _input.SkipToByteBoundary(); _state = InflaterState.UncompressedByte1; goto case InflaterState.UncompressedByte1; case InflaterState.UncompressedByte1: // decoding block length case InflaterState.UncompressedByte2: case InflaterState.UncompressedByte3: case InflaterState.UncompressedByte4: int bits = _input.GetBits(8); if (bits < 0) { return false; } _blockLengthBuffer[_state - InflaterState.UncompressedByte1] = (byte)bits; if (_state == InflaterState.UncompressedByte4) { _blockLength = _blockLengthBuffer[0] + ((int)_blockLengthBuffer[1]) * 256; int blockLengthComplement = _blockLengthBuffer[2] + ((int)_blockLengthBuffer[3]) * 256; // make sure complement matches if ((ushort)_blockLength != (ushort)(~blockLengthComplement)) { throw new InvalidDataException(SR.InvalidBlockLength); } } _state += 1; break; case InflaterState.DecodingUncompressed: // copying block data // Directly copy bytes from input to output. int bytesCopied = _output.CopyFrom(_input, _blockLength); _blockLength -= bytesCopied; if (_blockLength == 0) { // Done with this block, need to re-init bit buffer for next block _state = InflaterState.ReadingBFinal; end_of_block = true; return true; } // We can fail to copy all bytes for two reasons: // Running out of Input // running out of free space in output window if (_output.FreeBytes == 0) { return true; } return false; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.UnknownState); } } } private bool DecodeBlock(out bool end_of_block_code_seen) { end_of_block_code_seen = false; int freeBytes = _output.FreeBytes; // it is a little bit faster than frequently accessing the property while (freeBytes > 258) { // 258 means we can safely do decoding since maximum repeat length is 258 int symbol; switch (_state) { case InflaterState.DecodeTop: // decode an element from the literal tree // TODO: optimize this!!! symbol = _literalLengthTree.GetNextSymbol(_input); if (symbol < 0) { // running out of input return false; } if (symbol < 256) { // literal _output.Write((byte)symbol); --freeBytes; } else if (symbol == 256) { // end of block end_of_block_code_seen = true; // Reset state _state = InflaterState.ReadingBFinal; return true; // *********** } else { // length/distance pair symbol -= 257; // length code started at 257 if (symbol < 8) { symbol += 3; // match length = 3,4,5,6,7,8,9,10 _extraBits = 0; } else if (symbol == 28) { // extra bits for code 285 is 0 symbol = 258; // code 285 means length 258 _extraBits = 0; } else { if (symbol < 0 || symbol >= s_extraLengthBits.Length) { throw new InvalidDataException(SR.GenericInvalidData); } _extraBits = s_extraLengthBits[symbol]; Debug.Assert(_extraBits != 0, "We handle other cases seperately!"); } _length = symbol; goto case InflaterState.HaveInitialLength; } break; case InflaterState.HaveInitialLength: if (_extraBits > 0) { _state = InflaterState.HaveInitialLength; int bits = _input.GetBits(_extraBits); if (bits < 0) { return false; } if (_length < 0 || _length >= s_lengthBase.Length) { throw new InvalidDataException(SR.GenericInvalidData); } _length = s_lengthBase[_length] + bits; } _state = InflaterState.HaveFullLength; goto case InflaterState.HaveFullLength; case InflaterState.HaveFullLength: if (_blockType == BlockType.Dynamic) { _distanceCode = _distanceTree.GetNextSymbol(_input); } else { // get distance code directly for static block _distanceCode = _input.GetBits(5); if (_distanceCode >= 0) { _distanceCode = s_staticDistanceTreeTable[_distanceCode]; } } if (_distanceCode < 0) { // running out input return false; } _state = InflaterState.HaveDistCode; goto case InflaterState.HaveDistCode; case InflaterState.HaveDistCode: // To avoid a table lookup we note that for distanceCode >= 2, // extra_bits = (distanceCode-2) >> 1 int offset; if (_distanceCode > 3) { _extraBits = (_distanceCode - 2) >> 1; int bits = _input.GetBits(_extraBits); if (bits < 0) { return false; } offset = s_distanceBasePosition[_distanceCode] + bits; } else { offset = _distanceCode + 1; } Debug.Assert(freeBytes >= 258, "following operation is not safe!"); _output.WriteLengthDistance(_length, offset); freeBytes -= _length; _state = InflaterState.DecodeTop; break; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.UnknownState); } } return true; } // Format of the dynamic block header: // 5 Bits: HLIT, # of Literal/Length codes - 257 (257 - 286) // 5 Bits: HDIST, # of Distance codes - 1 (1 - 32) // 4 Bits: HCLEN, # of Code Length codes - 4 (4 - 19) // // (HCLEN + 4) x 3 bits: code lengths for the code length // alphabet given just above, in the order: 16, 17, 18, // 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 // // These code lengths are interpreted as 3-bit integers // (0-7); as above, a code length of 0 means the // corresponding symbol (literal/length or distance code // length) is not used. // // HLIT + 257 code lengths for the literal/length alphabet, // encoded using the code length Huffman code // // HDIST + 1 code lengths for the distance alphabet, // encoded using the code length Huffman code // // The code length repeat codes can cross from HLIT + 257 to the // HDIST + 1 code lengths. In other words, all code lengths form // a single sequence of HLIT + HDIST + 258 values. private bool DecodeDynamicBlockHeader() { switch (_state) { case InflaterState.ReadingNumLitCodes: _literalLengthCodeCount = _input.GetBits(5); if (_literalLengthCodeCount < 0) { return false; } _literalLengthCodeCount += 257; _state = InflaterState.ReadingNumDistCodes; goto case InflaterState.ReadingNumDistCodes; case InflaterState.ReadingNumDistCodes: _distanceCodeCount = _input.GetBits(5); if (_distanceCodeCount < 0) { return false; } _distanceCodeCount += 1; _state = InflaterState.ReadingNumCodeLengthCodes; goto case InflaterState.ReadingNumCodeLengthCodes; case InflaterState.ReadingNumCodeLengthCodes: _codeLengthCodeCount = _input.GetBits(4); if (_codeLengthCodeCount < 0) { return false; } _codeLengthCodeCount += 4; _loopCounter = 0; _state = InflaterState.ReadingCodeLengthCodes; goto case InflaterState.ReadingCodeLengthCodes; case InflaterState.ReadingCodeLengthCodes: while (_loopCounter < _codeLengthCodeCount) { int bits = _input.GetBits(3); if (bits < 0) { return false; } _codeLengthTreeCodeLength[s_codeOrder[_loopCounter]] = (byte)bits; ++_loopCounter; } for (int i = _codeLengthCodeCount; i < s_codeOrder.Length; i++) { _codeLengthTreeCodeLength[s_codeOrder[i]] = 0; } // create huffman tree for code length _codeLengthTree = new HuffmanTree(_codeLengthTreeCodeLength); _codeArraySize = _literalLengthCodeCount + _distanceCodeCount; _loopCounter = 0; // reset loop count _state = InflaterState.ReadingTreeCodesBefore; goto case InflaterState.ReadingTreeCodesBefore; case InflaterState.ReadingTreeCodesBefore: case InflaterState.ReadingTreeCodesAfter: while (_loopCounter < _codeArraySize) { if (_state == InflaterState.ReadingTreeCodesBefore) { if ((_lengthCode = _codeLengthTree.GetNextSymbol(_input)) < 0) { return false; } } // The alphabet for code lengths is as follows: // 0 - 15: Represent code lengths of 0 - 15 // 16: Copy the previous code length 3 - 6 times. // The next 2 bits indicate repeat length // (0 = 3, ... , 3 = 6) // Example: Codes 8, 16 (+2 bits 11), // 16 (+2 bits 10) will expand to // 12 code lengths of 8 (1 + 6 + 5) // 17: Repeat a code length of 0 for 3 - 10 times. // (3 bits of length) // 18: Repeat a code length of 0 for 11 - 138 times // (7 bits of length) if (_lengthCode <= 15) { _codeList[_loopCounter++] = (byte)_lengthCode; } else { if (!_input.EnsureBitsAvailable(7)) { // it doesn't matter if we require more bits here _state = InflaterState.ReadingTreeCodesAfter; return false; } int repeatCount; if (_lengthCode == 16) { if (_loopCounter == 0) { // can't have "prev code" on first code throw new InvalidDataException(); } byte previousCode = _codeList[_loopCounter - 1]; repeatCount = _input.GetBits(2) + 3; if (_loopCounter + repeatCount > _codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { _codeList[_loopCounter++] = previousCode; } } else if (_lengthCode == 17) { repeatCount = _input.GetBits(3) + 3; if (_loopCounter + repeatCount > _codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { _codeList[_loopCounter++] = 0; } } else { // code == 18 repeatCount = _input.GetBits(7) + 11; if (_loopCounter + repeatCount > _codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { _codeList[_loopCounter++] = 0; } } } _state = InflaterState.ReadingTreeCodesBefore; // we want to read the next code. } break; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.UnknownState); } byte[] literalTreeCodeLength = new byte[HuffmanTree.MaxLiteralTreeElements]; byte[] distanceTreeCodeLength = new byte[HuffmanTree.MaxDistTreeElements]; // Create literal and distance tables Array.Copy(_codeList, literalTreeCodeLength, _literalLengthCodeCount); Array.Copy(_codeList, _literalLengthCodeCount, distanceTreeCodeLength, 0, _distanceCodeCount); // Make sure there is an end-of-block code, otherwise how could we ever end? if (literalTreeCodeLength[HuffmanTree.EndOfBlockCode] == 0) { throw new InvalidDataException(); } _literalLengthTree = new HuffmanTree(literalTreeCodeLength); _distanceTree = new HuffmanTree(distanceTreeCodeLength); _state = InflaterState.DecodeTop; return true; } } }
using GalaSoft.MvvmLight; using JiraAssistant.Logic.Services; using System.Collections.Generic; using System.Threading.Tasks; using GalaSoft.MvvmLight.Threading; using GalaSoft.MvvmLight.Command; using JiraAssistant.Logic.Services.Jira; using System.Collections.ObjectModel; using System.Windows; using System.ComponentModel; using JiraAssistant.Logic.Services.Daemons; using JiraAssistant.Domain.Ui; using JiraAssistant.Logic.Settings; using JiraAssistant.Domain.Exceptions; using GalaSoft.MvvmLight.Messaging; using JiraAssistant.Domain.NavigationMessages; using System.Reflection; namespace JiraAssistant.Logic.ContextlessViewModels { public class MainViewModel : ViewModelBase, INavigator { private readonly Stack<INavigationPage> _navigationHistory = new Stack<INavigationPage>(); private INavigationPage _currentPage; private AnimationState _collapseAnimationState; private AnimationState _expandAnimationState; private readonly IJiraApi _jiraApi; private string _userMessage; private Visibility _windowVisibility; private readonly IMessenger _messenger; public MainViewModel(IJiraApi jiraApi, GeneralSettings settings, WorkLogUpdater workLogUpdater, IMessenger messenger) { _jiraApi = jiraApi; _messenger = messenger; Settings = settings; BackCommand = new RelayCommand(Back, () => _navigationHistory.Count > 1); ClearMessageCommand = new RelayCommand(() => { UserMessage = ""; }); OpenSettingsCommand = new RelayCommand(OpenSettings, () => _navigationHistory.Count > 1 && _navigationHistory.Peek().GetType().Name != "ApplicationSettings"); LogWorkCommand = workLogUpdater.LogWorkCommand; BackToPageCommand = new RelayCommand<NavigationHistoryEntry>(BackToPage); CloseApplicationCommand = new RelayCommand(CloseApplication); OpenRecentUpdatesCommand = new RelayCommand(OpenRecentUpdates); ActivateWindowCommand = new RelayCommand(() => WindowVisibility = Visibility.Visible); NavigationHistory = new ObservableCollection<NavigationHistoryEntry>(); } private void OpenRecentUpdates() { _messenger.Send(new OpenRecentUpdatesMessage()); } private void OpenSettings() { _messenger.Send(new OpenSettingsMessage()); } private void CloseApplication() { Application.Current.Shutdown(); } public RelayCommand BackCommand { get; private set; } public RelayCommand ClearMessageCommand { get; private set; } public AnimationState CollapseAnimationState { get { return _collapseAnimationState; } set { _collapseAnimationState = value; RaisePropertyChanged(); } } public AnimationState ExpandAnimationState { get { return _expandAnimationState; } set { _expandAnimationState = value; RaisePropertyChanged(); } } public INavigationPage CurrentPage { get { return _currentPage; } set { _currentPage = value; RaisePropertyChanged(); } } public string ApplicationTitle { get { return string.Format("Jira Assistant - {0}", Assembly.GetEntryAssembly().GetName().Version.ToString(3)); } } public string UserMessage { get { return _userMessage; } set { _userMessage = value; RaisePropertyChanged(); } } public RelayCommand OpenSettingsCommand { get; private set; } public ObservableCollection<NavigationHistoryEntry> NavigationHistory { get; private set; } public RelayCommand<NavigationHistoryEntry> BackToPageCommand { get; private set; } public GeneralSettings Settings { get; private set; } public Visibility WindowVisibility { get { return _windowVisibility; } set { _windowVisibility = value; RaisePropertyChanged(); } } public RelayCommand ActivateWindowCommand { get; private set; } public RelayCommand LogWorkCommand { get; private set; } public RelayCommand CloseApplicationCommand { get; private set; } public RelayCommand OpenRecentUpdatesCommand { get; private set; } private async void BackToPage(NavigationHistoryEntry entry) { if (entry.Page.Title.Contains("Log out")) await _jiraApi.Session.Logout(); if (_navigationHistory.Peek() == entry.Page) return; while (_navigationHistory.Peek() != entry.Page) { _navigationHistory.Pop(); NavigationHistory.RemoveAt(0); } await SetPage(); } public async void Back() { if (_navigationHistory.Count == 1) return; _navigationHistory.Pop(); NavigationHistory.RemoveAt(0); if (_navigationHistory.Count == 1) { try { await _jiraApi.Session.Logout(); } catch (IncompleteJiraConfiguration) { } } await SetPage(); } public async void NavigateTo(INavigationPage page) { _navigationHistory.Push(page); NavigationHistory.Insert(0, new NavigationHistoryEntry(page)); await SetPage(); } public async Task SetPage() { CollapseTab(); await Task.Factory.StartNew(() => { DispatcherHelper.CheckBeginInvokeOnUI(() => { if (CurrentPage != null) CurrentPage.OnNavigatedFrom(); }); }); await Task.Delay(250); await Task.Factory.StartNew(() => { DispatcherHelper.CheckBeginInvokeOnUI(() => { CurrentPage = _navigationHistory.Peek(); }); }); await Task.Delay(200); ExpandTab(); await Task.Factory.StartNew(() => { DispatcherHelper.CheckBeginInvokeOnUI(() => { CurrentPage.OnNavigatedTo(); BackCommand.RaiseCanExecuteChanged(); OpenSettingsCommand.RaiseCanExecuteChanged(); }); }); } private void ExpandTab() { ExpandAnimationState = AnimationState.Stop; ExpandAnimationState = AnimationState.Play; } private void CollapseTab() { CollapseAnimationState = AnimationState.Stop; CollapseAnimationState = AnimationState.Play; } public async void ClearHistory() { while (_navigationHistory.Count > 1) { _navigationHistory.Pop(); NavigationHistory.RemoveAt(0); } await SetPage(); } public void HandleClosing(CancelEventArgs args) { if (Settings.CloseToTray) { WindowVisibility = Visibility.Hidden; args.Cancel = true; } } } public class NavigationHistoryEntry { public NavigationHistoryEntry(INavigationPage page) { Page = page; } public INavigationPage Page { get; private set; } public string Title { get { return Page.Title; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable warnings #nullable enable annotations using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.ExceptionServices; #if ActivatorUtilities_In_DependencyInjection using Microsoft.Extensions.Internal; namespace Microsoft.Extensions.DependencyInjection #else namespace Microsoft.Extensions.Internal #endif { /// <summary> /// Helper code for the various activator services. /// </summary> #if ActivatorUtilities_In_DependencyInjection public #else // Do not take a dependency on this class unless you are explicitly trying to avoid taking a // dependency on Microsoft.AspNetCore.DependencyInjection.Abstractions. internal #endif static class ActivatorUtilities { private static readonly MethodInfo GetServiceInfo = GetMethodInfo<Func<IServiceProvider, Type, Type, bool, object>>((sp, t, r, c) => GetService(sp, t, r, c)); /// <summary> /// Instantiate a type with constructor arguments provided directly and/or from an <see cref="IServiceProvider"/>. /// </summary> /// <param name="provider">The service provider used to resolve dependencies</param> /// <param name="instanceType">The type to activate</param> /// <param name="parameters">Constructor arguments not provided by the <paramref name="provider"/>.</param> /// <returns>An activated object of type instanceType</returns> public static object CreateInstance(IServiceProvider provider, Type instanceType, params object[] parameters) { int bestLength = -1; var seenPreferred = false; ConstructorMatcher bestMatcher = default; if (!instanceType.IsAbstract) { foreach (var constructor in instanceType.GetConstructors()) { var matcher = new ConstructorMatcher(constructor); var isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false); var length = matcher.Match(parameters); if (isPreferred) { if (seenPreferred) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (length == -1) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } } if (isPreferred || bestLength < length) { bestLength = length; bestMatcher = matcher; } seenPreferred |= isPreferred; } } if (bestLength == -1) { var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor."; throw new InvalidOperationException(message); } return bestMatcher.CreateInstance(provider); } /// <summary> /// Create a delegate that will instantiate a type with constructor arguments provided directly /// and/or from an <see cref="IServiceProvider"/>. /// </summary> /// <param name="instanceType">The type to activate</param> /// <param name="argumentTypes"> /// The types of objects, in order, that will be passed to the returned function as its second parameter /// </param> /// <returns> /// A factory that will instantiate instanceType using an <see cref="IServiceProvider"/> /// and an argument array containing objects matching the types defined in argumentTypes /// </returns> public static ObjectFactory CreateFactory(Type instanceType, Type[] argumentTypes) { FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructor, out int?[] parameterMap); var provider = Expression.Parameter(typeof(IServiceProvider), "provider"); var argumentArray = Expression.Parameter(typeof(object[]), "argumentArray"); var factoryExpressionBody = BuildFactoryExpression(constructor, parameterMap, provider, argumentArray); var factoryLamda = Expression.Lambda<Func<IServiceProvider, object[], object>>( factoryExpressionBody, provider, argumentArray); var result = factoryLamda.Compile(); return result.Invoke; } /// <summary> /// Instantiate a type with constructor arguments provided directly and/or from an <see cref="IServiceProvider"/>. /// </summary> /// <typeparam name="T">The type to activate</typeparam> /// <param name="provider">The service provider used to resolve dependencies</param> /// <param name="parameters">Constructor arguments not provided by the <paramref name="provider"/>.</param> /// <returns>An activated object of type T</returns> public static T CreateInstance<T>(IServiceProvider provider, params object[] parameters) { return (T)CreateInstance(provider, typeof(T), parameters); } /// <summary> /// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly. /// </summary> /// <typeparam name="T">The type of the service</typeparam> /// <param name="provider">The service provider used to resolve dependencies</param> /// <returns>The resolved service or created instance</returns> public static T GetServiceOrCreateInstance<T>(IServiceProvider provider) { return (T)GetServiceOrCreateInstance(provider, typeof(T)); } /// <summary> /// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly. /// </summary> /// <param name="provider">The service provider</param> /// <param name="type">The type of the service</param> /// <returns>The resolved service or created instance</returns> public static object GetServiceOrCreateInstance(IServiceProvider provider, Type type) { return provider.GetService(type) ?? CreateInstance(provider, type); } private static MethodInfo GetMethodInfo<T>(Expression<T> expr) { var mc = (MethodCallExpression)expr.Body; return mc.Method; } private static object? GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired) { var service = sp.GetService(type); if (service == null && !isDefaultParameterRequired) { var message = $"Unable to resolve service for type '{type}' while attempting to activate '{requiredBy}'."; throw new InvalidOperationException(message); } return service; } private static Expression BuildFactoryExpression( ConstructorInfo constructor, int?[] parameterMap, Expression serviceProvider, Expression factoryArgumentArray) { var constructorParameters = constructor.GetParameters(); var constructorArguments = new Expression[constructorParameters.Length]; for (var i = 0; i < constructorParameters.Length; i++) { var constructorParameter = constructorParameters[i]; var parameterType = constructorParameter.ParameterType; var hasDefaultValue = ParameterDefaultValue.TryGetDefaultValue(constructorParameter, out var defaultValue); if (parameterMap[i] != null) { constructorArguments[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i])); } else { var parameterTypeExpression = new Expression[] { serviceProvider, Expression.Constant(parameterType, typeof(Type)), Expression.Constant(constructor.DeclaringType, typeof(Type)), Expression.Constant(hasDefaultValue) }; constructorArguments[i] = Expression.Call(GetServiceInfo, parameterTypeExpression); } // Support optional constructor arguments by passing in the default value // when the argument would otherwise be null. if (hasDefaultValue) { var defaultValueExpression = Expression.Constant(defaultValue); constructorArguments[i] = Expression.Coalesce(constructorArguments[i], defaultValueExpression); } constructorArguments[i] = Expression.Convert(constructorArguments[i], parameterType); } return Expression.New(constructor, constructorArguments); } private static void FindApplicableConstructor( Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out int?[] parameterMap) { matchingConstructor = null!; parameterMap = null!; if (!TryFindPreferredConstructor(instanceType, argumentTypes, ref matchingConstructor!, ref parameterMap!) && !TryFindMatchingConstructor(instanceType, argumentTypes, ref matchingConstructor!, ref parameterMap!)) { var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor."; throw new InvalidOperationException(message); } } // Tries to find constructor based on provided argument types private static bool TryFindMatchingConstructor( Type instanceType, Type[] argumentTypes, ref ConstructorInfo matchingConstructor, ref int?[] parameterMap) { foreach (var constructor in instanceType.GetConstructors()) { if (TryCreateParameterMap(constructor.GetParameters(), argumentTypes, out int?[] tempParameterMap)) { if (matchingConstructor != null) { throw new InvalidOperationException($"Multiple constructors accepting all given argument types have been found in type '{instanceType}'. There should only be one applicable constructor."); } matchingConstructor = constructor; parameterMap = tempParameterMap; } } return matchingConstructor != null; } // Tries to find constructor marked with ActivatorUtilitiesConstructorAttribute private static bool TryFindPreferredConstructor( Type instanceType, Type[] argumentTypes, ref ConstructorInfo matchingConstructor, ref int?[] parameterMap) { var seenPreferred = false; foreach (var constructor in instanceType.GetConstructors()) { if (constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false)) { if (seenPreferred) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (!TryCreateParameterMap(constructor.GetParameters(), argumentTypes, out int?[] tempParameterMap)) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } matchingConstructor = constructor; parameterMap = tempParameterMap; seenPreferred = true; } } return matchingConstructor != null; } // Creates an injective parameterMap from givenParameterTypes to assignable constructorParameters. // Returns true if each given parameter type is assignable to a unique; otherwise, false. private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap) { parameterMap = new int?[constructorParameters.Length]; for (var i = 0; i < argumentTypes.Length; i++) { var foundMatch = false; var givenParameter = argumentTypes[i]; for (var j = 0; j < constructorParameters.Length; j++) { if (parameterMap[j] != null) { // This ctor parameter has already been matched continue; } if (constructorParameters[j].ParameterType.IsAssignableFrom(givenParameter)) { foundMatch = true; parameterMap[j] = i; break; } } if (!foundMatch) { return false; } } return true; } private struct ConstructorMatcher { private readonly ConstructorInfo _constructor; private readonly ParameterInfo[] _parameters; private readonly object[] _parameterValues; public ConstructorMatcher(ConstructorInfo constructor) { _constructor = constructor; _parameters = _constructor.GetParameters(); _parameterValues = new object[_parameters.Length]; } public int Match(object[] givenParameters) { var applyIndexStart = 0; var applyExactLength = 0; for (var givenIndex = 0; givenIndex != givenParameters.Length; givenIndex++) { var givenType = givenParameters[givenIndex]?.GetType(); var givenMatched = false; for (var applyIndex = applyIndexStart; givenMatched == false && applyIndex != _parameters.Length; ++applyIndex) { if (_parameterValues[applyIndex] == null && _parameters[applyIndex].ParameterType.IsAssignableFrom(givenType)) { givenMatched = true; _parameterValues[applyIndex] = givenParameters[givenIndex]; if (applyIndexStart == applyIndex) { applyIndexStart++; if (applyIndex == givenIndex) { applyExactLength = applyIndex; } } } } if (givenMatched == false) { return -1; } } return applyExactLength; } public object CreateInstance(IServiceProvider provider) { for (var index = 0; index != _parameters.Length; index++) { if (_parameterValues[index] == null) { var value = provider.GetService(_parameters[index].ParameterType); if (value == null) { if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out var defaultValue)) { throw new InvalidOperationException($"Unable to resolve service for type '{_parameters[index].ParameterType}' while attempting to activate '{_constructor.DeclaringType}'."); } else { _parameterValues[index] = defaultValue; } } else { _parameterValues[index] = value; } } } #if NETCOREAPP return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null); #else try { return _constructor.Invoke(_parameterValues); } catch (TargetInvocationException ex) when (ex.InnerException != null) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); // The above line will always throw, but the compiler requires we throw explicitly. throw; } #endif } } private static void ThrowMultipleCtorsMarkedWithAttributeException() { throw new InvalidOperationException($"Multiple constructors were marked with {nameof(ActivatorUtilitiesConstructorAttribute)}."); } private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments() { throw new InvalidOperationException($"Constructor marked with {nameof(ActivatorUtilitiesConstructorAttribute)} does not accept all given argument types."); } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * The following part was imported from https://gitlab.freedesktop.org/uchardet/uchardet * The implementation of this feature was originally done on https://gitlab.freedesktop.org/uchardet/uchardet/blob/master/src/LangModels/LangRussianModel.cpp * and adjusted to language specific support. */ namespace UtfUnknown.Core.Models.SingleByte.Russian; internal class Iso_8859_5_RussianModel : RussianModel { private static readonly byte[] CHAR_TO_ORDER_MAP = { CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, RET, CTR, CTR, RET, CTR, CTR, /* 0X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 1X */ SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, /* 2X */ NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, SYM, SYM, SYM, SYM, SYM, SYM, /* 3X */ SYM, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 74, 153, 75, 154, /* 4X */ 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, SYM, SYM, SYM, SYM, SYM, /* 5X */ SYM, 71, 172, 66, 173, 65, 174, 76, 175, 64, 176, 177, 77, 72, 178, 69, /* 6X */ 67, 179, 78, 73, 180, 181, 79, 182, 183, 184, 185, SYM, SYM, SYM, SYM, SYM, /* 7X */ 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, /* 8X */ 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, /* 9X */ 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, /* AX */ 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35, /* BX */ 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43, /* CX */ 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15, /* DX */ 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16, /* EX */ 239, 68, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, NUM, CTR /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ public Iso_8859_5_RussianModel() : base( CHAR_TO_ORDER_MAP, CodepageName.ISO_8859_5) { } }
//--------------------------------------------------------------------------- // // <copyright file="Size.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.WindowsBase; using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Windows.Markup; using System.Windows.Converters; using System.Windows; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows { [Serializable] [TypeConverter(typeof(SizeConverter))] [ValueSerializer(typeof(SizeValueSerializer))] // Used by MarkupWriter partial struct Size : IFormattable { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Compares two Size instances for exact equality. /// Note that double values can acquire error when operated upon, such that /// an exact comparison between two values which are logically equal may fail. /// Furthermore, using this equality operator, Double.NaN is not equal to itself. /// </summary> /// <returns> /// bool - true if the two Size instances are exactly equal, false otherwise /// </returns> /// <param name='size1'>The first Size to compare</param> /// <param name='size2'>The second Size to compare</param> public static bool operator == (Size size1, Size size2) { return size1.Width == size2.Width && size1.Height == size2.Height; } /// <summary> /// Compares two Size instances for exact inequality. /// Note that double values can acquire error when operated upon, such that /// an exact comparison between two values which are logically equal may fail. /// Furthermore, using this equality operator, Double.NaN is not equal to itself. /// </summary> /// <returns> /// bool - true if the two Size instances are exactly unequal, false otherwise /// </returns> /// <param name='size1'>The first Size to compare</param> /// <param name='size2'>The second Size to compare</param> public static bool operator != (Size size1, Size size2) { return !(size1 == size2); } /// <summary> /// Compares two Size instances for object equality. In this equality /// Double.NaN is equal to itself, unlike in numeric equality. /// Note that double values can acquire error when operated upon, such that /// an exact comparison between two values which /// are logically equal may fail. /// </summary> /// <returns> /// bool - true if the two Size instances are exactly equal, false otherwise /// </returns> /// <param name='size1'>The first Size to compare</param> /// <param name='size2'>The second Size to compare</param> public static bool Equals (Size size1, Size size2) { if (size1.IsEmpty) { return size2.IsEmpty; } else { return size1.Width.Equals(size2.Width) && size1.Height.Equals(size2.Height); } } /// <summary> /// Equals - compares this Size with the passed in object. In this equality /// Double.NaN is equal to itself, unlike in numeric equality. /// Note that double values can acquire error when operated upon, such that /// an exact comparison between two values which /// are logically equal may fail. /// </summary> /// <returns> /// bool - true if the object is an instance of Size and if it's equal to "this". /// </returns> /// <param name='o'>The object to compare to "this"</param> public override bool Equals(object o) { if ((null == o) || !(o is Size)) { return false; } Size value = (Size)o; return Size.Equals(this,value); } /// <summary> /// Equals - compares this Size with the passed in object. In this equality /// Double.NaN is equal to itself, unlike in numeric equality. /// Note that double values can acquire error when operated upon, such that /// an exact comparison between two values which /// are logically equal may fail. /// </summary> /// <returns> /// bool - true if "value" is equal to "this". /// </returns> /// <param name='value'>The Size to compare to "this"</param> public bool Equals(Size value) { return Size.Equals(this, value); } /// <summary> /// Returns the HashCode for this Size /// </summary> /// <returns> /// int - the HashCode for this Size /// </returns> public override int GetHashCode() { if (IsEmpty) { return 0; } else { // Perform field-by-field XOR of HashCodes return Width.GetHashCode() ^ Height.GetHashCode(); } } /// <summary> /// Parse - returns an instance converted from the provided string using /// the culture "en-US" /// <param name="source"> string with Size data </param> /// </summary> public static Size Parse(string source) { IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS; TokenizerHelper th = new TokenizerHelper(source, formatProvider); Size value; String firstToken = th.NextTokenRequired(); // The token will already have had whitespace trimmed so we can do a // simple string compare. if (firstToken == "Empty") { value = Empty; } else { value = new Size( Convert.ToDouble(firstToken, formatProvider), Convert.ToDouble(th.NextTokenRequired(), formatProvider)); } // There should be no more tokens in this string. th.LastTokenRequired(); return value; } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties /// <summary> /// Creates a string representation of this object based on the current culture. /// </summary> /// <returns> /// A string representation of this object. /// </returns> public override string ToString() { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, null /* format provider */); } /// <summary> /// Creates a string representation of this object based on the IFormatProvider /// passed in. If the provider is null, the CurrentCulture is used. /// </summary> /// <returns> /// A string representation of this object. /// </returns> public string ToString(IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, provider); } /// <summary> /// Creates a string representation of this object based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <returns> /// A string representation of this object. /// </returns> string IFormattable.ToString(string format, IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(format, provider); } /// <summary> /// Creates a string representation of this object based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <returns> /// A string representation of this object. /// </returns> internal string ConvertToString(string format, IFormatProvider provider) { if (IsEmpty) { return "Empty"; } // Helper to get the numeric list separator for a given culture. char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider); return String.Format(provider, "{1:" + format + "}{0}{2:" + format + "}", separator, _width, _height); } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal double _width; internal double _height; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #endregion Constructors } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using Microsoft.Research.Naiad.Dataflow; using Microsoft.Research.Naiad.Dataflow.Channels; using Microsoft.Research.Naiad.Runtime.Controlling; using Microsoft.Research.Naiad.Scheduling; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Research.Naiad.Diagnostics; namespace Microsoft.Research.Naiad.Runtime.Progress { internal interface LocalProgressInfo { PointstampCountSet PointstampCountSet { get; } } internal interface ProgressTracker : Frontier { void BroadcastProgressUpdate(Pointstamp time, int update); LocalProgressInfo GetInfoForWorker(int workerId); ProgressUpdateAggregator Aggregator { get; } void Complain(TextWriter writer); void Cancel(); void BlockUntilComplete(); } internal class DistributedProgressTracker : ProgressTracker { private ProgressChannel progressChannel; // single producer -> many consumers ProgressUpdateConsumer consumer; public LocalProgressInfo GetInfoForWorker(int workerId) { return this.consumer; } private ProgressUpdateAggregator aggregator; public ProgressUpdateAggregator Aggregator { get { return this.aggregator; } } public void BroadcastProgressUpdate(Pointstamp time, int update) { this.consumer.InjectElement(time, update); } public event EventHandler<FrontierChangedEventArgs> OnFrontierChanged { add { this.consumer.OnFrontierChanged += value; } remove { this.consumer.OnFrontierChanged -= value; } } public void Cancel() { this.consumer.FrontierEmpty.Set(); } public void BlockUntilComplete() { this.consumer.FrontierEmpty.WaitOne(); } public DistributedProgressTracker(InternalComputation internalComputation) { var processes = internalComputation.Controller.Configuration.Processes; var processid = internalComputation.Controller.Configuration.ProcessID; var context = new TimeContext<Empty>(internalComputation.ContextManager.MakeRawContextForScope<Empty>("progress context")); // construct aggregator stage with unconnected output var aggregatorPlacement = new Placement.SingleVertexPerProcess(processes, 0); var aggregator = new Stage<ProgressUpdateAggregator, Empty>(aggregatorPlacement, context, Stage.OperatorType.Default, (i, v) => new ProgressUpdateAggregator(i, v), "Aggregator"); var stream = aggregator.NewOutput(vertex => vertex.Output); aggregator.Materialize(); this.aggregator = aggregator.GetVertex(processid); // construct consumer stage with unconnected input var consumerPlacement = new Placement.SingleVertexPerProcess(processes, 0); var consumer = new Stage<ProgressUpdateConsumer, Empty>(consumerPlacement, context, Stage.OperatorType.Default, (i, v) => new ProgressUpdateConsumer(i, v, this.aggregator), "Consumer"); var recvPort = consumer.NewUnconnectedInput(vertex => vertex.Input, null); consumer.Materialize(); this.consumer = consumer.GetVertex(processid); // connect aggregators to consumers with special progress channel this.progressChannel = new ProgressChannel(aggregatorPlacement.Count, this.consumer, stream.StageOutput, recvPort, internalComputation.Controller, internalComputation.AllocateNewGraphIdentifier()); stream.StageOutput.AttachBundleToSender(this.progressChannel); Logging.Progress("Distributed progress tracker enabled"); } public void Complain(TextWriter writer) { lock (this.consumer.PCS) { var frontier = this.consumer.PCS.Frontier; for (int i = 0; i < frontier.Length; i++) writer.WriteLine("\tfrontier[{0}]:\t{1}\t{2}", i, frontier[i], this.consumer.PCS.Counts[frontier[i]]); } } } internal class CentralizedProgressTracker : ProgressTracker { public ProgressUpdateAggregator Aggregator { get { return this.aggregator; } } private readonly ProgressUpdateAggregator aggregator; private readonly ProgressUpdateConsumer consumer; private readonly ProgressUpdateCentralizer centralizer; public LocalProgressInfo GetInfoForWorker(int workerId) { return this.consumer; } public event EventHandler<FrontierChangedEventArgs> OnFrontierChanged { add { this.consumer.OnFrontierChanged += value; } remove { this.consumer.OnFrontierChanged -= value; } } public void Cancel() { this.consumer.FrontierEmpty.Set(); } public void BlockUntilComplete() { // The FrontierEmpty event is signalled on the transition to empty, // so check the length in case the computation has no vertices. if (this.consumer.PCS.Frontier.Length > 0) this.consumer.FrontierEmpty.WaitOne(); } public void BroadcastProgressUpdate(Pointstamp time, int update) { this.consumer.InjectElement(time, 1); if (this.centralizer != null) this.centralizer.InjectElement(time, update); } public CentralizedProgressTracker(InternalComputation internalComputation) { var centralizerProcessId = internalComputation.Controller.Configuration.CentralizerProcessId; var centralizerThreadId = internalComputation.Controller.Configuration.CentralizerThreadId; var processes = internalComputation.Controller.Configuration.Processes; var processid = internalComputation.Controller.Configuration.ProcessID; Logging.Progress("Centralized progress tracker enabled, running on process {0} thread {1}", centralizerProcessId, centralizerThreadId); var context = new TimeContext<Empty>(internalComputation.ContextManager.MakeRawContextForScope<Empty>("progress context")); // construct aggregator stage and unconnected output var aggregatorPlacement = new Placement.SingleVertexPerProcess(processes, 0); var aggregatorStage = new Stage<ProgressUpdateAggregator, Empty>(aggregatorPlacement, context, Stage.OperatorType.Default, (i, v) => new ProgressUpdateAggregator(i, v), "Aggregator"); var stream = aggregatorStage.NewOutput(vertex => vertex.Output); aggregatorStage.Materialize(); this.aggregator = aggregatorStage.GetVertex(processid); // construct centralizer stage and unconnected input and output var centralizerPlacement = new Placement.SingleVertex(centralizerProcessId, centralizerThreadId); var centralizer = new Stage<ProgressUpdateCentralizer, Empty>(centralizerPlacement, context, Stage.OperatorType.Default, (i, v) => new ProgressUpdateCentralizer(i, v, null), "Centralizer"); var centralizerRecvPort = centralizer.NewUnconnectedInput<Update>(vertex => vertex.Input, null); var centralizerSendPort = centralizer.NewOutput(vertex => vertex.Output, null); centralizer.Materialize(); this.centralizer = (processid == centralizerProcessId) ? centralizer.GetVertex(0) : null; // construct consumer stage and unconnected input var consumerPlacement = new Placement.SingleVertexPerProcess(processes, 0); var consumer = new Stage<ProgressUpdateConsumer, Empty>(consumerPlacement, context, Stage.OperatorType.Default, (i, v) => new Runtime.Progress.ProgressUpdateConsumer(i, v, this.aggregator), "Consumer"); var consumerRecvPort = consumer.NewUnconnectedInput(vertex => vertex.Input, null); consumer.Materialize(); this.consumer = consumer.GetVertex(processid); // connect centralizer to consumers with special progress channel var progressChannel = new ProgressChannel(centralizer.Placement.Count, this.consumer, centralizerSendPort.StageOutput, consumerRecvPort, internalComputation.Controller, internalComputation.AllocateNewGraphIdentifier()); centralizerSendPort.StageOutput.AttachBundleToSender(progressChannel); // connect aggregators to centralizer with special centralized progress channel var centralizerChannel = new CentralizedProgressChannel(centralizer, stream.StageOutput, centralizerRecvPort, internalComputation.Controller, internalComputation.AllocateNewGraphIdentifier()); stream.StageOutput.AttachBundleToSender(centralizerChannel); Logging.Progress("Centralized progress tracker initialization completed"); } public void Complain(TextWriter writer) { lock (this.consumer.PCS) { var frontier = this.consumer.PCS.Frontier; for (int i = 0; i < frontier.Length; i++) writer.WriteLine("\tfrontier[{0}]:\t{1}\t{2}", i, frontier[i], this.consumer.PCS.Counts[frontier[i]]); } if (this.centralizer != null) { lock (this.centralizer.PCS) { var frontier = this.centralizer.PCS.Frontier; for (int i = 0; i < frontier.Length; i++) writer.WriteLine("\tcentralized frontier[{0}]:\t{1}\t{2}", i, frontier[i], this.centralizer.PCS.Counts[frontier[i]]); } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Semantics; namespace System.Runtime.Analyzers { /// <summary> /// CA2241: Provide correct arguments to formatting methods /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class ProvideCorrectArgumentsToFormattingMethodsAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2241"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsTitle), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsMessage), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsDescription), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessage, DiagnosticCategory.Usage, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: @"https://msdn.microsoft.com/en-us/library/ms182361.aspx", customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); analysisContext.RegisterCompilationStartAction(compilationContext => { var formatInfo = new StringFormatInfo(compilationContext.Compilation); compilationContext.RegisterOperationAction(operationContext => { var invocation = (IInvocationExpression)operationContext.Operation; StringFormatInfo.Info info = formatInfo.TryGet(invocation.TargetMethod); if (info == null || invocation.ArgumentsInParameterOrder.Length <= info.FormatStringIndex) { // not a target method return; } IArgument formatStringArgument = invocation.ArgumentsInParameterOrder[info.FormatStringIndex]; if (!object.Equals(formatStringArgument?.Value?.Type, formatInfo.String) || !(formatStringArgument?.Value?.ConstantValue.Value is string)) { // wrong argument return; } var stringFormat = (string)formatStringArgument.Value.ConstantValue.Value; int expectedStringFormatArgumentCount = GetFormattingArguments(stringFormat); // explict parameter case if (info.ExpectedStringFormatArgumentCount >= 0) { // __arglist is not supported here if (invocation.TargetMethod.IsVararg) { // can't deal with this for now. return; } if (info.ExpectedStringFormatArgumentCount != expectedStringFormatArgumentCount) { operationContext.ReportDiagnostic(operationContext.Operation.Syntax.CreateDiagnostic(Rule)); } return; } // params case IArgument paramsArgument = invocation.ArgumentsInParameterOrder[info.FormatStringIndex + 1]; if (paramsArgument.ArgumentKind != ArgumentKind.ParamArray) { // wrong format return; } var arrayCreation = paramsArgument.Value as IArrayCreationExpression; if (arrayCreation == null || !object.Equals(arrayCreation.ElementType, formatInfo.Object) || arrayCreation.DimensionSizes.Length != 1) { // wrong format return; } // compiler generating object array for params case IArrayInitializer intializer = arrayCreation.Initializer; if (intializer == null) { // unsupported format return; } // REVIEW: "ElementValues" is a bit confusing where I need to double dot those to get number of elements int actualArgumentCount = intializer.ElementValues.Length; if (actualArgumentCount != expectedStringFormatArgumentCount) { operationContext.ReportDiagnostic(operationContext.Operation.Syntax.CreateDiagnostic(Rule)); } }, OperationKind.InvocationExpression); }); } private static int GetFormattingArguments(string format) { // code is from mscorlib // https://github.com/dotnet/coreclr/blob/bc146608854d1db9cdbcc0b08029a87754e12b49/src/mscorlib/src/System/Text/StringBuilder.cs#L1312 // return count of this format - {index[,alignment][:formatString]} var count = 0; var pos = 0; int len = format.Length; // main loop while (true) { // loop to find starting "{" char ch; while (pos < len) { ch = format[pos]; pos++; if (ch == '}') { if (pos < len && format[pos] == '}') // Treat as escape character for }} { pos++; } else { return -1; } } if (ch == '{') { if (pos < len && format[pos] == '{') // Treat as escape character for {{ { pos++; } else { pos--; break; } } } // finished with "{" if (pos == len) { break; } pos++; if (pos == len || (ch = format[pos]) < '0' || ch > '9') { // finished with "{x" return -1; } // searching for index var index = 0; do { index = index * 10 + ch - '0'; pos++; if (pos == len) { // wrong index format return -1; } ch = format[pos]; } while (ch >= '0' && ch <= '9' && index < 1000000); // eat up whitespace while (pos < len && (ch = format[pos]) == ' ') { pos++; } // searching for alignment var width = 0; if (ch == ',') { pos++; // eat up whitespace while (pos < len && format[pos] == ' ') { pos++; } if (pos == len) { // wrong format, reached end without "}" return -1; } ch = format[pos]; if (ch == '-') { pos++; if (pos == len) { // wrong format. reached end without "}" return -1; } ch = format[pos]; } if (ch < '0' || ch > '9') { // wrong format after "-" return -1; } do { width = width * 10 + ch - '0'; pos++; if (pos == len) { // wrong width format return -1; } ch = format[pos]; } while (ch >= '0' && ch <= '9' && width < 1000000); } // eat up whitespace while (pos < len && (ch = format[pos]) == ' ') { pos++; } // searching for embeded format string if (ch == ':') { pos++; while (true) { if (pos == len) { // reached end without "}" return -1; } ch = format[pos]; pos++; if (ch == '{') { if (pos < len && format[pos] == '{') // Treat as escape character for {{ pos++; else return -1; } else if (ch == '}') { if (pos < len && format[pos] == '}') // Treat as escape character for }} pos++; else { pos--; break; } } } } if (ch != '}') { // "}" is expected return -1; } pos++; count++; } // end of main loop return count; } private class StringFormatInfo { private const string Format = "format"; private readonly ImmutableDictionary<IMethodSymbol, Info> _map; public StringFormatInfo(Compilation compilation) { ImmutableDictionary<IMethodSymbol, Info>.Builder builder = ImmutableDictionary.CreateBuilder<IMethodSymbol, Info>(); INamedTypeSymbol console = WellKnownTypes.Console(compilation); AddStringFormatMap(builder, console, "Write"); AddStringFormatMap(builder, console, "WriteLine"); INamedTypeSymbol @string = WellKnownTypes.String(compilation); AddStringFormatMap(builder, @string, "Format"); _map = builder.ToImmutable(); String = @string; Object = WellKnownTypes.Object(compilation); } #pragma warning disable CA1720 // Identifier contains type name public INamedTypeSymbol String { get; } public INamedTypeSymbol Object { get; } #pragma warning restore CA1720 // Identifier contains type name public Info TryGet(IMethodSymbol method) { if (_map.TryGetValue(method, out Info info)) { return info; } return null; } private static void AddStringFormatMap(ImmutableDictionary<IMethodSymbol, Info>.Builder builder, INamedTypeSymbol type, string methodName) { if (type == null) { return; } foreach (IMethodSymbol method in type.GetMembers(methodName).OfType<IMethodSymbol>()) { int formatIndex = FindParameterIndexOfName(method.Parameters, Format); if (formatIndex < 0 || formatIndex == method.Parameters.Length - 1) { // no valid format string continue; } int expectedArguments = GetExpectedNumberOfArguments(method.Parameters, formatIndex); builder.Add(method, new Info(formatIndex, expectedArguments)); } } private static int GetExpectedNumberOfArguments(ImmutableArray<IParameterSymbol> parameters, int formatIndex) { // check params IParameterSymbol nextParameter = parameters[formatIndex + 1]; if (nextParameter.IsParams) { return -1; } return parameters.Length - formatIndex - 1; } private static int FindParameterIndexOfName(ImmutableArray<IParameterSymbol> parameters, string name) { for (var i = 0; i < parameters.Length; i++) { if (string.Equals(parameters[i].Name, name, StringComparison.Ordinal)) { return i; } } return -1; } public class Info { public Info(int formatIndex, int expectedArguments) { FormatStringIndex = formatIndex; ExpectedStringFormatArgumentCount = expectedArguments; } public int FormatStringIndex { get; } public int ExpectedStringFormatArgumentCount { get; } } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.IO; namespace NLog.UnitTests.Config { using NLog.Conditions; using NLog.Config; using NLog.LayoutRenderers; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using System; using System.Globalization; using System.Text; using Xunit; public class TargetConfigurationTests : NLogTestBase { [Fact] public void SimpleTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='d' type='Debug' layout='${message}' /> </targets> </nlog>"); DebugTarget t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("d", t.Name); SimpleLayout l = t.Layout as SimpleLayout; Assert.Equal("${message}", l.Text); Assert.NotNull(t.Layout); Assert.Single(l.Renderers); Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]); } [Fact] public void SimpleElementSyntaxTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='Debug'> <name>d</name> <layout>${message}</layout> </target> </targets> </nlog>"); DebugTarget t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("d", t.Name); SimpleLayout l = t.Layout as SimpleLayout; Assert.Equal("${message}", l.Text); Assert.NotNull(t.Layout); Assert.Single(l.Renderers); Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]); } [Fact] public void TargetWithLayoutHasUniqueLayout() { var target1 = new StructuredDebugTarget(); var target2 = new StructuredDebugTarget(); var simpleLayout1 = target1.Layout as SimpleLayout; var simpleLayout2 = target2.Layout as SimpleLayout; // Ensure the default Layout for two Targets are not reusing objects // As it would cause havoc with initializing / closing lifetime-events Assert.NotSame(simpleLayout1, simpleLayout2); Assert.Equal(simpleLayout1.Renderers.Count, simpleLayout1.Renderers.Count); for (int i = 0; i < simpleLayout1.Renderers.Count; ++i) { Assert.NotSame(simpleLayout1.Renderers[i], simpleLayout2.Renderers[i]); } } [Fact] public void NestedXmlConfigElementTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <extensions> <add type='" + typeof(StructuredDebugTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='StructuredDebugTarget'> <name>structuredTgt</name> <layout>${message}</layout> <config platform='any'> <parameter name='param1' /> </config> </target> </targets> </nlog>"); var t = c.FindTargetByName("structuredTgt") as StructuredDebugTarget; Assert.NotNull(t); Assert.Equal("any", t.Config.Platform); Assert.Equal("param1", t.Config.Parameter.Name); } [Fact] public void ArrayParameterTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='MethodCall' name='mct'> <parameter name='p1' layout='${message}' /> <parameter name='p2' layout='${level}' /> <parameter name='p3' layout='${logger}' /> </target> </targets> </nlog>"); var t = c.FindTargetByName("mct") as MethodCallTarget; Assert.NotNull(t); Assert.Equal(3, t.Parameters.Count); Assert.Equal("p1", t.Parameters[0].Name); Assert.Equal("${message}", t.Parameters[0].Layout.ToString()); Assert.Equal("p2", t.Parameters[1].Name); Assert.Equal("${level}", t.Parameters[1].Layout.ToString()); Assert.Equal("p3", t.Parameters[2].Name); Assert.Equal("${logger}", t.Parameters[2].Layout.ToString()); } [Fact] public void ArrayElementParameterTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='MethodCall' name='mct'> <parameter> <name>p1</name> <layout>${message}</layout> </parameter> <parameter> <name>p2</name> <layout type='CsvLayout'> <column name='x' layout='${message}' /> <column name='y' layout='${level}' /> </layout> </parameter> <parameter> <name>p3</name> <layout>${logger}</layout> </parameter> </target> </targets> </nlog>"); var t = c.FindTargetByName("mct") as MethodCallTarget; Assert.NotNull(t); Assert.Equal(3, t.Parameters.Count); Assert.Equal("p1", t.Parameters[0].Name); Assert.Equal("${message}", t.Parameters[0].Layout.ToString()); Assert.Equal("p2", t.Parameters[1].Name); CsvLayout csvLayout = t.Parameters[1].Layout as CsvLayout; Assert.NotNull(csvLayout); Assert.Equal(2, csvLayout.Columns.Count); Assert.Equal("x", csvLayout.Columns[0].Name); Assert.Equal("y", csvLayout.Columns[1].Name); Assert.Equal("p3", t.Parameters[2].Name); Assert.Equal("${logger}", t.Parameters[2].Layout.ToString()); } [Fact] public void SimpleTest2() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='d' type='Debug' layout='${message} ${level}' /> </targets> </nlog>"); DebugTarget t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("d", t.Name); SimpleLayout l = t.Layout as SimpleLayout; Assert.Equal("${message} ${level}", l.Text); Assert.NotNull(l); Assert.Equal(3, l.Renderers.Count); Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]); Assert.IsType<LiteralLayoutRenderer>(l.Renderers[1]); Assert.IsType<LevelLayoutRenderer>(l.Renderers[2]); Assert.Equal(" ", ((LiteralLayoutRenderer)l.Renderers[1]).Text); } [Fact] public void WrapperTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <wrapper-target name='b' type='BufferingWrapper' bufferSize='19'> <wrapper name='a' type='AsyncWrapper'> <target name='c' type='Debug' layout='${message}' /> </wrapper> </wrapper-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("a")); Assert.NotNull(c.FindTargetByName("b")); Assert.NotNull(c.FindTargetByName("c")); Assert.IsType<BufferingTargetWrapper>(c.FindTargetByName("b")); Assert.IsType<AsyncTargetWrapper>(c.FindTargetByName("a")); Assert.IsType<DebugTarget>(c.FindTargetByName("c")); BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper; AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper; DebugTarget dt = c.FindTargetByName("c") as DebugTarget; Assert.Same(atw, btw.WrappedTarget); Assert.Same(dt, atw.WrappedTarget); Assert.Equal(19, btw.BufferSize); } [Fact] public void WrapperRefTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='c' type='Debug' layout='${message}' /> <wrapper name='a' type='AsyncWrapper'> <target-ref name='c' /> </wrapper> <wrapper-target name='b' type='BufferingWrapper' bufferSize='19'> <wrapper-target-ref name='a' /> </wrapper-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("a")); Assert.NotNull(c.FindTargetByName("b")); Assert.NotNull(c.FindTargetByName("c")); Assert.IsType<BufferingTargetWrapper>(c.FindTargetByName("b")); Assert.IsType<AsyncTargetWrapper>(c.FindTargetByName("a")); Assert.IsType<DebugTarget>(c.FindTargetByName("c")); BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper; AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper; DebugTarget dt = c.FindTargetByName("c") as DebugTarget; Assert.Same(atw, btw.WrappedTarget); Assert.Same(dt, atw.WrappedTarget); Assert.Equal(19, btw.BufferSize); } [Fact] public void CompoundTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <compound-target name='rr' type='RoundRobinGroup'> <target name='d1' type='Debug' layout='${message}1' /> <target name='d2' type='Debug' layout='${message}2' /> <target name='d3' type='Debug' layout='${message}3' /> <target name='d4' type='Debug' layout='${message}4' /> </compound-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("rr")); Assert.NotNull(c.FindTargetByName("d1")); Assert.NotNull(c.FindTargetByName("d2")); Assert.NotNull(c.FindTargetByName("d3")); Assert.NotNull(c.FindTargetByName("d4")); Assert.IsType<RoundRobinGroupTarget>(c.FindTargetByName("rr")); Assert.IsType<DebugTarget>(c.FindTargetByName("d1")); Assert.IsType<DebugTarget>(c.FindTargetByName("d2")); Assert.IsType<DebugTarget>(c.FindTargetByName("d3")); Assert.IsType<DebugTarget>(c.FindTargetByName("d4")); RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget; DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget; DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget; DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget; DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget; Assert.Equal(4, rr.Targets.Count); Assert.Same(d1, rr.Targets[0]); Assert.Same(d2, rr.Targets[1]); Assert.Same(d3, rr.Targets[2]); Assert.Same(d4, rr.Targets[3]); Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text); Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text); Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text); Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text); } [Fact] public void CompoundRefTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='d1' type='Debug' layout='${message}1' /> <target name='d2' type='Debug' layout='${message}2' /> <target name='d3' type='Debug' layout='${message}3' /> <target name='d4' type='Debug' layout='${message}4' /> <compound-target name='rr' type='RoundRobinGroup'> <target-ref name='d1' /> <target-ref name='d2' /> <target-ref name='d3' /> <target-ref name='d4' /> </compound-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("rr")); Assert.NotNull(c.FindTargetByName("d1")); Assert.NotNull(c.FindTargetByName("d2")); Assert.NotNull(c.FindTargetByName("d3")); Assert.NotNull(c.FindTargetByName("d4")); Assert.IsType<RoundRobinGroupTarget>(c.FindTargetByName("rr")); Assert.IsType<DebugTarget>(c.FindTargetByName("d1")); Assert.IsType<DebugTarget>(c.FindTargetByName("d2")); Assert.IsType<DebugTarget>(c.FindTargetByName("d3")); Assert.IsType<DebugTarget>(c.FindTargetByName("d4")); RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget; DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget; DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget; DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget; DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget; Assert.Equal(4, rr.Targets.Count); Assert.Same(d1, rr.Targets[0]); Assert.Same(d2, rr.Targets[1]); Assert.Same(d3, rr.Targets[2]); Assert.Same(d4, rr.Targets[3]); Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text); Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text); Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text); Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text); } [Fact] public void AsyncWrappersTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets async='true'> <target type='Debug' name='d' /> <target type='Debug' name='d2' /> </targets> </nlog>"); var t = c.FindTargetByName("d") as AsyncTargetWrapper; Assert.NotNull(t); Assert.Equal("d", t.Name); var wrappedTarget = t.WrappedTarget as DebugTarget; Assert.NotNull(wrappedTarget); Assert.Equal("d_wrapped", wrappedTarget.Name); t = c.FindTargetByName("d2") as AsyncTargetWrapper; Assert.NotNull(t); Assert.Equal("d2", t.Name); wrappedTarget = t.WrappedTarget as DebugTarget; Assert.NotNull(wrappedTarget); Assert.Equal("d2_wrapped", wrappedTarget.Name); } [Fact] public void UnnamedWrappedTargetTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets async='true'> <target type='AsyncWrapper' name='d'> <target type='Debug' /> </target> </targets> </nlog>"); var t = c.FindTargetByName("d") as AsyncTargetWrapper; Assert.NotNull(t); Assert.Equal("d", t.Name); var wrappedTarget = t.WrappedTarget as DebugTarget; Assert.NotNull(wrappedTarget); Assert.Equal("d_wrapped", wrappedTarget.Name); } [Fact] public void DefaultTargetParametersTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <default-target-parameters type='Debug' layout='x${message}x' /> <target type='Debug' name='d' /> <target type='Debug' name='d2' /> </targets> </nlog>"); var t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("x${message}x", t.Layout.ToString()); t = c.FindTargetByName("d2") as DebugTarget; Assert.NotNull(t); Assert.Equal("x${message}x", t.Layout.ToString()); } [Fact] public void DefaultTargetParametersOnWrappedTargetTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <default-target-parameters type='Debug' layout='x${message}x' /> <target type='BufferingWrapper' name='buf1'> <target type='Debug' name='d1' /> </target> </targets> </nlog>"); var wrap = c.FindTargetByName("buf1") as BufferingTargetWrapper; Assert.NotNull(wrap); Assert.NotNull(wrap.WrappedTarget); var t = wrap.WrappedTarget as DebugTarget; Assert.NotNull(t); Assert.Equal("x${message}x", t.Layout.ToString()); } [Fact] public void DefaultWrapperTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <default-wrapper type='BufferingWrapper'> <wrapper type='RetryingWrapper' /> </default-wrapper> <target type='Debug' name='d' layout='${level}' /> <target type='Debug' name='d2' layout='${level}' /> </targets> </nlog>"); var bufferingTargetWrapper = c.FindTargetByName("d") as BufferingTargetWrapper; Assert.NotNull(bufferingTargetWrapper); var retryingTargetWrapper = bufferingTargetWrapper.WrappedTarget as RetryingTargetWrapper; Assert.NotNull(retryingTargetWrapper); Assert.Null(retryingTargetWrapper.Name); var debugTarget = retryingTargetWrapper.WrappedTarget as DebugTarget; Assert.NotNull(debugTarget); Assert.Equal("d_wrapped", debugTarget.Name); Assert.Equal("${level}", debugTarget.Layout.ToString()); var debugTarget2 = c.FindTargetByName<DebugTarget>("d"); Assert.Same(debugTarget, debugTarget2); } [Fact] public void DontThrowExceptionWhenArchiveEverySetByDefaultParameters() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <default-target-parameters type='File' concurrentWrites='true' keepFileOpen='true' maxArchiveFiles='5' archiveNumbering='Rolling' archiveEvery='Day' /> <target fileName='" + Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + @".log' name = 'file' type = 'File' layout = '${message}' /> </targets> <rules> <logger name='*' writeTo='file'/> </rules> </nlog> "); LogManager.Configuration = configuration; LogManager.GetLogger("TestLogger").Info("DefaultFileTargetParametersTests.DontThrowExceptionWhenArchiveEverySetByDefaultParameters is true"); } [Fact] public void DontThrowExceptionsWhenMissingRequiredParameters() { using (new NoThrowNLogExceptions()) { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='bufferingwrapper' name='mytarget'> <target type='unknowntargettype' name='badtarget' /> </target> </targets> <rules> <logger name='*' writeTo='mytarget'/> </rules> </nlog> "); LogManager.Configuration = configuration; LogManager.GetLogger(nameof(DontThrowExceptionsWhenMissingRequiredParameters)).Info("Test"); LogManager.Configuration = null; } } [Fact] public void DataTypesTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <extensions> <add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyTarget' name='myTarget' byteProperty='42' int16Property='42' int32Property='42' int64Property='42000000000' stringProperty='foobar' boolProperty='true' doubleProperty='3.14159' floatProperty='3.14159' enumProperty='Value3' flagsEnumProperty='Value1,Value3' encodingProperty='utf-8' cultureProperty='en-US' typeProperty='System.Int32' layoutProperty='${level}' conditionProperty=""starts-with(message, 'x')"" uriProperty='http://nlog-project.org' lineEndingModeProperty='default' /> </targets> </nlog>"); var myTarget = c.FindTargetByName("myTarget") as MyTarget; Assert.NotNull(myTarget); Assert.Equal((byte)42, myTarget.ByteProperty); Assert.Equal((short)42, myTarget.Int16Property); Assert.Equal(42, myTarget.Int32Property); Assert.Equal(42000000000L, myTarget.Int64Property); Assert.Equal("foobar", myTarget.StringProperty); Assert.True(myTarget.BoolProperty); Assert.Equal(3.14159, myTarget.DoubleProperty); Assert.Equal(3.14159f, myTarget.FloatProperty); Assert.Equal(MyEnum.Value3, myTarget.EnumProperty); Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty); Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty); Assert.Equal("en-US", myTarget.CultureProperty.Name); Assert.Equal(typeof(int), myTarget.TypeProperty); Assert.Equal("${level}", myTarget.LayoutProperty.ToString()); Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString()); Assert.Equal(new Uri("http://nlog-project.org"), myTarget.UriProperty); Assert.Equal(LineEndingMode.Default, myTarget.LineEndingModeProperty); } [Fact] public void NullableDataTypesTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <extensions> <add type='" + typeof(MyNullableTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyNullableTarget' name='myTarget' byteProperty='42' int16Property='42' int32Property='42' int64Property='42000000000' stringProperty='foobar' boolProperty='true' doubleProperty='3.14159' floatProperty='3.14159' enumProperty='Value3' flagsEnumProperty='Value1,Value3' encodingProperty='utf-8' cultureProperty='en-US' typeProperty='System.Int32' layoutProperty='${level}' conditionProperty=""starts-with(message, 'x')"" /> </targets> </nlog>"); var myTarget = c.FindTargetByName("myTarget") as MyNullableTarget; Assert.NotNull(myTarget); Assert.Equal((byte)42, myTarget.ByteProperty); Assert.Equal((short)42, myTarget.Int16Property); Assert.Equal(42, myTarget.Int32Property); Assert.Equal(42000000000L, myTarget.Int64Property); Assert.Equal("foobar", myTarget.StringProperty); Assert.True(myTarget.BoolProperty); Assert.Equal(3.14159, myTarget.DoubleProperty); Assert.Equal(3.14159f, myTarget.FloatProperty); Assert.Equal(MyEnum.Value3, myTarget.EnumProperty); Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty); Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty); Assert.Equal("en-US", myTarget.CultureProperty.Name); Assert.Equal(typeof(int), myTarget.TypeProperty); Assert.Equal("${level}", myTarget.LayoutProperty.ToString()); Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString()); } [Target("MyTarget")] public class MyTarget : Target { public byte ByteProperty { get; set; } public short Int16Property { get; set; } public int Int32Property { get; set; } public long Int64Property { get; set; } public string StringProperty { get; set; } public bool BoolProperty { get; set; } public double DoubleProperty { get; set; } public float FloatProperty { get; set; } public MyEnum EnumProperty { get; set; } public MyFlagsEnum FlagsEnumProperty { get; set; } public Encoding EncodingProperty { get; set; } public CultureInfo CultureProperty { get; set; } public Type TypeProperty { get; set; } public Layout LayoutProperty { get; set; } public ConditionExpression ConditionProperty { get; set; } public Uri UriProperty { get; set; } public LineEndingMode LineEndingModeProperty { get; set; } public MyTarget() : base() { } public MyTarget(string name) : this() { Name = name; } } [Target("MyNullableTarget")] public class MyNullableTarget : Target { public byte? ByteProperty { get; set; } public short? Int16Property { get; set; } public int? Int32Property { get; set; } public long? Int64Property { get; set; } public string StringProperty { get; set; } public bool? BoolProperty { get; set; } public double? DoubleProperty { get; set; } public float? FloatProperty { get; set; } public MyEnum? EnumProperty { get; set; } public MyFlagsEnum? FlagsEnumProperty { get; set; } public Encoding EncodingProperty { get; set; } public CultureInfo CultureProperty { get; set; } public Type TypeProperty { get; set; } public Layout LayoutProperty { get; set; } public ConditionExpression ConditionProperty { get; set; } public MyNullableTarget() : base() { } public MyNullableTarget(string name) : this() { Name = name; } } public enum MyEnum { Value1, Value2, Value3, } [Flags] public enum MyFlagsEnum { Value1 = 1, Value2 = 2, Value3 = 4, } [Target("StructuredDebugTarget")] public class StructuredDebugTarget : TargetWithLayout { public StructuredDebugTargetConfig Config { get; set; } public StructuredDebugTarget() { Config = new StructuredDebugTargetConfig(); } } public class StructuredDebugTargetConfig { public string Platform { get; set; } public StructuredDebugTargetParameter Parameter { get; set; } public StructuredDebugTargetConfig() { Parameter = new StructuredDebugTargetParameter(); } } public class StructuredDebugTargetParameter { public string Name { get; set; } } } }
using System; using System.Collections.Generic; using System.Text; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Collections.Specialized; namespace PawnManager.TreeList { public sealed class TreeNode : INotifyPropertyChanged { #region NodeCollection private class NodeCollection : Collection<TreeNode> { private TreeNode _owner; public NodeCollection(TreeNode owner) { _owner = owner; } protected override void ClearItems() { while (this.Count != 0) this.RemoveAt(this.Count - 1); } protected override void InsertItem(int index, TreeNode item) { if (item == null) throw new ArgumentNullException("item"); if (item.Parent != _owner) { if (item.Parent != null) item.Parent.Children.Remove(item); item._parent = _owner; item._index = index; for (int i = index; i < Count; i++) this[i]._index++; base.InsertItem(index, item); } } protected override void RemoveItem(int index) { TreeNode item = this[index]; item._parent = null; item._index = -1; for (int i = index + 1; i < Count; i++) this[i]._index--; base.RemoveItem(index); } protected override void SetItem(int index, TreeNode item) { if (item == null) throw new ArgumentNullException("item"); RemoveAt(index); InsertItem(index, item); } } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion #region Properties private TreeList _tree; internal TreeList Tree { get { return _tree; } } private INotifyCollectionChanged _childrenSource; internal INotifyCollectionChanged ChildrenSource { get { return _childrenSource; } set { if (_childrenSource != null) _childrenSource.CollectionChanged -= ChildrenChanged; _childrenSource = value; if (_childrenSource != null) _childrenSource.CollectionChanged += ChildrenChanged; } } private int _index = -1; public int Index { get { return _index; } } /// <summary> /// Returns true if all parent nodes of this node are expanded. /// </summary> internal bool IsVisible { get { TreeNode node = _parent; while (node != null) { if (!node.IsExpanded) return false; node = node.Parent; } return true; } } public bool IsExpandedOnce { get; internal set; } public bool HasChildren { get; internal set; } private bool _isExpanded; public bool IsExpanded { get { return _isExpanded; } set { if (value != IsExpanded) { Tree.SetIsExpanded(this, value); OnPropertyChanged("IsExpanded"); OnPropertyChanged("IsExpandable"); } } } internal void AssignIsExpanded(bool value) { _isExpanded = value; } public bool IsExpandable { get { return (HasChildren && !IsExpandedOnce) || Nodes.Count > 0; } } private bool _isSelected; public bool IsSelected { get { return _isSelected; } set { if (value != _isSelected) { _isSelected = value; OnPropertyChanged("IsSelected"); } } } private TreeNode _parent; public TreeNode Parent { get { return _parent; } } public int Level { get { if (_parent == null) return -1; else return _parent.Level + 1; } } public TreeNode PreviousNode { get { if (_parent != null) { int index = Index; if (index > 0) return _parent.Nodes[index - 1]; } return null; } } public TreeNode NextNode { get { if (_parent != null) { int index = Index; if (index < _parent.Nodes.Count - 1) return _parent.Nodes[index + 1]; } return null; } } internal TreeNode BottomNode { get { TreeNode parent = this.Parent; if (parent != null) { if (parent.NextNode != null) return parent.NextNode; else return parent.BottomNode; } return null; } } internal TreeNode NextVisibleNode { get { if (IsExpanded && Nodes.Count > 0) return Nodes[0]; else { TreeNode nn = NextNode; if (nn != null) return nn; else return BottomNode; } } } public int VisibleChildrenCount { get { return AllVisibleChildren.Count(); } } public IEnumerable<TreeNode> AllVisibleChildren { get { int level = this.Level; TreeNode node = this; while (true) { node = node.NextVisibleNode; if (node != null && node.Level > level) yield return node; else break; } } } private object _tag; public object Tag { get { return _tag; } } private Collection<TreeNode> _children; internal Collection<TreeNode> Children { get { return _children; } } private ReadOnlyCollection<TreeNode> _nodes; public ReadOnlyCollection<TreeNode> Nodes { get { return _nodes; } } #endregion internal TreeNode(TreeList tree, object tag) { if (tree == null) throw new ArgumentNullException("tree"); _tree = tree; _children = new NodeCollection(this); _nodes = new ReadOnlyCollection<TreeNode>(_children); _tag = tag; } public override string ToString() { if (Tag != null) return Tag.ToString(); else return base.ToString(); } void ChildrenChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: if (e.NewItems != null) { int index = e.NewStartingIndex; int rowIndex = Tree.Rows.IndexOf(this); foreach (object obj in e.NewItems) { Tree.InsertNewNode(this, obj, rowIndex, index); index++; } } break; case NotifyCollectionChangedAction.Remove: if (Children.Count > e.OldStartingIndex) RemoveChildAt(e.OldStartingIndex); break; case NotifyCollectionChangedAction.Move: case NotifyCollectionChangedAction.Replace: case NotifyCollectionChangedAction.Reset: while (Children.Count > 0) RemoveChildAt(0); Tree.CreateChildrenNodes(this); break; } HasChildren = Children.Count > 0; OnPropertyChanged("IsExpandable"); } private void RemoveChildAt(int index) { var child = Children[index]; Tree.DropChildrenRows(child, true); ClearChildrenSource(child); Children.RemoveAt(index); } private void ClearChildrenSource(TreeNode node) { node.ChildrenSource = null; foreach (var n in node.Children) ClearChildrenSource(n); } } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Runtime.InteropServices; using Axiom.Core; using Axiom.Graphics; using Tao.OpenGl; namespace Axiom.RenderSystems.OpenGL { /// <summary> /// Summary description for GLHardwareIndexBuffer. /// </summary> public class GLHardwareIndexBuffer : HardwareIndexBuffer { #region Fields /// <summary> /// Saves the GL buffer ID for this buffer. /// </summary> private int bufferID; #endregion #region Constructors /// <summary> /// Constructor. /// </summary> /// <param name="type">Index type (16 or 32 bit).</param> /// <param name="numIndices">Number of indices in the buffer.</param> /// <param name="usage">Usage flags.</param> /// <param name="useShadowBuffer">Should this buffer be backed by a software shadow buffer?</param> public GLHardwareIndexBuffer(IndexType type, int numIndices, BufferUsage usage, bool useShadowBuffer) : base(type, numIndices, usage, false, useShadowBuffer) { // generate the buffer Gl.glGenBuffersARB(1, out bufferID); if(bufferID == 0) throw new Exception("Cannot create GL index buffer"); Gl.glBindBufferARB(Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, bufferID); // initialize this buffer. we dont have data yet tho Gl.glBufferDataARB( Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, sizeInBytes, IntPtr.Zero, GLHelper.ConvertEnum(usage)); } #endregion #region HardwareIndexBuffer Implementation /// <summary> /// /// </summary> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="locking"></param> /// <returns></returns> protected override IntPtr LockImpl(int offset, int length, BufferLocking locking) { int access = 0; if(isLocked) { throw new Exception("Invalid attempt to lock an index buffer that has already been locked."); } // bind this buffer Gl.glBindBufferARB(Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, bufferID); if(locking == BufferLocking.Discard) { // commented out to fix ATI issues /*Gl.glBufferDataARB(Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, sizeInBytes, IntPtr.Zero, GLHelper.ConvertEnum(usage)); */ // find out how we shall access this buffer access = (usage == BufferUsage.Dynamic) ? Gl.GL_READ_WRITE_ARB : Gl.GL_WRITE_ONLY_ARB; } else if(locking == BufferLocking.ReadOnly) { if(usage == BufferUsage.WriteOnly) { LogManager.Instance.Write("Invalid attempt to lock a write-only vertex buffer as read-only."); } access = Gl.GL_READ_ONLY_ARB; } else if (locking == BufferLocking.Normal || locking == BufferLocking.NoOverwrite) { access = (usage == BufferUsage.Dynamic) ? Gl.GL_READ_WRITE_ARB : Gl.GL_WRITE_ONLY_ARB; } IntPtr ptr = Gl.glMapBufferARB(Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, access); if(ptr == IntPtr.Zero) { throw new Exception("GL Vertex Buffer: Out of memory"); } isLocked = true; return new IntPtr(ptr.ToInt32() + offset); } /// <summary> /// /// </summary> public override void UnlockImpl() { Gl.glBindBufferARB(Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, bufferID); if(Gl.glUnmapBufferARB(Gl.GL_ELEMENT_ARRAY_BUFFER_ARB) == 0) { throw new Exception("Buffer data corrupted!"); } isLocked = false; } /// <summary> /// /// </summary> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="src"></param> /// <param name="discardWholeBuffer"></param> public override void WriteData(int offset, int length, IntPtr src, bool discardWholeBuffer) { Gl.glBindBufferARB(Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, bufferID); if(useShadowBuffer) { // lock the buffer for reading IntPtr dest = shadowBuffer.Lock(offset, length, discardWholeBuffer ? BufferLocking.Discard : BufferLocking.Normal); // copy that data in there Memory.Copy(src, dest, length); // unlock the buffer shadowBuffer.Unlock(); } if(discardWholeBuffer) { Gl.glBufferDataARB(Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, sizeInBytes, IntPtr.Zero, GLHelper.ConvertEnum(usage)); } Gl.glBufferSubDataARB( Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, offset, length, src); } /// <summary> /// /// </summary> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="dest"></param> public override void ReadData(int offset, int length, IntPtr dest) { if(useShadowBuffer) { // lock the buffer for reading IntPtr src = shadowBuffer.Lock(offset, length, BufferLocking.ReadOnly); // copy that data in there Memory.Copy(src, dest, length); // unlock the buffer shadowBuffer.Unlock(); } else { Gl.glBindBufferARB(Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, bufferID); Gl.glGetBufferSubDataARB( Gl.GL_ELEMENT_ARRAY_BUFFER_ARB, offset, length, dest); } } /// <summary> /// Called to destroy this buffer. /// </summary> public override void Dispose() { Gl.glDeleteBuffersARB(1, ref bufferID); } #endregion HardwareIndexBuffer Implementation #region Properties /// <summary> /// Gets the GL buffer ID for this buffer. /// </summary> public int GLBufferID { get { return bufferID; } } #endregion } }
// <copyright file="FirefoxOptions.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.Firefox { /// <summary> /// Class to manage options specific to <see cref="FirefoxDriver"/> /// </summary> /// <remarks> /// Used with the marionette executable wires.exe. /// </remarks> /// <example> /// <code> /// FirefoxOptions options = new FirefoxOptions(); /// </code> /// <para></para> /// <para>For use with FirefoxDriver:</para> /// <para></para> /// <code> /// FirefoxDriver driver = new FirefoxDriver(options); /// </code> /// <para></para> /// <para>For use with RemoteWebDriver:</para> /// <para></para> /// <code> /// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities()); /// </code> /// </example> public class FirefoxOptions : DriverOptions { private const string BrowserNameValue = "firefox"; private const string IsMarionetteCapability = "marionette"; private const string FirefoxLegacyProfileCapability = "firefox_profile"; private const string FirefoxLegacyBinaryCapability = "firefox_binary"; private const string FirefoxProfileCapability = "profile"; private const string FirefoxBinaryCapability = "binary"; private const string FirefoxArgumentsCapability = "args"; private const string FirefoxLogCapability = "log"; private const string FirefoxPrefsCapability = "prefs"; private const string FirefoxOptionsCapability = "moz:firefoxOptions"; private bool isMarionette = true; private string browserBinaryLocation; private FirefoxDriverLogLevel logLevel = FirefoxDriverLogLevel.Default; private FirefoxProfile profile; private List<string> firefoxArguments = new List<string>(); private Dictionary<string, object> profilePreferences = new Dictionary<string, object>(); private Dictionary<string, object> additionalCapabilities = new Dictionary<string, object>(); private Dictionary<string, object> additionalFirefoxOptions = new Dictionary<string, object>(); /// <summary> /// Initializes a new instance of the <see cref="FirefoxOptions"/> class. /// </summary> public FirefoxOptions() : base() { this.BrowserName = BrowserNameValue; this.AddKnownCapabilityName(FirefoxOptions.FirefoxOptionsCapability, "current FirefoxOptions class instance"); this.AddKnownCapabilityName(FirefoxOptions.IsMarionetteCapability, "UseLegacyImplementation property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxProfileCapability, "Profile property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxBinaryCapability, "BrowserExecutableLocation property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxArgumentsCapability, "AddArguments method"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxPrefsCapability, "SetPreference method"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxLogCapability, "LogLevel property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxLegacyProfileCapability, "Profile property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxLegacyBinaryCapability, "BrowserExecutableLocation property"); } /// <summary> /// Initializes a new instance of the <see cref="FirefoxOptions"/> class for the given profile and binary. /// </summary> /// <param name="profile">The <see cref="FirefoxProfile"/> to use in the options.</param> /// <param name="binary">The <see cref="FirefoxBinary"/> to use in the options.</param> /// <param name="capabilities">The <see cref="DesiredCapabilities"/> to copy into the options.</param> internal FirefoxOptions(FirefoxProfile profile, FirefoxBinary binary, DesiredCapabilities capabilities) { this.BrowserName = BrowserNameValue; if (profile != null) { this.profile = profile; } if (binary != null) { this.browserBinaryLocation = binary.BinaryExecutable.ExecutablePath; } if (capabilities != null) { this.ImportCapabilities(capabilities); } } /// <summary> /// Gets or sets a value indicating whether to use the legacy driver implementation. /// </summary> public bool UseLegacyImplementation { get { return !this.isMarionette; } set { this.isMarionette = !value; } } /// <summary> /// Gets or sets the <see cref="FirefoxProfile"/> object to be used with this instance. /// </summary> public FirefoxProfile Profile { get { return this.profile; } set { this.profile = value; } } /// <summary> /// Gets or sets the path and file name of the Firefox browser executable. /// </summary> public string BrowserExecutableLocation { get { return this.browserBinaryLocation; } set { this.browserBinaryLocation = value; } } /// <summary> /// Gets or sets the logging level of the Firefox driver. /// </summary> public FirefoxDriverLogLevel LogLevel { get { return this.logLevel; } set { this.logLevel = value; } } /// <summary> /// Adds an argument to be used in launching the Firefox browser. /// </summary> /// <param name="argumentName">The argument to add.</param> /// <remarks>Arguments must be preceeded by two dashes ("--").</remarks> public void AddArgument(string argumentName) { if (string.IsNullOrEmpty(argumentName)) { throw new ArgumentException("argumentName must not be null or empty", "argumentName"); } this.AddArguments(argumentName); } /// <summary> /// Adds a list arguments to be used in launching the Firefox browser. /// </summary> /// <param name="argumentsToAdd">An array of arguments to add.</param> /// <remarks>Each argument must be preceeded by two dashes ("--").</remarks> public void AddArguments(params string[] argumentsToAdd) { this.AddArguments(new List<string>(argumentsToAdd)); } /// <summary> /// Adds a list arguments to be used in launching the Firefox browser. /// </summary> /// <param name="argumentsToAdd">An array of arguments to add.</param> /// <remarks>Each argument must be preceeded by two dashes ("--").</remarks> public void AddArguments(IEnumerable<string> argumentsToAdd) { if (argumentsToAdd == null) { throw new ArgumentNullException("argumentsToAdd", "argumentsToAdd must not be null"); } this.firefoxArguments.AddRange(argumentsToAdd); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, bool preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, int preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, long preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, double preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, string preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Provides a means to add additional capabilities not yet added as type safe options /// for the Chrome driver. /// </summary> /// <param name="capabilityName">The name of the capability to add.</param> /// <param name="capabilityValue">The value of the capability to add.</param> /// <exception cref="ArgumentException"> /// thrown when attempting to add a capability for which there is already a type safe option, or /// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string. /// </exception> /// <remarks>Calling <see cref="AddAdditionalCapability(string, object)"/> /// where <paramref name="capabilityName"/> has already been added will overwrite the /// existing value with the new value in <paramref name="capabilityValue"/>. /// Also, by default, calling this method adds capabilities to the options object passed to /// geckodriver.exe.</remarks> public override void AddAdditionalCapability(string capabilityName, object capabilityValue) { // Add the capability to the chromeOptions object by default. This is to handle // the 80% case where the chromedriver team adds a new option in chromedriver.exe // and the bindings have not yet had a type safe option added. this.AddAdditionalCapability(capabilityName, capabilityValue, false); } /// <summary> /// Provides a means to add additional capabilities not yet added as type safe options /// for the Firefox driver. /// </summary> /// <param name="capabilityName">The name of the capability to add.</param> /// <param name="capabilityValue">The value of the capability to add.</param> /// <param name="isGlobalCapability">Indicates whether the capability is to be set as a global /// capability for the driver instead of a Firefox-specific option.</param> /// <exception cref="ArgumentException"> /// thrown when attempting to add a capability for which there is already a type safe option, or /// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string. /// </exception> /// <remarks>Calling <see cref="AddAdditionalCapability(string, object, bool)"/> /// where <paramref name="capabilityName"/> has already been added will overwrite the /// existing value with the new value in <paramref name="capabilityValue"/></remarks> public void AddAdditionalCapability(string capabilityName, object capabilityValue, bool isGlobalCapability) { if (this.IsKnownCapabilityName(capabilityName)) { string typeSafeOptionName = this.GetTypeSafeOptionName(capabilityName); string message = string.Format(CultureInfo.InvariantCulture, "There is already an option for the {0} capability. Please use the {1} instead.", capabilityName, typeSafeOptionName); throw new ArgumentException(message, "capabilityName"); } if (string.IsNullOrEmpty(capabilityName)) { throw new ArgumentException("Capability name may not be null an empty string.", "capabilityName"); } if (isGlobalCapability) { this.additionalCapabilities[capabilityName] = capabilityValue; } else { this.additionalFirefoxOptions[capabilityName] = capabilityValue; } } /// <summary> /// Returns DesiredCapabilities for Firefox with these options included as /// capabilities. This does not copy the options. Further changes will be /// reflected in the returned capabilities. /// </summary> /// <returns>The DesiredCapabilities for Firefox with these options.</returns> public override ICapabilities ToCapabilities() { DesiredCapabilities capabilities = GenerateDesiredCapabilities(this.isMarionette); if (this.isMarionette) { Dictionary<string, object> firefoxOptions = this.GenerateFirefoxOptionsDictionary(); capabilities.SetCapability(FirefoxOptionsCapability, firefoxOptions); } else { if (this.profile != null) { if (this.Proxy != null) { this.profile.InternalSetProxyPreferences(this.Proxy); } capabilities.SetCapability(FirefoxProfileCapability, this.profile.ToBase64String()); } if (!string.IsNullOrEmpty(this.browserBinaryLocation)) { capabilities.SetCapability(FirefoxBinaryCapability, this.browserBinaryLocation); } else { using (FirefoxBinary executablePathBinary = new FirefoxBinary()) { string executablePath = executablePathBinary.BinaryExecutable.ExecutablePath; capabilities.SetCapability(FirefoxBinaryCapability, executablePath); } } } foreach (KeyValuePair<string, object> pair in this.additionalCapabilities) { capabilities.SetCapability(pair.Key, pair.Value); } return capabilities; } private Dictionary<string, object> GenerateFirefoxOptionsDictionary() { Dictionary<string, object> firefoxOptions = new Dictionary<string, object>(); if (this.profile != null) { firefoxOptions[FirefoxProfileCapability] = this.profile.ToBase64String(); } if (!string.IsNullOrEmpty(this.browserBinaryLocation)) { firefoxOptions[FirefoxBinaryCapability] = this.browserBinaryLocation; } else { if (!this.isMarionette) { using (FirefoxBinary executablePathBinary = new FirefoxBinary()) { string executablePath = executablePathBinary.BinaryExecutable.ExecutablePath; if (!string.IsNullOrEmpty(executablePath)) { firefoxOptions[FirefoxBinaryCapability] = executablePath; } } } } if (this.logLevel != FirefoxDriverLogLevel.Default) { Dictionary<string, object> logObject = new Dictionary<string, object>(); logObject["level"] = this.logLevel.ToString().ToLowerInvariant(); firefoxOptions[FirefoxLogCapability] = logObject; } if (this.firefoxArguments.Count > 0) { List<object> args = new List<object>(); foreach (string argument in this.firefoxArguments) { args.Add(argument); } firefoxOptions[FirefoxArgumentsCapability] = args; } if (this.profilePreferences.Count > 0) { firefoxOptions[FirefoxPrefsCapability] = this.profilePreferences; } foreach (KeyValuePair<string, object> pair in this.additionalFirefoxOptions) { firefoxOptions.Add(pair.Key, pair.Value); } return firefoxOptions; } private void SetPreferenceValue(string preferenceName, object preferenceValue) { if (string.IsNullOrEmpty(preferenceName)) { throw new ArgumentException("Preference name may not be null an empty string.", "preferenceName"); } if (!this.isMarionette) { throw new ArgumentException("Preferences cannot be set directly when using the legacy FirefoxDriver implementation. Set them in the profile."); } this.profilePreferences[preferenceName] = preferenceValue; } private void ImportCapabilities(DesiredCapabilities capabilities) { foreach (KeyValuePair<string, object> pair in capabilities.CapabilitiesDictionary) { if (pair.Key == CapabilityType.BrowserName) { } else if (pair.Key == CapabilityType.BrowserVersion) { this.BrowserVersion = pair.Value.ToString(); } else if (pair.Key == CapabilityType.PlatformName) { this.PlatformName = pair.Value.ToString(); } else if (pair.Key == CapabilityType.Proxy) { this.Proxy = new Proxy(pair.Value as Dictionary<string, object>); } else if (pair.Key == CapabilityType.UnhandledPromptBehavior) { this.UnhandledPromptBehavior = (UnhandledPromptBehavior)Enum.Parse(typeof(UnhandledPromptBehavior), pair.Value.ToString(), true); } else if (pair.Key == CapabilityType.PageLoadStrategy) { this.PageLoadStrategy = (PageLoadStrategy)Enum.Parse(typeof(PageLoadStrategy), pair.Value.ToString(), true); } else if (pair.Key == FirefoxOptionsCapability) { Dictionary<string, object> mozFirefoxOptions = pair.Value as Dictionary<string, object>; foreach (KeyValuePair<string, object> option in mozFirefoxOptions) { if (option.Key == FirefoxArgumentsCapability) { object[] args = option.Value as object[]; for (int i = 0; i < args.Length; i++) { this.firefoxArguments.Add(args[i].ToString()); } } else if (option.Key == FirefoxPrefsCapability) { this.profilePreferences = option.Value as Dictionary<string, object>; } else if (option.Key == FirefoxLogCapability) { Dictionary<string, object> logDictionary = option.Value as Dictionary<string, object>; if (logDictionary.ContainsKey("level")) { this.logLevel = (FirefoxDriverLogLevel)Enum.Parse(typeof(FirefoxDriverLogLevel), logDictionary["level"].ToString(), true); } } else if (option.Key == FirefoxBinaryCapability) { this.browserBinaryLocation = option.Value.ToString(); } else if (option.Key == FirefoxProfileCapability) { this.profile = FirefoxProfile.FromBase64String(option.Value.ToString()); } else { this.AddAdditionalCapability(option.Key, option.Value); } } } else { this.AddAdditionalCapability(pair.Key, pair.Value, true); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** A specially designed handle wrapper to ensure we never leak ** an OS handle. The runtime treats this class specially during ** P/Invoke marshaling and finalization. Users should write ** subclasses of SafeHandle for each distinct handle type. ** ** ===========================================================*/ using System; using System.Threading; namespace System.Runtime.InteropServices { /* Problems addressed by the SafeHandle class: 1) Critical finalization - ensure we never leak OS resources in SQL. Done without running truly arbitrary & unbounded amounts of managed code. 2) Reduced graph promotion - during finalization, keep object graph small 3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread race (HandleRef) 4) Elimination of security races w/ explicit calls to Close (HandleProtector) 5) Enforcement of the above via the type system - Don't use IntPtr anymore. 6) Allows the handle lifetime to be controlled externally via a boolean. Subclasses of SafeHandle will implement the ReleaseHandle abstract method used to execute any code required to free the handle. This method will be prepared as a constrained execution region at instance construction time (along with all the methods in its statically determinable call graph). This implies that we won't get any inconvenient jit allocation errors or rude thread abort interrupts while releasing the handle but the user must still write careful code to avoid injecting fault paths of their own (see the CER spec for more details). In particular, any sub-methods you call should be decorated with a reliability contract of the appropriate level. In most cases this should be: ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success) Also, any P/Invoke methods should use the SuppressUnmanagedCodeSecurity attribute to avoid a runtime security check that can also inject failures (even if the check is guaranteed to pass). The GC will run ReleaseHandle methods after any normal finalizers have been run for objects that were collected at the same time. This ensures classes like FileStream can run a normal finalizer to flush out existing buffered data. This is key - it means adding this class to a class like FileStream does not alter our current semantics w.r.t. finalization today. Subclasses must also implement the IsInvalid property so that the infrastructure can tell when critical finalization is actually required. Again, this method is prepared ahead of time. It's envisioned that direct subclasses of SafeHandle will provide an IsInvalid implementation that suits the general type of handle they support (null is invalid, -1 is invalid etc.) and then these classes will be further derived for specific safe handle types. Most classes using SafeHandle should not provide a finalizer. If they do need to do so (ie, for flushing out file buffers, needing to write some data back into memory, etc), then they can provide a finalizer that will be guaranteed to run before the SafeHandle's critical finalizer. Note that SafeHandle's ReleaseHandle is called from a constrained execution region, and is eagerly prepared before we create your class. This means you should only call methods with an appropriate reliability contract from your ReleaseHandle method. Subclasses are expected to be written as follows (note that SuppressUnmanagedCodeSecurity should always be used on any P/Invoke methods invoked as part of ReleaseHandle, in order to switch the security check from runtime to jit time and thus remove a possible failure path from the invocation of the method): internal sealed MySafeHandleSubclass : SafeHandle { // Called by P/Invoke when returning SafeHandles private MySafeHandleSubclass() : base(IntPtr.Zero, true) { } // If & only if you need to support user-supplied handles internal MySafeHandleSubclass(IntPtr preexistingHandle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) { SetHandle(preexistingHandle); } // Do not provide a finalizer - SafeHandle's critical finalizer will // call ReleaseHandle for you. public override bool IsInvalid { get { return handle == IntPtr.Zero; } } override protected bool ReleaseHandle() { return MyNativeMethods.CloseHandle(handle); } } Then elsewhere to create one of these SafeHandles, define a method with the following type of signature (CreateFile follows this model). Note that when returning a SafeHandle like this, P/Invoke will call your class's default constructor. Also, you probably want to define CloseHandle somewhere, and remember to apply a reliability contract to it. [SuppressUnmanagedCodeSecurity] internal static class MyNativeMethods { [DllImport(Win32Native.CORE_HANDLE)] private static extern MySafeHandleSubclass CreateHandle(int someState); [DllImport(Win32Native.CORE_HANDLE, SetLastError=true), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static extern bool CloseHandle(IntPtr handle); } Drawbacks with this implementation: 1) Requires some magic to run the critical finalizer. */ public abstract class SafeHandle : IDisposable { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")] protected IntPtr handle; // PUBLICLY DOCUMENTED handle field private int _state; // Combined ref count and closed/disposed flags (so we can atomically modify them). private bool _ownsHandle; // Whether we can release this handle. // Bitmasks for the _state field above. private static class StateBits { public const int Closed = 0x00000001; public const int Disposed = 0x00000002; public const int RefCount = unchecked((int)0xfffffffc); public const int RefCountOne = 4; // Amount to increment state field to yield a ref count increment of 1 }; // Creates a SafeHandle class. Users must then set the Handle property. // To prevent the SafeHandle from being freed, write a subclass that // doesn't define a finalizer. protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle) { handle = invalidHandleValue; _state = StateBits.RefCountOne; // Ref count 1 and not closed or disposed. _ownsHandle = ownsHandle; if (!ownsHandle) GC.SuppressFinalize(this); } // // The handle cannot be closed until we are sure that no other objects might // be using it. In the case of finalization, there may be other objects in // the finalization queue that still hold a reference to this SafeHandle. // So we can't assume that just because our finalizer is running, no other // object will need to access this handle. // // The CLR solves this by having SafeHandle derive from CriticalFinalizerObject. // This ensures that SafeHandle's finalizer will run only after all "normal" // finalizers in the queue. But MRT doesn't support CriticalFinalizerObject, or // any other explicit control of finalization order. // // For now, we'll hack this by not releasing the handle when our finalizer // is called. Instead, we create a new DelayedFinalizer instance, whose // finalizer will release the handle. Thus the handle won't be released in this // finalization cycle, but should be released in the next. // // This has the effect of delaying cleanup for much longer than would have // happened on the CLR. This also means that we may not close some handles // at shutdown, since there may not be another finalization cycle to run // the delayed finalizer. If either of these end up being a problem, we should // consider adding more control over finalization order to MRT (or, better, // turning over control of finalization ordering to System.Private.CoreLib). // private class DelayedFinalizer { private SafeHandle _safeHandle; public DelayedFinalizer(SafeHandle safeHandle) { _safeHandle = safeHandle; } ~DelayedFinalizer() { _safeHandle.Dispose(false); } } ~SafeHandle() { new DelayedFinalizer(this); } // Keep the 'handle' variable named 'handle' to make sure it matches the surface area protected void SetHandle(IntPtr handle) { this.handle = handle; } // Used by Interop marshalling code internal void InitializeHandle(IntPtr _handle) { // The SafeHandle should be invalid to be able to initialize it System.Diagnostics.Debug.Assert(IsInvalid); handle = _handle; } // This method is necessary for getting an IntPtr out of a SafeHandle. // Used to tell whether a call to create the handle succeeded by comparing // the handle against a known invalid value, and for backwards // compatibility to support the handle properties returning IntPtrs on // many of our Framework classes. // Note that this method is dangerous for two reasons: // 1) If the handle has been marked invalid with SetHandleasInvalid, // DangerousGetHandle will still return the original handle value. // 2) The handle returned may be recycled at any point. At best this means // the handle might stop working suddenly. At worst, if the handle or // the resource the handle represents is exposed to untrusted code in // any way, this can lead to a handle recycling security attack (i.e. an // untrusted caller can query data on the handle you've just returned // and get back information for an entirely unrelated resource). public IntPtr DangerousGetHandle() { return handle; } public bool IsClosed { get { return (_state & StateBits.Closed) == StateBits.Closed; } } public abstract bool IsInvalid { get; } internal void Close() { Dispose(true); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { InternalRelease(true); GC.SuppressFinalize(this); } public void SetHandleAsInvalid() { int oldState, newState; do { oldState = _state; if ((oldState & StateBits.Closed) != 0) return; newState = oldState | StateBits.Closed; } while (Interlocked.CompareExchange(ref _state, newState, oldState) != oldState); } // Implement this abstract method in your derived class to specify how to // free the handle. Be careful not write any code that's subject to faults // in this method (the runtime will prepare the infrastructure for you so // that no jit allocations etc. will occur, but don't allocate memory unless // you can deal with the failure and still free the handle). // The boolean returned should be true for success and false if the runtime // should fire a SafeHandleCriticalFailure MDA (CustomerDebugProbe) if that // MDA is enabled. protected abstract bool ReleaseHandle(); // Add a reason why this handle should not be relinquished (i.e. have // ReleaseHandle called on it). This method has dangerous in the name since // it must always be used carefully (e.g. called within a CER) to avoid // leakage of the handle. It returns a boolean indicating whether the // increment was actually performed to make it easy for program logic to // back out in failure cases (i.e. is a call to DangerousRelease needed). // It is passed back via a ref parameter rather than as a direct return so // that callers need not worry about the atomicity of calling the routine // and assigning the return value to a variable (the variable should be // explicitly set to false prior to the call). The only failure cases are // when the method is interrupted prior to processing by a thread abort or // when the handle has already been (or is in the process of being) // released. public void DangerousAddRef(ref bool success) { DangerousAddRef_WithNoNullCheck(); success = true; } // Partner to DangerousAddRef. This should always be successful when used in // a correct manner (i.e. matching a successful DangerousAddRef and called // from a region such as a CER where a thread abort cannot interrupt // processing). In the same way that unbalanced DangerousAddRef calls can // cause resource leakage, unbalanced DangerousRelease calls may cause // invalid handle states to become visible to other threads. This // constitutes a potential security hole (via handle recycling) as well as a // correctness problem -- so don't ever expose Dangerous* calls out to // untrusted code. public void DangerousRelease() { InternalRelease(false); } // Do not call this directly - only call through the extension method SafeHandleExtensions.DangerousAddRef. internal void DangerousAddRef_WithNoNullCheck() { // To prevent handle recycling security attacks we must enforce the // following invariant: we cannot successfully AddRef a handle on which // we've committed to the process of releasing. // We ensure this by never AddRef'ing a handle that is marked closed and // never marking a handle as closed while the ref count is non-zero. For // this to be thread safe we must perform inspection/updates of the two // values as a single atomic operation. We achieve this by storing them both // in a single aligned DWORD and modifying the entire state via interlocked // compare exchange operations. // Additionally we have to deal with the problem of the Dispose operation. // We must assume that this operation is directly exposed to untrusted // callers and that malicious callers will try and use what is basically a // Release call to decrement the ref count to zero and free the handle while // it's still in use (the other way a handle recycling attack can be // mounted). We combat this by allowing only one Dispose to operate against // a given safe handle (which balances the creation operation given that // Dispose suppresses finalization). We record the fact that a Dispose has // been requested in the same state field as the ref count and closed state. // So the state field ends up looking like this: // // 31 2 1 0 // +-----------------------------------------------------------+---+---+ // | Ref count | D | C | // +-----------------------------------------------------------+---+---+ // // Where D = 1 means a Dispose has been performed and C = 1 means the // underlying handle has (or will be shortly) released. // Might have to perform the following steps multiple times due to // interference from other AddRef's and Release's. int oldState, newState; do { // First step is to read the current handle state. We use this as a // basis to decide whether an AddRef is legal and, if so, to propose an // update predicated on the initial state (a conditional write). oldState = _state; // Check for closed state. if ((oldState & StateBits.Closed) != 0) { throw new ObjectDisposedException("SafeHandle"); } // Not closed, let's propose an update (to the ref count, just add // StateBits.RefCountOne to the state to effectively add 1 to the ref count). // Continue doing this until the update succeeds (because nobody // modifies the state field between the read and write operations) or // the state moves to closed. newState = oldState + StateBits.RefCountOne; } while (Interlocked.CompareExchange(ref _state, newState, oldState) != oldState); // If we got here we managed to update the ref count while the state // remained non closed. So we're done. } private void InternalRelease(bool fDispose) { // See AddRef above for the design of the synchronization here. Basically we // will try to decrement the current ref count and, if that would take us to // zero refs, set the closed state on the handle as well. bool fPerformRelease = false; // Might have to perform the following steps multiple times due to // interference from other AddRef's and Release's. int oldState, newState; do { // First step is to read the current handle state. We use this cached // value to predicate any modification we might decide to make to the // state). oldState = _state; // If this is a Dispose operation we have additional requirements (to // ensure that Dispose happens at most once as the comments in AddRef // detail). We must check that the dispose bit is not set in the old // state and, in the case of successful state update, leave the disposed // bit set. Silently do nothing if Dispose has already been called // (because we advertise that as a semantic of Dispose). if (fDispose && ((oldState & StateBits.Disposed) != 0)) return; // We should never see a ref count of zero (that would imply we have // unbalanced AddRef and Releases). (We might see a closed state before // hitting zero though -- that can happen if SetHandleAsInvalid is // used). if ((oldState & StateBits.RefCount) == 0) { throw new ObjectDisposedException("SafeHandle"); } // If we're proposing a decrement to zero and the handle is not closed // and we own the handle then we need to release the handle upon a // successful state update. fPerformRelease = ((oldState & (StateBits.RefCount | StateBits.Closed)) == StateBits.RefCountOne); fPerformRelease &= _ownsHandle; // If so we need to check whether the handle is currently invalid by // asking the SafeHandle subclass. We must do this *before* // transitioning the handle to closed, however, since setting the closed // state will cause IsInvalid to always return true. if (fPerformRelease && IsInvalid) fPerformRelease = false; // Attempt the update to the new state, fail and retry if the initial // state has been modified in the meantime. Decrement the ref count by // substracting StateBits.RefCountOne from the state then OR in the bits for // Dispose (if that's the reason for the Release) and closed (if the // initial ref count was 1). newState = (oldState - StateBits.RefCountOne) | ((oldState & StateBits.RefCount) == StateBits.RefCountOne ? StateBits.Closed : 0) | (fDispose ? StateBits.Disposed : 0); } while (Interlocked.CompareExchange(ref _state, newState, oldState) != oldState); // If we get here we successfully decremented the ref count. Additonally we // may have decremented it to zero and set the handle state as closed. In // this case (providng we own the handle) we will call the ReleaseHandle // method on the SafeHandle subclass. if (fPerformRelease) ReleaseHandle(); } } internal static class SafeHandleExtensions { public static void DangerousAddRef(this SafeHandle safeHandle) { // This check provides rough compatibility with the desktop code (this code's desktop counterpart is AcquireSafeHandleFromWaitHandle() inside clr.dll) // which throws ObjectDisposed if someone passes an uninitialized WaitHandle into one of the Wait apis. We use an extension method // because otherwise, the "null this" would trigger a NullReferenceException before we ever get to this check. if (safeHandle == null) throw new ObjectDisposedException(SR.ObjectDisposed_Generic); safeHandle.DangerousAddRef_WithNoNullCheck(); } } }
using System; using System.Collections; using System.Linq; using UnityEngine; namespace UnityTest { [Serializable] public class AssertionComponent : MonoBehaviour { [Flags] public enum CheckMethod { AfterPeriodOfTime = 1 << 0, Start = 1 << 1, Update = 1 << 2, FixedUpdate = 1 << 3, LateUpdate = 1 << 4, OnDestroy = 1 << 5, OnEnable = 1 << 6, OnDisable = 1 << 7, OnControllerColliderHit = 1 << 8, OnParticleCollision = 1 << 9, OnJointBreak = 1 << 10, OnBecameInvisible = 1 << 11, OnBecameVisible = 1 << 12, OnTriggerEnter = 1 << 13, OnTriggerExit = 1 << 14, OnTriggerStay = 1 << 15, OnCollisionEnter = 1 << 16, OnCollisionExit = 1 << 17, OnCollisionStay = 1 << 18, #if !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2 OnTriggerEnter2D = 1 << 19, OnTriggerExit2D = 1 << 20, OnTriggerStay2D = 1 << 21, OnCollisionEnter2D = 1 << 22, OnCollisionExit2D = 1 << 23, OnCollisionStay2D = 1 << 24, #endif } [SerializeField] public float checkAfterTime = 1f; [SerializeField] public bool repeatCheckTime = true; [SerializeField] public float repeatEveryTime = 1f; [SerializeField] public int checkAfterFrames = 1; [SerializeField] public bool repeatCheckFrame = true; [SerializeField] public int repeatEveryFrame = 1; [SerializeField] public bool hasFailed; [SerializeField] public CheckMethod checkMethods = CheckMethod.Start; [SerializeField] private ActionBase m_ActionBase; [SerializeField] public int checksPerformed = 0; private int checkOnFrame = 0; public ActionBase Action { get { return m_ActionBase; } set { m_ActionBase = value; m_ActionBase.go = gameObject; m_ActionBase.thisPropertyPath = ""; if (m_ActionBase is ComparerBase) (m_ActionBase as ComparerBase).otherPropertyPath = ""; } } public void Awake () { if (!Debug.isDebugBuild) Destroy (this); OnComponentCopy (); } #if UNITY_EDITOR public void OnValidate () { OnComponentCopy (); } #endif private void OnComponentCopy () { if (m_ActionBase == null) return; var oldAction = FindObjectsOfType (typeof (AssertionComponent)).Where (o => ((AssertionComponent) o).m_ActionBase == m_ActionBase && o != this); //if it's not a copy but a new component don't do anything if (!oldAction.Any ()) return; if (oldAction.Count () > 1) Debug.LogWarning ("More than one refence to comparer found. This shouldn't happen"); m_ActionBase = ((AssertionComponent) oldAction.Single ()).m_ActionBase.CreateCopy (); } public void Start () { CheckAssertionFor (CheckMethod.Start); if(IsCheckMethodSelected(CheckMethod.AfterPeriodOfTime)) { StartCoroutine("CheckPeriodically"); } if(IsCheckMethodSelected (CheckMethod.Update)) { checkOnFrame = Time.frameCount + checkAfterFrames; } } public IEnumerator CheckPeriodically() { yield return new WaitForSeconds(checkAfterTime); CheckAssertionFor(CheckMethod.AfterPeriodOfTime); while (repeatCheckTime) { yield return new WaitForSeconds(repeatEveryTime); CheckAssertionFor(CheckMethod.AfterPeriodOfTime); } } public bool ShouldCheckOnFrame() { if (Time.frameCount > checkOnFrame) { if (repeatCheckFrame) checkOnFrame += repeatEveryFrame; return true; } return false; } public void OnDisable () { CheckAssertionFor (CheckMethod.OnDisable); } public void OnEnable () { CheckAssertionFor (CheckMethod.OnEnable); } public void OnDestroy () { CheckAssertionFor (CheckMethod.OnDestroy); } public void Update () { if (IsCheckMethodSelected(CheckMethod.Update) && ShouldCheckOnFrame ()) { CheckAssertionFor (CheckMethod.Update); } } public void FixedUpdate () { CheckAssertionFor(CheckMethod.FixedUpdate); } public void LateUpdate () { CheckAssertionFor (CheckMethod.LateUpdate); } public void OnControllerColliderHit () { CheckAssertionFor (CheckMethod.OnControllerColliderHit); } public void OnParticleCollision () { CheckAssertionFor (CheckMethod.OnParticleCollision); } public void OnJointBreak () { CheckAssertionFor (CheckMethod.OnJointBreak); } public void OnBecameInvisible () { CheckAssertionFor (CheckMethod.OnBecameInvisible); } public void OnBecameVisible () { CheckAssertionFor (CheckMethod.OnBecameVisible); } public void OnTriggerEnter () { CheckAssertionFor (CheckMethod.OnTriggerEnter); } public void OnTriggerExit () { CheckAssertionFor (CheckMethod.OnTriggerExit); } public void OnTriggerStay () { CheckAssertionFor (CheckMethod.OnTriggerStay); } public void OnCollisionEnter () { CheckAssertionFor (CheckMethod.OnCollisionEnter); } public void OnCollisionExit () { CheckAssertionFor (CheckMethod.OnCollisionExit); } public void OnCollisionStay () { CheckAssertionFor (CheckMethod.OnCollisionStay); } #if !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2 public void OnTriggerEnter2D () { CheckAssertionFor (CheckMethod.OnTriggerEnter2D); } public void OnTriggerExit2D () { CheckAssertionFor (CheckMethod.OnTriggerExit2D); } public void OnTriggerStay2D () { CheckAssertionFor (CheckMethod.OnTriggerStay2D); } public void OnCollisionEnter2D () { CheckAssertionFor (CheckMethod.OnCollisionEnter2D); } public void OnCollisionExit2D () { CheckAssertionFor (CheckMethod.OnCollisionExit2D); } public void OnCollisionStay2D () { CheckAssertionFor (CheckMethod.OnCollisionStay2D); } #endif private void CheckAssertionFor (CheckMethod checkMethod) { if (IsCheckMethodSelected (checkMethod)) { Assertions.CheckAssertions (this); } } public bool IsCheckMethodSelected (CheckMethod method) { return method == (checkMethods & method); } } }
/* Copyright (c) 2004-2006 Jan Benda and Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Text; using System.Threading; using System.Collections; using System.ComponentModel; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using PHP.Core; using PHP.Core.Reflection; #if SILVERLIGHT using PHP.CoreCLR; #endif namespace PHP.Library { #region Directory user-class /// <summary> /// User-like class encapsulating enumeration of a Directory. /// Uses the PhpDiretory implementation upon PhpWrapper streams. /// </summary> #if !SILVERLIGHT [Serializable] #endif [ImplementsType] public class Directory : PhpObject { #region Fields /// <summary> /// Reference to the directory listing resource. /// </summary> public PhpReference handle = new PhpSmartReference(); /// <summary> /// The opened path (accessible from the PHP script). /// </summary> public PhpReference path = new PhpSmartReference(); #endregion #region Construction /// <summary> /// Start listing of a directory (intended to be used from C#). /// </summary> /// <param name="directory">The path to the directory.</param> public Directory(string directory) : this(ScriptContext.CurrentContext, true) { this.path = new PhpReference(directory); this.handle = new PhpReference(PhpDirectory.Open(directory)); } /// <summary> /// For internal purposes only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public Directory(ScriptContext context, bool newInstance) : base(context, newInstance) { } /// <summary> /// For internal purposes only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public Directory(ScriptContext context, DTypeDesc caller) : base(context, caller) { } #if !SILVERLIGHT /// <summary>Deserializing constructor.</summary> protected Directory(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif #endregion #region read /// <summary> /// Read next directory entry. /// </summary> /// <returns>Filename of a contained file (including . and ..).</returns> [ImplementsMethod] [return:CastToFalse] public object read(ScriptContext context, [Optional]object handle) { PhpResource res = (handle == Arg.Default ? this.handle.Value : handle) as PhpResource; if (res == null) { PhpException.InvalidImplicitCast("handle", PhpResource.PhpTypeName, "read"); return null; } return PhpDirectory.Read(res); } #endregion #region rewind /// <summary> /// Restart the directory listing. /// </summary> [ImplementsMethod] public object rewind(ScriptContext context, [Optional]object handle) { PhpResource res = (handle == Arg.Default ? this.handle.Value : handle) as PhpResource; if (res == null) { PhpException.InvalidImplicitCast("handle", PhpResource.PhpTypeName, "rewind"); return null; } PhpDirectory.Rewind(res); return null; } #endregion #region close /// <summary> /// Finish the directory listing. /// </summary> [ImplementsMethod] public object close(ScriptContext context, [Optional]object handle) { PhpResource res = (handle == Arg.Default ? this.handle.Value : handle) as PhpResource; if (res == null) { PhpException.InvalidImplicitCast("handle", PhpResource.PhpTypeName, "close"); return null; } PhpDirectory.Close(res); return null; } #endregion #region Implementation Details /// <summary> /// Populates the provided <see cref="DTypeDesc"/> with this class's methods and properties. /// </summary> /// <param name="typeDesc">The type desc to populate.</param> private static void __PopulateTypeDesc(PhpTypeDesc typeDesc) { typeDesc.AddMethod("read", PhpMemberAttributes.Public, read); typeDesc.AddMethod("rewind", PhpMemberAttributes.Public, rewind); typeDesc.AddMethod("close", PhpMemberAttributes.Public, close); typeDesc.AddProperty("handle", PhpMemberAttributes.Public, (instance) => ((Directory)instance).handle, (instance, value) => ((Directory)instance).handle = (PhpReference)value); typeDesc.AddProperty("path", PhpMemberAttributes.Public, (instance) => ((Directory)instance).path, (instance, value) => ((Directory)instance).path = (PhpReference)value); } /// <summary>Arg-less overload.</summary> [EditorBrowsable(EditorBrowsableState.Never)] public static object read(object instance, PhpStack stack) { switch (stack.ArgCount) { case 0: { stack.RemoveFrame(); return ((Directory)instance).read(stack.Context, Arg.Default) ?? false; } case 1: { stack.CalleeName = "read"; object arg = stack.PeekValue(1); stack.RemoveFrame(); return ((Directory)instance).read(stack.Context, arg) ?? false; } default: { stack.RemoveFrame(); PhpException.InvalidArgumentCount(null, "read"); return null; } } } /// <summary>Arg-less overload.</summary> [EditorBrowsable(EditorBrowsableState.Never)] public static object rewind(object instance, PhpStack stack) { switch (stack.ArgCount) { case 0: { stack.RemoveFrame(); ((Directory)instance).rewind(stack.Context, Arg.Default); break; } case 1: { stack.CalleeName = "rewind"; object arg = stack.PeekValue(1); stack.RemoveFrame(); ((Directory)instance).rewind(stack.Context, arg); break; } default: { stack.RemoveFrame(); PhpException.InvalidArgumentCount(null, "rewind"); break; } } return null; } /// <summary>Arg-less overload.</summary> [EditorBrowsable(EditorBrowsableState.Never)] public static object close(object instance, PhpStack stack) { switch (stack.ArgCount) { case 0: { stack.RemoveFrame(); ((Directory)instance).close(stack.Context, Arg.Default); break; } case 1: { stack.CalleeName = "close"; object arg = stack.PeekValue(1); stack.RemoveFrame(); ((Directory)instance).close(stack.Context, arg); break; } default: { stack.RemoveFrame(); PhpException.InvalidArgumentCount(null, "close"); break; } } return null; } #endregion } #endregion #region DirectoryListing /// <summary> /// Enumeration class used for PhpDirectory listings - serves as a PhpResource. /// Uses the PhpWrapper stream wrappers only to generate the list of contained files. /// No actual resources to be released explicitly. /// </summary> internal sealed class DirectoryListing : PhpResource { public DirectoryListing(string[] listing) : base(DirectoryListingName) { this.Listing = listing; if (listing != null) { this.Enumerator = listing.GetEnumerator(); this.Enumerator.Reset(); } else { this.Close(); // Invalid resource } } protected override void FreeManaged() { if (object.ReferenceEquals(this, PhpDirectory.lastDirHandle)) PhpDirectory.lastDirHandle = null; } public readonly string[] Listing; public readonly System.Collections.IEnumerator Enumerator; private const string DirectoryListingName = "stream"; //private static int DirectoryListingType = PhpResource.RegisterType(DirectoryListingName); // Note: PHP uses the stream mechanism listings (opendir etc.) // this is the same but a) faster, b) more memory expensive for large directories // (and unfinished listings in script) } #endregion /// <summary> /// Gives access to the directory manipulation and itereation. /// </summary> /// <threadsafety static="true"/> public static class PhpDirectory { #region Browsing (getcwd, chdir, NS: chroot) /// <summary>Gets the virtual working directory of the current script.</summary> /// <remarks></remarks> /// <returns>Absolute path to the current directory.</returns> [ImplementsFunction("getcwd")] public static string GetWorking() { string result = ScriptContext.CurrentContext.WorkingDirectory; return (result != null) ? result : ""; } /// <summary>Changes the virtual working directory for the current script.</summary> /// <param name="directory">Absolute or relative path to the new working directory.</param> /// <returns>Returns <c>true</c> on success or <c>false</c> on failure.</returns> /// <exception cref="PhpException">If the specified directory does not exist.</exception> [ImplementsFunction("chdir")] public static bool SetWorking(string directory) { if (directory != null) { string newPath = PhpPath.AbsolutePath(directory); if (System.IO.Directory.Exists(newPath)) { // Note: open_basedir not applied here, URL will not pass through ScriptContext.CurrentContext.WorkingDirectory = newPath; return true; } } PhpException.Throw(PhpError.Warning, LibResources.GetString("directory_not_found", directory)); return false; } /// <summary> /// Changes the root directory of the current process to <paramref name="directory"/>. /// Not supported. /// </summary> /// <remarks> /// This function is only available if your system supports it /// and you're using the CLI, CGI or Embed SAPI. /// Note: This function is not implemented on Windows platforms. /// </remarks> /// <param name="directory">The new value of the root directory.</param> /// <returns>Returns TRUE on success or FALSE on failure.</returns> [ImplementsFunction("chroot", FunctionImplOptions.NotSupported)] [EditorBrowsable(EditorBrowsableState.Never)] public static bool SetRoot(string directory) { PhpException.FunctionNotSupported(); return false; } #endregion #region Iterating (dir, opendir, readdir, rewinddir, closedir, scandir) /// <summary>Returns an object encapsulating the directory listing mechanism on a given /// <paramref name="directory"/>.</summary> /// <remarks>A pseudo-object oriented mechanism for reading a directory. The given directory is opened. /// Two properties are available once the directory has been opened. The handle property /// can be used with other directory functions such as <c>readdir()</c>, <c>rewinddir()</c> and <c>closedir()</c>. /// The path property is set to path the directory that was opened. /// Three methods are available: <see cref="PHP.Library.Directory.read"/>, /// <see cref="PHP.Library.Directory.rewind"/> and <see cref="PHP.Library.Directory.close"/>.</remarks> /// <param name="directory">The path to open for listing.</param> /// <returns>An instance of <see cref="PHP.Library.Directory"/>.</returns> [ImplementsFunction("dir")] public static Directory GetIterator(string directory) { return new Directory(directory); } /// <summary> /// Last handle opened by <c>opendir</c>. /// </summary> [ThreadStatic] internal static PhpResource lastDirHandle; /// <summary>Returns a directory handle to be used in subsequent /// <c>readdir()</c>, <c>rewinddir()</c> and <c>closedir()</c> calls.</summary> /// <remarks> /// <para> /// If path is not a valid directory or the directory can not /// be opened due to permission restrictions or filesystem errors, /// <c>opendir()</c> returns <c>false</c> and generates a PHP error of level <c>E_WARNING</c>. /// </para> /// <para> /// As of PHP 4.3.0 path can also be any URL which supports directory listing, /// however only the <c>file://</c> url wrapper supports this in PHP 4.3. /// As of PHP 5.0.0, support for the <c>ftp://</c> url wrapper is included as well. /// </para> /// </remarks> /// <param name="directory">The path of the directory to be listed.</param> /// <returns>A <see cref="DirectoryListing"/> resource containing the listing.</returns> /// <exception cref="PhpException">In case the specified stream wrapper can not be found /// or the desired directory can not be opened.</exception> [ImplementsFunction("opendir")] [return: CastToFalse] public static PhpResource Open(string directory) { lastDirHandle = null; StreamWrapper wrapper; if (!PhpStream.ResolvePath(ref directory, out wrapper, CheckAccessMode.Directory, CheckAccessOptions.Empty)) return null; string[] listing = wrapper.Listing(directory, 0, null); return (listing != null) ? (lastDirHandle = new DirectoryListing(listing)) : null; } /// <summary> /// Reads an entry from a directory handle. Uses last handle opened by <c>opendir</c>. /// </summary> [ImplementsFunction("readdir")] [return: CastToFalse] public static string Read() { return Read(PhpDirectory.lastDirHandle); } /// <summary> /// Reads an entry from a directory handle. /// </summary> /// <param name="dirHandle">A <see cref="PhpResource"/> returned by <see cref="Open"/>.</param> /// <returns> /// Returns the path of the next file from the directory. /// The filenames (including . and ..) are returned in the order /// in which they are stored by the filesystem. /// </returns> [ImplementsFunction("readdir")] [return: CastToFalse] public static string Read(PhpResource dirHandle) { IEnumerator enumerator = ValidListing(dirHandle); if (enumerator != null && enumerator.MoveNext()) return enumerator.Current.ToString(); else return null; } /// <summary> /// Rewinds a directory handle. Uses last handle opened by <c>opendir</c>. /// </summary> [ImplementsFunction("rewinddir")] public static void Rewind() { Rewind(PhpDirectory.lastDirHandle); } /// <summary> /// Rewinds a directory handle. /// Function has no return value. /// </summary> /// <param name="dirHandle">A <see cref="PhpResource"/> returned by <see cref="Open"/>.</param> /// <remarks> /// Resets the directory stream indicated by <paramref name="dirHandle"/> to the /// beginning of the directory. /// </remarks> [ImplementsFunction("rewinddir")] public static void Rewind(PhpResource dirHandle) { IEnumerator enumerator = ValidListing(dirHandle); if (enumerator == null) return; enumerator.Reset(); } /// <summary> /// Closes a directory handle. Uses last handle opened by <c>opendir</c>. /// </summary> [ImplementsFunction("closedir")] public static void Close() { Close(PhpDirectory.lastDirHandle); } /// <summary> /// Closes a directory handle. /// Function has no return value. /// </summary> /// <param name="dirHandle">A <see cref="PhpResource"/> returned by <see cref="Open"/>.</param> /// <remarks> /// Closes the directory stream indicated by <paramref name="dirHandle"/>. /// The stream must have previously been opened by by <see cref="Open"/>. /// </remarks> [ImplementsFunction("closedir")] public static void Close(PhpResource dirHandle) { // Note: PHP allows other all stream resources to be closed with closedir(). IEnumerator enumerator = ValidListing(dirHandle); if (enumerator == null) return; dirHandle.Close(); // releases the DirectoryListing and sets to invalid. } /// <summary>Lists files and directories inside the specified <paramref name="directory"/>.</summary> /// <remarks> /// Returns an array of files and directories from the <paramref name="directory"/>. /// If <paramref name="directory"/> is not a directory, then boolean <c>false</c> is returned, /// and an error of level <c>E_WARNING</c> is generated. /// </remarks> /// <param name="directory">The directory to be listed.</param> /// <returns>A <see cref="PhpArray"/> of filenames or <c>false</c> in case of failure.</returns> [ImplementsFunction("scandir")] [return: CastToFalse] public static PhpArray Scan(string directory) { return Scan(directory, 0); } /// <summary>Lists files and directories inside the specified path.</summary> /// <remarks> /// Returns an array of files and directories from the <paramref name="directory"/>. /// If <paramref name="directory"/> is not a directory, then boolean <c>false</c> is returned, /// and an error of level <c>E_WARNING</c> is generated. /// </remarks> /// <param name="directory">The directory to be listed.</param> /// <param name="sorting_order"> /// By default, the listing is sorted in ascending alphabetical order. /// If the optional sorting_order is used (set to <c>1</c>), /// then sort order is alphabetical in descending order.</param> /// <returns>A <see cref="PhpArray"/> of filenames or <c>false</c> in case of failure.</returns> /// <exception cref="PhpException">In case the specified stream wrapper can not be found /// or the desired directory can not be opened.</exception> [ImplementsFunction("scandir")] [return: CastToFalse] public static PhpArray Scan(string directory, int sorting_order) { StreamWrapper wrapper; if (!PhpStream.ResolvePath(ref directory, out wrapper, CheckAccessMode.Directory, CheckAccessOptions.Empty)) return null; string[] listing = wrapper.Listing(directory, 0, null); if (listing != null) { PhpArray ret = new PhpArray(listing); // create the array from the system one if (sorting_order == 1) { PhpArrays.ReverseSort(ret, ComparisonMethod.String); } else { PhpArrays.Sort(ret, ComparisonMethod.String); } return ret; } return null; // false } /// <summary> /// Casts the given resource handle to the <see cref="DirectoryListing"/> enumerator. /// Throw an exception when a wrong argument is supplied. /// </summary> /// <param name="dir_handle">The handle passed to a PHP function.</param> /// <returns>The enumerator over the files in the DirectoryListing.</returns> /// <exception cref="PhpException">When the supplied argument is not a valid <see cref="DirectoryListing"/> resource.</exception> private static System.Collections.IEnumerator ValidListing(PhpResource dir_handle) { DirectoryListing listing = dir_handle as DirectoryListing; if (listing != null) return listing.Enumerator; PhpException.Throw(PhpError.Warning, LibResources.GetString("invalid_directory_resource")); return null; } #endregion #region Manipulating (mkdir, rmdir) /// <summary> /// Makes a new directory. /// </summary> /// <param name="pathname">The directory to create.</param> /// <returns><c>true</c> if successful, <c>false</c> otherwise.</returns> [ImplementsFunction("mkdir")] public static bool MakeDirectory(string pathname) { return MakeDirectory(pathname, (int)FileModeFlags.ReadWriteExecute, false, StreamContext.Default); } /// <summary> /// Makes a directory or a branch of directories using the specified wrapper. /// </summary> /// <param name="pathname">The path to create.</param> /// <param name="mode">A combination of <see cref="StreamMakeDirectoryOptions"/>.</param> /// <returns><c>true</c> if successful, <c>false</c> otherwise.</returns> [ImplementsFunction("mkdir")] public static bool MakeDirectory(string pathname, int mode) { return MakeDirectory(pathname, mode, false, StreamContext.Default); } /// <summary> /// /// </summary> /// <param name="pathname"></param> /// <param name="mode"></param> /// <param name="recursive"></param> /// <returns></returns> [ImplementsFunction("mkdir")] public static bool MakeDirectory(string pathname, int mode, bool recursive) { return MakeDirectory(pathname, mode, recursive, StreamContext.Default); } /// <summary> /// /// </summary> /// <param name="pathname"></param> /// <param name="mode"></param> /// <param name="recursive"></param> /// <param name="context"></param> /// <returns></returns> [ImplementsFunction("mkdir")] public static bool MakeDirectory(string pathname, int mode, bool recursive, PhpResource context) { StreamWrapper wrapper; if (!PhpStream.ResolvePath(ref pathname, out wrapper, CheckAccessMode.Directory, CheckAccessOptions.Empty)) return false; return wrapper.MakeDirectory(pathname, mode, recursive ? StreamMakeDirectoryOptions.Recursive : StreamMakeDirectoryOptions.Empty, StreamContext.Default); } /// <summary> /// Removes a directory. /// </summary> /// <param name="dirname"></param> /// <returns><c>true</c> if successful, <c>false</c> otherwise.</returns> [ImplementsFunction("rmdir")] public static bool RemoveDirectory(string dirname) { return RemoveDirectory(dirname, StreamContext.Default); } /// <summary> /// Removes a directory. /// </summary> /// <param name="dirname"></param> /// <param name="context"></param> /// <returns><c>true</c> if successful, <c>false</c> otherwise.</returns> [ImplementsFunction("rmdir")] public static bool RemoveDirectory(string dirname, StreamContext context) { StreamWrapper wrapper; if (!PhpStream.ResolvePath(ref dirname, out wrapper, CheckAccessMode.Directory, CheckAccessOptions.Empty)) return false; return wrapper.RemoveDirectory(dirname, StreamRemoveDirectoryOptions.Empty, StreamContext.Default); } #endregion } }
/* 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.Diagnostics; using System.IO; using System.IO.IsolatedStorage; using System.Net; using System.Runtime.Serialization; using System.Security; using System.Text; using System.Windows; using System.Windows.Media.Imaging; using System.Windows.Resources; namespace WPCordovaClassLib.Cordova.Commands { /// <summary> /// Provides access to isolated storage /// </summary> public class File : BaseCommand { // Error codes public const int NOT_FOUND_ERR = 1; public const int SECURITY_ERR = 2; public const int ABORT_ERR = 3; public const int NOT_READABLE_ERR = 4; public const int ENCODING_ERR = 5; public const int NO_MODIFICATION_ALLOWED_ERR = 6; public const int INVALID_STATE_ERR = 7; public const int SYNTAX_ERR = 8; public const int INVALID_MODIFICATION_ERR = 9; public const int QUOTA_EXCEEDED_ERR = 10; public const int TYPE_MISMATCH_ERR = 11; public const int PATH_EXISTS_ERR = 12; // File system options public const int TEMPORARY = 0; public const int PERSISTENT = 1; public const int RESOURCE = 2; public const int APPLICATION = 3; /// <summary> /// Temporary directory name /// </summary> private readonly string TMP_DIRECTORY_NAME = "tmp"; /// <summary> /// Represents error code for callback /// </summary> [DataContract] public class ErrorCode { /// <summary> /// Error code /// </summary> [DataMember(IsRequired = true, Name = "code")] public int Code { get; set; } /// <summary> /// Creates ErrorCode object /// </summary> public ErrorCode(int code) { this.Code = code; } } /// <summary> /// Represents File action options. /// </summary> [DataContract] public class FileOptions { /// <summary> /// File path /// </summary> /// private string _fileName; [DataMember(Name = "fileName")] public string FilePath { get { return this._fileName; } set { int index = value.IndexOfAny(new char[] { '#', '?' }); this._fileName = index > -1 ? value.Substring(0, index) : value; } } /// <summary> /// Full entryPath /// </summary> [DataMember(Name = "fullPath")] public string FullPath { get; set; } /// <summary> /// Directory name /// </summary> [DataMember(Name = "dirName")] public string DirectoryName { get; set; } /// <summary> /// Path to create file/directory /// </summary> [DataMember(Name = "path")] public string Path { get; set; } /// <summary> /// The encoding to use to encode the file's content. Default is UTF8. /// </summary> [DataMember(Name = "encoding")] public string Encoding { get; set; } /// <summary> /// Uri to get file /// </summary> /// private string _uri; [DataMember(Name = "uri")] public string Uri { get { return this._uri; } set { int index = value.IndexOfAny(new char[] { '#', '?' }); this._uri = index > -1 ? value.Substring(0, index) : value; } } /// <summary> /// Size to truncate file /// </summary> [DataMember(Name = "size")] public long Size { get; set; } /// <summary> /// Data to write in file /// </summary> [DataMember(Name = "data")] public string Data { get; set; } /// <summary> /// Position the writing starts with /// </summary> [DataMember(Name = "position")] public int Position { get; set; } /// <summary> /// Type of file system requested /// </summary> [DataMember(Name = "type")] public int FileSystemType { get; set; } /// <summary> /// New file/directory name /// </summary> [DataMember(Name = "newName")] public string NewName { get; set; } /// <summary> /// Destination directory to copy/move file/directory /// </summary> [DataMember(Name = "parent")] public string Parent { get; set; } /// <summary> /// Options for getFile/getDirectory methods /// </summary> [DataMember(Name = "options")] public CreatingOptions CreatingOpt { get; set; } /// <summary> /// Creates options object with default parameters /// </summary> public FileOptions() { this.SetDefaultValues(new StreamingContext()); } /// <summary> /// Initializes default values for class fields. /// Implemented in separate method because default constructor is not invoked during deserialization. /// </summary> /// <param name="context"></param> [OnDeserializing()] public void SetDefaultValues(StreamingContext context) { this.Encoding = "UTF-8"; this.FilePath = ""; this.FileSystemType = -1; } } /// <summary> /// Stores image info /// </summary> [DataContract] public class FileMetadata { [DataMember(Name = "fileName")] public string FileName { get; set; } [DataMember(Name = "fullPath")] public string FullPath { get; set; } [DataMember(Name = "type")] public string Type { get; set; } [DataMember(Name = "lastModifiedDate")] public string LastModifiedDate { get; set; } [DataMember(Name = "size")] public long Size { get; set; } public FileMetadata(string filePath) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (string.IsNullOrEmpty(filePath)) { throw new FileNotFoundException("File doesn't exist"); } else if (!isoFile.FileExists(filePath)) { // attempt to get it from the resources if (filePath.IndexOf("www") == 0) { Uri fileUri = new Uri(filePath, UriKind.Relative); StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri); if (streamInfo != null) { this.Size = streamInfo.Stream.Length; this.FileName = filePath.Substring(filePath.LastIndexOf("/") + 1); this.FullPath = filePath; } } else { throw new FileNotFoundException("File doesn't exist"); } } else { //TODO get file size the other way if possible using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.Read, isoFile)) { this.Size = stream.Length; } this.FullPath = filePath; this.FileName = System.IO.Path.GetFileName(filePath); this.LastModifiedDate = isoFile.GetLastWriteTime(filePath).DateTime.ToString(); } this.Type = MimeTypeMapper.GetMimeType(this.FileName); } } } /// <summary> /// Represents file or directory modification metadata /// </summary> [DataContract] public class ModificationMetadata { /// <summary> /// Modification time /// </summary> [DataMember] public string modificationTime { get; set; } } /// <summary> /// Represents file or directory entry /// </summary> [DataContract] public class FileEntry { /// <summary> /// File type /// </summary> [DataMember(Name = "isFile")] public bool IsFile { get; set; } /// <summary> /// Directory type /// </summary> [DataMember(Name = "isDirectory")] public bool IsDirectory { get; set; } /// <summary> /// File/directory name /// </summary> [DataMember(Name = "name")] public string Name { get; set; } /// <summary> /// Full path to file/directory /// </summary> [DataMember(Name = "fullPath")] public string FullPath { get; set; } public bool IsResource { get; set; } public static FileEntry GetEntry(string filePath, bool bIsRes = false) { FileEntry entry = null; try { entry = new FileEntry(filePath, bIsRes); } catch (Exception ex) { Debug.WriteLine("Exception in GetEntry for filePath :: " + filePath + " " + ex.Message); } return entry; } /// <summary> /// Creates object and sets necessary properties /// </summary> /// <param name="filePath"></param> public FileEntry(string filePath, bool bIsRes = false) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException(); } if (filePath.Contains(" ")) { Debug.WriteLine("FilePath with spaces :: " + filePath); } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { IsResource = bIsRes; IsFile = isoFile.FileExists(filePath); IsDirectory = isoFile.DirectoryExists(filePath); if (IsFile) { this.Name = Path.GetFileName(filePath); } else if (IsDirectory) { this.Name = this.GetDirectoryName(filePath); if (string.IsNullOrEmpty(Name)) { this.Name = "/"; } } else { if (IsResource) { this.Name = Path.GetFileName(filePath); } else { throw new FileNotFoundException(); } } try { this.FullPath = filePath.Replace('\\', '/'); // new Uri(filePath).LocalPath; } catch (Exception) { this.FullPath = filePath; } } } /// <summary> /// Extracts directory name from path string /// Path should refer to a directory, for example \foo\ or /foo. /// </summary> /// <param name="path"></param> /// <returns></returns> private string GetDirectoryName(string path) { if (String.IsNullOrEmpty(path)) { return path; } string[] split = path.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); if (split.Length < 1) { return null; } else { return split[split.Length - 1]; } } } /// <summary> /// Represents info about requested file system /// </summary> [DataContract] public class FileSystemInfo { /// <summary> /// file system type /// </summary> [DataMember(Name = "name", IsRequired = true)] public string Name { get; set; } /// <summary> /// Root directory entry /// </summary> [DataMember(Name = "root", EmitDefaultValue = false)] public FileEntry Root { get; set; } /// <summary> /// Creates class instance /// </summary> /// <param name="name"></param> /// <param name="rootEntry"> Root directory</param> public FileSystemInfo(string name, FileEntry rootEntry = null) { Name = name; Root = rootEntry; } } [DataContract] public class CreatingOptions { /// <summary> /// Create file/directory if is doesn't exist /// </summary> [DataMember(Name = "create")] public bool Create { get; set; } /// <summary> /// Generate an exception if create=true and file/directory already exists /// </summary> [DataMember(Name = "exclusive")] public bool Exclusive { get; set; } } // returns null value if it fails. private string[] getOptionStrings(string options) { string[] optStings = null; try { optStings = JSON.JsonHelper.Deserialize<string[]>(options); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), CurrentCommandCallbackId); } return optStings; } /// <summary> /// Gets amount of free space available for Isolated Storage /// </summary> /// <param name="options">No options is needed for this method</param> public void getFreeDiskSpace(string options) { string callbackId = getOptionStrings(options)[0]; try { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isoFile.AvailableFreeSpace), callbackId); } } catch (IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } /// <summary> /// Check if file exists /// </summary> /// <param name="options">File path</param> public void testFileExists(string options) { IsDirectoryOrFileExist(options, false); } /// <summary> /// Check if directory exists /// </summary> /// <param name="options">directory name</param> public void testDirectoryExists(string options) { IsDirectoryOrFileExist(options, true); } /// <summary> /// Check if file or directory exist /// </summary> /// <param name="options">File path/Directory name</param> /// <param name="isDirectory">Flag to recognize what we should check</param> public void IsDirectoryOrFileExist(string options, bool isDirectory) { string[] args = getOptionStrings(options); string callbackId = args[1]; FileOptions fileOptions = JSON.JsonHelper.Deserialize<FileOptions>(args[0]); string filePath = args[0]; if (fileOptions == null) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); } try { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool isExist; if (isDirectory) { isExist = isoFile.DirectoryExists(fileOptions.DirectoryName); } else { isExist = isoFile.FileExists(fileOptions.FilePath); } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isExist), callbackId); } } catch (IsolatedStorageException) // default handler throws INVALID_MODIFICATION_ERR { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } public void readAsDataURL(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int startPos = int.Parse(optStrings[1]); int endPos = int.Parse(optStrings[2]); string callbackId = optStrings[3]; if (filePath != null) { try { string base64URL = null; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string mimeType = MimeTypeMapper.GetMimeType(filePath); using (IsolatedStorageFileStream stream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read)) { string base64String = GetFileContent(stream); base64URL = "data:" + mimeType + ";base64," + base64String; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, base64URL), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } } public void readAsArrayBuffer(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int startPos = int.Parse(optStrings[1]); int endPos = int.Parse(optStrings[2]); string callbackId = optStrings[3]; DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId); } public void readAsBinaryString(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int startPos = int.Parse(optStrings[1]); int endPos = int.Parse(optStrings[2]); string callbackId = optStrings[3]; DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId); } public void readAsText(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; string encStr = optStrings[1]; int startPos = int.Parse(optStrings[2]); int endPos = int.Parse(optStrings[3]); string callbackId = optStrings[4]; try { string text = ""; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { readResourceAsText(options); return; } Encoding encoding = Encoding.GetEncoding(encStr); using (IsolatedStorageFileStream reader = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read)) { if (startPos < 0) { startPos = Math.Max((int)reader.Length + startPos, 0); } else if (startPos > 0) { startPos = Math.Min((int)reader.Length, startPos); } if (endPos > 0) { endPos = Math.Min((int)reader.Length, endPos); } else if (endPos < 0) { endPos = Math.Max(endPos + (int)reader.Length, 0); } var buffer = new byte[endPos - startPos]; reader.Seek(startPos, SeekOrigin.Begin); reader.Read(buffer, 0, buffer.Length); text = encoding.GetString(buffer, 0, buffer.Length); } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } /// <summary> /// Reads application resource as a text /// </summary> /// <param name="options">Path to a resource</param> public void readResourceAsText(string options) { string[] optStrings = getOptionStrings(options); string pathToResource = optStrings[0]; string encStr = optStrings[1]; int start = int.Parse(optStrings[2]); int endMarker = int.Parse(optStrings[3]); string callbackId = optStrings[4]; try { if (pathToResource.StartsWith("/")) { pathToResource = pathToResource.Remove(0, 1); } var resource = Application.GetResourceStream(new Uri(pathToResource, UriKind.Relative)); if (resource == null) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string text; StreamReader streamReader = new StreamReader(resource.Stream); text = streamReader.ReadToEnd(); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } public void truncate(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int size = int.Parse(optStrings[1]); string callbackId = optStrings[2]; try { long streamLength = 0; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= size && size <= stream.Length) { stream.SetLength(size); } streamLength = stream.Length; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } public void SaveImageToIsolatedStorage(string options) { string[] optionsString = JSON.JsonHelper.Deserialize<string[]>(options); if (optionsString.Length > 0) { string imgHttpUrl = optionsString[0]; string fileName = Path.GetFileName(imgHttpUrl); using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { if (!iso.FileExists(fileName)) { WebClient webClientImg = new WebClient(); webClientImg.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted); webClientImg.OpenReadAsync(new Uri(imgHttpUrl), fileName); } } } } void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { try { String imgUrl = (string)e.UserState; string isoStorageLocation = imgUrl; using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { IsolatedStorageFileStream isostream = iso.CreateFile(isoStorageLocation); Deployment.Current.Dispatcher.BeginInvoke(() => { BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(e.Result); WriteableBitmap wb = new WriteableBitmap(bitmap); // Encode WriteableBitmap object to a JPEG stream. Extensions.SaveJpeg(wb, isostream, wb.PixelWidth, wb.PixelHeight, 0, 85); isostream.Close(); }); } } catch (Exception ex) { } } //write:[filePath,data,position,isBinary,callbackId] public void write(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; string data = optStrings[1]; int position = int.Parse(optStrings[2]); bool isBinary = bool.Parse(optStrings[3]); string callbackId = optStrings[4]; try { if (string.IsNullOrEmpty(data)) { Debug.WriteLine("Expected some data to be send in the write command to {0}", filePath); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); return; } char[] dataToWrite = isBinary ? JSON.JsonHelper.Deserialize<char[]>(data) : data.ToCharArray(); using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create the file if not exists if (!isoFile.FileExists(filePath)) { var file = isoFile.CreateFile(filePath); file.Close(); } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= position && position <= stream.Length) { stream.SetLength(position); } using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Seek(0, SeekOrigin.End); writer.Write(dataToWrite); } } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, dataToWrite.Length), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } /// <summary> /// Look up metadata about this entry. /// </summary> /// <param name="options">filePath to entry</param> public void getMetadata(string options) { string[] optStings = getOptionStrings(options); string filePath = optStings[0]; string callbackId = optStings[1]; if (filePath != null) { try { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.FileExists(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString() }), callbackId); } else if (isoFile.DirectoryExists(filePath)) { string modTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString(); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = modTime }), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } } /// <summary> /// Returns a File that represents the current state of the file that this FileEntry represents. /// </summary> /// <param name="filePath">filePath to entry</param> /// <returns></returns> public void getFileMetadata(string options) { string[] optStings = getOptionStrings(options); string filePath = optStings[0]; string callbackId = optStings[1]; if (filePath != null) { try { FileMetadata metaData = new FileMetadata(filePath); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, metaData), callbackId); } catch (IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } } /// <summary> /// Look up the parent DirectoryEntry containing this Entry. /// If this Entry is the root of IsolatedStorage, its parent is itself. /// </summary> /// <param name="options"></param> public void getParent(string options) { string[] optStings = getOptionStrings(options); string filePath = optStings[0]; string callbackId = optStings[1]; if (filePath != null) { try { if (string.IsNullOrEmpty(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { FileEntry entry; if (isoFile.FileExists(filePath) || isoFile.DirectoryExists(filePath)) { string path = this.GetParentDirectory(filePath); entry = FileEntry.GetEntry(path); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } } public void remove(string options) { string[] args = getOptionStrings(options); string filePath = args[0]; string callbackId = args[1]; if (filePath != null) { try { if (filePath == "/" || filePath == "" || filePath == @"\") { throw new Exception("Cannot delete root file system"); } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.FileExists(filePath)) { isoFile.DeleteFile(filePath); } else { if (isoFile.DirectoryExists(filePath)) { isoFile.DeleteDirectory(filePath); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } } public void removeRecursively(string options) { string[] args = getOptionStrings(options); string filePath = args[0]; string callbackId = args[1]; if (filePath != null) { if (string.IsNullOrEmpty(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); } else { if (removeDirRecursively(filePath, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } } } } public void readEntries(string options) { string[] args = getOptionStrings(options); string filePath = args[0]; string callbackId = args[1]; if (filePath != null) { try { if (string.IsNullOrEmpty(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.DirectoryExists(filePath)) { string path = File.AddSlashToDirectory(filePath); List<FileEntry> entries = new List<FileEntry>(); string[] files = isoFile.GetFileNames(path + "*"); string[] dirs = isoFile.GetDirectoryNames(path + "*"); foreach (string file in files) { entries.Add(FileEntry.GetEntry(path + file)); } foreach (string dir in dirs) { entries.Add(FileEntry.GetEntry(path + dir + "/")); } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entries), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } } public void requestFileSystem(string options) { // TODO: try/catch string[] optVals = getOptionStrings(options); //FileOptions fileOptions = new FileOptions(); int fileSystemType = int.Parse(optVals[0]); double size = double.Parse(optVals[1]); string callbackId = optVals[2]; IsolatedStorageFile.GetUserStoreForApplication(); if (size > (10 * 1024 * 1024)) // 10 MB, compier will clean this up! { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId); return; } try { if (size != 0) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { long availableSize = isoFile.AvailableFreeSpace; if (size > availableSize) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId); return; } } } if (fileSystemType == PERSISTENT) { // TODO: this should be in it's own folder to prevent overwriting of the app assets, which are also in ISO DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("persistent", FileEntry.GetEntry("/"))), callbackId); } else if (fileSystemType == TEMPORARY) { using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoStorage.FileExists(TMP_DIRECTORY_NAME)) { isoStorage.CreateDirectory(TMP_DIRECTORY_NAME); } } string tmpFolder = "/" + TMP_DIRECTORY_NAME + "/"; DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("temporary", FileEntry.GetEntry(tmpFolder))), callbackId); } else if (fileSystemType == RESOURCE) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("resource")), callbackId); } else if (fileSystemType == APPLICATION) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("application")), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } public void resolveLocalFileSystemURI(string options) { string[] optVals = getOptionStrings(options); string uri = optVals[0].Split('?')[0]; string callbackId = optVals[1]; if (uri != null) { // a single '/' is valid, however, '/someDir' is not, but '/tmp//somedir' and '///someDir' are valid if (uri.StartsWith("/") && uri.IndexOf("//") < 0 && uri != "/") { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } try { // fix encoded spaces string path = Uri.UnescapeDataString(uri); FileEntry uriEntry = FileEntry.GetEntry(path); if (uriEntry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, uriEntry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } } public void copyTo(string options) { TransferTo(options, false); } public void moveTo(string options) { TransferTo(options, true); } public void getFile(string options) { GetFileOrDirectory(options, false); } public void getDirectory(string options) { GetFileOrDirectory(options, true); } #region internal functionality /// <summary> /// Retrieves the parent directory name of the specified path, /// </summary> /// <param name="path">Path</param> /// <returns>Parent directory name</returns> private string GetParentDirectory(string path) { if (String.IsNullOrEmpty(path) || path == "/") { return "/"; } if (path.EndsWith(@"/") || path.EndsWith(@"\")) { return this.GetParentDirectory(Path.GetDirectoryName(path)); } string result = Path.GetDirectoryName(path); if (result == null) { result = "/"; } return result; } private bool removeDirRecursively(string fullPath, string callbackId) { try { if (fullPath == "/") { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); return false; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.DirectoryExists(fullPath)) { string tempPath = File.AddSlashToDirectory(fullPath); string[] files = isoFile.GetFileNames(tempPath + "*"); if (files.Length > 0) { foreach (string file in files) { isoFile.DeleteFile(tempPath + file); } } string[] dirs = isoFile.GetDirectoryNames(tempPath + "*"); if (dirs.Length > 0) { foreach (string dir in dirs) { if (!removeDirRecursively(tempPath + dir, callbackId)) { return false; } } } isoFile.DeleteDirectory(fullPath); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); return false; } } return true; } private bool CanonicalCompare(string pathA, string pathB) { string a = pathA.Replace("//", "/"); string b = pathB.Replace("//", "/"); return a.Equals(b, StringComparison.OrdinalIgnoreCase); } /* * copyTo:["fullPath","parent", "newName"], * moveTo:["fullPath","parent", "newName"], */ private void TransferTo(string options, bool move) { // TODO: try/catch string[] optStrings = getOptionStrings(options); string fullPath = optStrings[0]; string parent = optStrings[1]; string newFileName = optStrings[2]; string callbackId = optStrings[3]; char[] invalids = Path.GetInvalidPathChars(); if (newFileName.IndexOfAny(invalids) > -1 || newFileName.IndexOf(":") > -1) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } try { if ((parent == null) || (string.IsNullOrEmpty(parent)) || (string.IsNullOrEmpty(fullPath))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string parentPath = File.AddSlashToDirectory(parent); string currentPath = fullPath; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool isFileExist = isoFile.FileExists(currentPath); bool isDirectoryExist = isoFile.DirectoryExists(currentPath); bool isParentExist = isoFile.DirectoryExists(parentPath); if ((!isFileExist && !isDirectoryExist) || !isParentExist) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string newName; string newPath; if (isFileExist) { newName = (string.IsNullOrEmpty(newFileName)) ? Path.GetFileName(currentPath) : newFileName; newPath = Path.Combine(parentPath, newName); // sanity check .. // cannot copy file onto itself if (CanonicalCompare(newPath, currentPath)) //(parent + newFileName)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); return; } else if (isoFile.DirectoryExists(newPath)) { // there is already a folder with the same name, operation is not allowed DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); return; } else if (isoFile.FileExists(newPath)) { // remove destination file if exists, in other case there will be exception isoFile.DeleteFile(newPath); } if (move) { isoFile.MoveFile(currentPath, newPath); } else { isoFile.CopyFile(currentPath, newPath, true); } } else { newName = (string.IsNullOrEmpty(newFileName)) ? currentPath : newFileName; newPath = Path.Combine(parentPath, newName); if (move) { // remove destination directory if exists, in other case there will be exception // target directory should be empty if (!newPath.Equals(currentPath) && isoFile.DirectoryExists(newPath)) { isoFile.DeleteDirectory(newPath); } isoFile.MoveDirectory(currentPath, newPath); } else { CopyDirectory(currentPath, newPath, isoFile); } } FileEntry entry = FileEntry.GetEntry(newPath); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } private bool HandleException(Exception ex, string cbId = "") { bool handled = false; string callbackId = String.IsNullOrEmpty(cbId) ? this.CurrentCommandCallbackId : cbId; if (ex is SecurityException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR), callbackId); handled = true; } else if (ex is FileNotFoundException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); handled = true; } else if (ex is ArgumentException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); handled = true; } else if (ex is IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); handled = true; } else if (ex is DirectoryNotFoundException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); handled = true; } return handled; } private void CopyDirectory(string sourceDir, string destDir, IsolatedStorageFile isoFile) { string path = File.AddSlashToDirectory(sourceDir); bool bExists = isoFile.DirectoryExists(destDir); if (!bExists) { isoFile.CreateDirectory(destDir); } destDir = File.AddSlashToDirectory(destDir); string[] files = isoFile.GetFileNames(path + "*"); if (files.Length > 0) { foreach (string file in files) { isoFile.CopyFile(path + file, destDir + file, true); } } string[] dirs = isoFile.GetDirectoryNames(path + "*"); if (dirs.Length > 0) { foreach (string dir in dirs) { CopyDirectory(path + dir, destDir + dir, isoFile); } } } private void GetFileOrDirectory(string options, bool getDirectory) { FileOptions fOptions = new FileOptions(); string[] args = getOptionStrings(options); fOptions.FullPath = args[0]; fOptions.Path = args[1]; string callbackId = args[3]; try { fOptions.CreatingOpt = JSON.JsonHelper.Deserialize<CreatingOptions>(args[2]); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); return; } try { if ((string.IsNullOrEmpty(fOptions.Path)) || (string.IsNullOrEmpty(fOptions.FullPath))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string path; if (fOptions.Path.Split(':').Length > 2) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } try { path = Path.Combine(fOptions.FullPath + "/", fOptions.Path); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool isFile = isoFile.FileExists(path); bool isDirectory = isoFile.DirectoryExists(path); bool create = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Create; bool exclusive = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Exclusive; if (create) { if (exclusive && (isoFile.FileExists(path) || isoFile.DirectoryExists(path))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, PATH_EXISTS_ERR), callbackId); return; } // need to make sure the parent exists // it is an error to create a directory whose immediate parent does not yet exist // see issue: https://issues.apache.org/jira/browse/CB-339 string[] pathParts = path.Split('/'); string builtPath = pathParts[0]; for (int n = 1; n < pathParts.Length - 1; n++) { builtPath += "/" + pathParts[n]; if (!isoFile.DirectoryExists(builtPath)) { Debug.WriteLine(String.Format("Error :: Parent folder \"{0}\" does not exist, when attempting to create \"{1}\"", builtPath, path)); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } } if ((getDirectory) && (!isDirectory)) { isoFile.CreateDirectory(path); } else { if ((!getDirectory) && (!isFile)) { IsolatedStorageFileStream fileStream = isoFile.CreateFile(path); fileStream.Close(); } } } else // (not create) { if ((!isFile) && (!isDirectory)) { if (path.IndexOf("//www") == 0) { Uri fileUri = new Uri(path.Remove(0, 2), UriKind.Relative); StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri); if (streamInfo != null) { FileEntry _entry = FileEntry.GetEntry(fileUri.OriginalString, true); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, _entry), callbackId); //using (BinaryReader br = new BinaryReader(streamInfo.Stream)) //{ // byte[] data = br.ReadBytes((int)streamInfo.Stream.Length); //} } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } return; } if (((getDirectory) && (!isDirectory)) || ((!getDirectory) && (!isFile))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, TYPE_MISMATCH_ERR), callbackId); return; } } FileEntry entry = FileEntry.GetEntry(path); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } private static string AddSlashToDirectory(string dirPath) { if (dirPath.EndsWith("/")) { return dirPath; } else { return dirPath + "/"; } } /// <summary> /// Returns file content in a form of base64 string /// </summary> /// <param name="stream">File stream</param> /// <returns>Base64 representation of the file</returns> private string GetFileContent(Stream stream) { int streamLength = (int)stream.Length; byte[] fileData = new byte[streamLength + 1]; stream.Read(fileData, 0, streamLength); stream.Close(); return Convert.ToBase64String(fileData); } #endregion } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ namespace Leap { using System; using System.Collections.Generic; using Leap.Unity; using UnityEngine; public class TestHandFactory { public static Frame MakeTestFrame(int frameId, bool leftHandIncluded, bool rightHandIncluded) { Frame testFrame = new Frame(frameId, 0, 120.0f, new InteractionBox(), new List<Hand>()); if (leftHandIncluded) testFrame.Hands.Add(MakeTestHand(frameId, 10, true)); if (rightHandIncluded) testFrame.Hands.Add(MakeTestHand(frameId, 20, false)); return testFrame; } public static Hand MakeTestHand(bool isLeft, int frameId = 0, int handId = 0) { return MakeTestHand(frameId, handId, isLeft); } /// <summary> /// Returns a test Leap Hand object transformed by the leftHandTransform argument. If the Leap hand is /// a right hand, the position and rotation of the Hand will be mirrored along the X axis (so you can provide /// LeapTransform to construct both left and right hands. /// </summary> public static Hand MakeTestHand(bool isLeft, LeapTransform leftHandTransform, int frameId = 0, int handId = 0) { if (!isLeft) { leftHandTransform.translation = new Vector(-leftHandTransform.translation.x, leftHandTransform.translation.y, leftHandTransform.translation.z); leftHandTransform.rotation = new LeapQuaternion(-leftHandTransform.rotation.x, leftHandTransform.rotation.y, leftHandTransform.rotation.z, -leftHandTransform.rotation.w); leftHandTransform.MirrorX(); } return MakeTestHand(frameId, handId, isLeft).Transform(leftHandTransform); } /// <summary> /// Returns a test Leap Hand object in the argument pose position and rotation from the hand controller. /// </summary> public static Hand MakeTestHand(bool isLeft, TestHandPose pose, int frameId = 0, int handId = 0) { return MakeTestHand(isLeft, GetTestPoseLeftHandTransform(pose), frameId, handId); } public enum TestHandPose { PoseA, PoseB } public static LeapTransform GetTestPoseLeftHandTransform(TestHandPose pose) { LeapTransform transform = LeapTransform.Identity; switch (pose) { case TestHandPose.PoseA: transform.rotation = AngleAxis(180 * Constants.DEG_TO_RAD, Vector.Forward); transform.translation = new Vector(80f, 120f, 0f); break; case TestHandPose.PoseB: transform.rotation = Quaternion.Euler(30F, -10F, -20F).ToLeapQuaternion(); transform.translation = new Vector(220f, 270f, 130f); break; } return transform; } public static Hand MakeTestHand(int frameId, int handId, bool isLeft) { List<Finger> fingers = new List<Finger>(5); fingers.Add(MakeThumb(frameId, handId, isLeft)); fingers.Add(MakeIndexFinger(frameId, handId, isLeft)); fingers.Add(MakeMiddleFinger(frameId, handId, isLeft)); fingers.Add(MakeRingFinger(frameId, handId, isLeft)); fingers.Add(MakePinky(frameId, handId, isLeft)); Vector armWrist = new Vector(-7.05809944059f, 4.0f, 50.0f); Vector elbow = armWrist + 250f * Vector.Backward; // Adrian: The previous "armBasis" used "elbow" as a translation component. Arm arm = new Arm(elbow, armWrist,(elbow + armWrist)/2, Vector.Forward, 250f, 41f, LeapQuaternion.Identity); Hand testHand = new Hand(frameId, handId, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 85f, isLeft, 0.0f, arm, fingers, new Vector (0,0,0), new Vector(0,0,0), new Vector(0,0,0), Vector.Down, LeapQuaternion.Identity, Vector.Forward, new Vector(-4.36385750984f, 6.5f, 31.0111342526f)); return testHand; } static LeapQuaternion AngleAxis(float angle, Vector axis) { if (!axis.MagnitudeSquared.NearlyEquals(1.0f)) { throw new ArgumentException("Axis must be a unit vector."); } float sineHalfAngle = Mathf.Sin(angle/2.0f); LeapQuaternion q = new LeapQuaternion(sineHalfAngle * axis.x, sineHalfAngle * axis.y, sineHalfAngle * axis.z, Mathf.Cos(angle/2.0f)); return q.Normalized; } static LeapQuaternion RotationBetween(Vector fromDirection, Vector toDirection) { float m = Mathf.Sqrt(2.0f + 2.0f * fromDirection.Dot(toDirection)); Vector w = (1.0f / m) * fromDirection.Cross(toDirection); return new LeapQuaternion(w.x, w.y, w.z, 0.5f * m); } static Finger MakeThumb(int frameId, int handId, bool isLeft) { //Thumb Vector position = new Vector(19.3382610281f, -6.0f, 53.168484654f); Vector forward = new Vector(0.636329113772f, -0.5f, -0.899787143982f); Vector up = new Vector(0.804793943718f, 0.447213915513f, 0.390264553767f); float[] jointLengths = {0.0f, 46.22f, 31.57f, 21.67f}; return MakeFinger(Finger.FingerType.TYPE_THUMB, position, forward, up, jointLengths, frameId, handId, handId + 0, isLeft); } static Finger MakeIndexFinger(int frameId, int handId, bool isLeft) { //Index Finger Vector position = new Vector(23.1812851873f, 2.0f, -23.1493459317f); Vector forward = new Vector(0.166044313785f, -0.14834045293f, -0.974897120667f); Vector up = new Vector(0.0249066470677f, 0.988936352868f, -0.1462345681f); float[] jointLengths = {68.12f, 39.78f, 22.38f, 15.82f}; return MakeFinger(Finger.FingerType.TYPE_INDEX, position, forward, up, jointLengths, frameId, handId, handId + 1, isLeft); } static Finger MakeMiddleFinger(int frameId, int handId, bool isLeft) { //Middle Finger Vector position = new Vector(2.78877821918f, 4.0f, -23.252105626f); Vector forward = new Vector(0.0295207858556f, -0.148340452932f, -0.988495641481f); Vector up = new Vector(-0.145765270107f, 0.977715980076f, -0.151075968756f); float[] jointLengths = {64.60f, 44.63f, 26.33f, 17.40f}; return MakeFinger(Finger.FingerType.TYPE_MIDDLE, position, forward, up, jointLengths, frameId, handId, handId + 2, isLeft); } static Finger MakeRingFinger(int frameId, int handId, bool isLeft) { //Ring Finger Vector position = new Vector(-17.447168266f, 4.0f, -17.2791440615f); Vector forward = new Vector(-0.121317937368f, -0.148340347175f, -0.981466810174f); Vector up = new Vector(-0.216910468316f, 0.968834928679f, -0.119619102602f); float[] jointLengths = {58.00f, 41.37f, 25.65f, 17.30f}; return MakeFinger(Finger.FingerType.TYPE_RING, position, forward, up, jointLengths, frameId, handId, handId + 3, isLeft); } static Finger MakePinky(int frameId, int handId, bool isLeft) { //Pinky Finger Vector position = new Vector(-35.3374394559f, 0.0f, -9.72871382551f); Vector forward = new Vector(-0.259328923438f, -0.105851224797f, -0.959970847306f); Vector up = new Vector(-0.353350220937f, 0.935459475557f, -0.00769356576168f); float[] jointLengths = {53.69f, 32.74f, 18.11f, 15.96f}; return MakeFinger(Finger.FingerType.TYPE_PINKY, position, forward, up, jointLengths, frameId, handId, handId + 4, isLeft); } static Finger MakeFinger(Finger.FingerType name, Vector position, Vector forward, Vector up, float[] jointLengths, int frameId, int handId, int fingerId, bool isLeft) { forward = forward.Normalized; up = up.Normalized; Bone[] bones = new Bone[5]; float proximalDistance = -jointLengths[0]; Bone metacarpal = MakeBone (Bone.BoneType.TYPE_METACARPAL, position + forward * proximalDistance, jointLengths[0], 8f, forward, up, isLeft); proximalDistance += jointLengths[0]; bones[0] = metacarpal; Bone proximal = MakeBone (Bone.BoneType.TYPE_PROXIMAL, position + forward * proximalDistance, jointLengths[1], 8f, forward, up, isLeft); proximalDistance += jointLengths[1]; bones[1] = proximal; Bone intermediate = MakeBone (Bone.BoneType.TYPE_INTERMEDIATE, position + forward * proximalDistance, jointLengths[2], 8f, forward, up, isLeft); proximalDistance += jointLengths[2]; bones[2] = intermediate; Bone distal = MakeBone (Bone.BoneType.TYPE_DISTAL, position + forward * proximalDistance, jointLengths[3], 8f, forward, up, isLeft); bones[3] = distal; return new Finger(frameId, handId, fingerId, 0.0f, position, new Vector(0, 0, 0), forward, position, 8f, jointLengths[1] + jointLengths[2] + jointLengths[3], true, name, bones[0], bones[1], bones[2], bones[3]); } static Bone MakeBone(Bone.BoneType name, Vector proximalPosition, float length, float width, Vector direction, Vector up, bool isLeft) { LeapQuaternion rotation = UnityEngine.Quaternion.LookRotation(-direction.ToVector3(), up.ToVector3()).ToLeapQuaternion(); return new Bone( proximalPosition, proximalPosition + direction * length, Vector.Lerp(proximalPosition, proximalPosition + direction * length, .5f), direction, length, width, name, rotation); } } }
namespace Zutatensuppe.DiabloInterface.Gui { using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Windows.Forms; using Zutatensuppe.DiabloInterface.Lib.Extensions; using Zutatensuppe.DiabloInterface.Lib.Plugin; using Zutatensuppe.DiabloInterface.Lib.Services; using Zutatensuppe.DiabloInterface.Gui.Forms; using Zutatensuppe.DiabloInterface.Lib; public class ConfigWindow : WsExCompositedForm { static readonly ILogger Logger = Logging.CreateLogger(MethodBase.GetCurrentMethod().DeclaringType); static readonly string ConfigFilePath = Application.StartupPath + @"\Settings"; private readonly IDiabloInterface di; bool dirty; private Label FontLabel; private GroupBox FontGroup; private Label TitleFontSizeLabel; private Label FontSizeLabel; private TableLayoutPanel VerticalSplitContainer; private TableLayoutPanel HorizontalSplitContainer; private GroupBox groupBox1; private CheckBox chkDisplayName; private CheckBox chkDisplayDeathCounter; private CheckBox chkDisplayAdvancedStats; private CheckBox chkDisplayGold; private CheckBox chkDisplayResistances; private CheckBox chkDisplayBaseStats; private CheckBox chkDisplayLevel; private NumericUpDown fontSizeNumeric; private NumericUpDown titleFontSizeNumeric; private Gui.Controls.FontComboBox fontComboBox; private TableLayoutPanel mainPanel; private Panel panel1; private Button btnUndo; private Button btnSave; private CheckBox chkDisplayDifficultyPercents; private Button btnSaveAs; private GroupBox grpConfigFiles; private ListBox lstConfigFiles; private ContextMenuStrip ctxConfigFileList; private ToolStripMenuItem menuLoad; private ToolStripMenuItem menuClone; private ToolStripMenuItem menuDelete; private ToolStripMenuItem menuNew; private TabControl tabControl1; private TabPage tabPageSettingsLayout; private TabPage tabPageSettingsRunes; private Button btnSetLevelColor; private Button btnSetFireResColor; private Button btnSetDeathsColor; private Button btnSetAdvancedStatsColor; private Button btnSetBaseStatsColor; private Button btnSetGoldColor; private Button btnSetNameColor; private ComboBox comboBoxLayout; private Label label2; private Label label1; private Button btnSetDifficultyColor; private Button btnSetPoisonResColor; private Button btnSetLightningResColor; private Button btnSetColdResColor; private Button button1; private Button btnSetBackgroundColor; private NumericUpDown numericUpDownPaddingInVerticalLayout; private ToolStripMenuItem renameToolStripMenuItem; private GroupBox groupBox2; private Label label3; private ComboBox comboBoxRunesOrientation; private CheckBox chkHighContrastRunes; private CheckBox chkDisplayRunes; private CheckBox chkShowRealValues; private Controls.RuneSettingsPage runeSettingsPage; private Button btnSetPlayersXColor; private Button btnSetGameCounterColor; private CheckBox chkShowPlayersX; private Button btnSetSeedColor; private CheckBox chkShowSeed; private Button btnSetLifeColor; private CheckBox chkShowLife; private Button btnSetManaColor; private CheckBox chkShowMana; private CheckBox chkShowGameCounter; private CheckBox checkBoxAttackerSelfDamage; private CheckBox checkBoxMonsterGold; private CheckBox checkBoxMagicFind; private Button btnSetAttackerSelfDamageColor; private Button btnSetExtraGoldColor; private Button btnSetMFColor; private CheckBox chkDisplayExpansionClassic; private Button btnColorExpansionClassic; private CheckBox chkDisplayHardcoreSoftcore; private Button btnColorHardcoreSoftcore; private Button btnColorAll; private Button btnColorCharCount; private CheckBox chkDisplayCharCount; public ConfigWindow(IDiabloInterface di) { Logger.Info("Creating config window."); this.di = di; RegisterServiceEventHandlers(); InitializeComponent(); PopulateConfigFileList(this.di.configService.ConfigFileCollection); // Unregister event handlers when we are done. Disposed += (sender, args) => { Logger.Info("Disposing config window."); UnregisterServiceEventHandlers(); }; ReloadWithConfig(this.di.configService.CurrentConfig); } private void InitializeComponent() { FontLabel = new Label(); FontGroup = new GroupBox(); fontComboBox = new Controls.FontComboBox(); FontSizeLabel = new Label(); TitleFontSizeLabel = new Label(); VerticalSplitContainer = new TableLayoutPanel(); grpConfigFiles = new GroupBox(); lstConfigFiles = new ListBox(); ctxConfigFileList = new ContextMenuStrip(); menuNew = new ToolStripMenuItem(); menuLoad = new ToolStripMenuItem(); renameToolStripMenuItem = new ToolStripMenuItem(); menuClone = new ToolStripMenuItem(); menuDelete = new ToolStripMenuItem(); HorizontalSplitContainer = new TableLayoutPanel(); tabControl1 = new TabControl(); tabPageSettingsLayout = new TabPage(); groupBox2 = new GroupBox(); numericUpDownPaddingInVerticalLayout = new NumericUpDown(); label3 = new Label(); comboBoxRunesOrientation = new ComboBox(); label2 = new Label(); label1 = new Label(); comboBoxLayout = new ComboBox(); groupBox1 = new GroupBox(); btnColorCharCount = new Button(); chkDisplayCharCount = new CheckBox(); btnColorAll = new Button(); chkDisplayExpansionClassic = new CheckBox(); btnColorExpansionClassic = new Button(); chkDisplayHardcoreSoftcore = new CheckBox(); btnColorHardcoreSoftcore = new Button(); checkBoxAttackerSelfDamage = new CheckBox(); checkBoxMonsterGold = new CheckBox(); checkBoxMagicFind = new CheckBox(); btnSetAttackerSelfDamageColor = new Button(); btnSetExtraGoldColor = new Button(); btnSetMFColor = new Button(); btnSetPlayersXColor = new Button(); chkShowPlayersX = new CheckBox(); btnSetSeedColor = new Button(); chkShowSeed = new CheckBox(); btnSetLifeColor = new Button(); chkShowLife = new CheckBox(); btnSetManaColor = new Button(); chkShowMana = new CheckBox(); btnSetGameCounterColor = new Button(); chkShowGameCounter = new CheckBox(); chkShowRealValues = new CheckBox(); chkHighContrastRunes = new CheckBox(); chkDisplayRunes = new CheckBox(); btnSetBackgroundColor = new Button(); button1 = new Button(); btnSetLevelColor = new Button(); btnSetDifficultyColor = new Button(); btnSetPoisonResColor = new Button(); btnSetLightningResColor = new Button(); btnSetColdResColor = new Button(); btnSetFireResColor = new Button(); btnSetDeathsColor = new Button(); btnSetAdvancedStatsColor = new Button(); btnSetBaseStatsColor = new Button(); btnSetGoldColor = new Button(); btnSetNameColor = new Button(); chkDisplayDifficultyPercents = new CheckBox(); chkDisplayAdvancedStats = new CheckBox(); chkDisplayLevel = new CheckBox(); chkDisplayGold = new CheckBox(); chkDisplayResistances = new CheckBox(); chkDisplayBaseStats = new CheckBox(); chkDisplayDeathCounter = new CheckBox(); chkDisplayName = new CheckBox(); tabPageSettingsRunes = new TabPage(); runeSettingsPage = new Controls.RuneSettingsPage(); mainPanel = new TableLayoutPanel(); panel1 = new Panel(); btnSaveAs = new Button(); btnUndo = new Button(); btnSave = new Button(); FontGroup.SuspendLayout(); VerticalSplitContainer.SuspendLayout(); grpConfigFiles.SuspendLayout(); ctxConfigFileList.SuspendLayout(); HorizontalSplitContainer.SuspendLayout(); tabControl1.SuspendLayout(); tabPageSettingsLayout.SuspendLayout(); groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)numericUpDownPaddingInVerticalLayout).BeginInit(); groupBox1.SuspendLayout(); tabPageSettingsRunes.SuspendLayout(); mainPanel.SuspendLayout(); panel1.SuspendLayout(); SuspendLayout(); fontComboBox.DrawMode = DrawMode.OwnerDrawVariable; fontComboBox.DropDownWidth = 250; fontComboBox.FormattingEnabled = true; fontComboBox.Location = new Point(105, 21); fontComboBox.Size = new Size(117, 21); fontComboBox.Sorted = true; titleFontSizeNumeric = new NumericUpDown(); ((System.ComponentModel.ISupportInitialize)titleFontSizeNumeric).BeginInit(); titleFontSizeNumeric.Location = new Point(105, 74); titleFontSizeNumeric.Minimum = new decimal(new int[] { 4, 0, 0, 0 }); titleFontSizeNumeric.Size = new Size(118, 20); titleFontSizeNumeric.Value = new decimal(new int[] { 20, 0, 0, 0 }); fontSizeNumeric = new NumericUpDown(); fontSizeNumeric.Anchor = AnchorStyles.Top | AnchorStyles.Right; fontSizeNumeric.Location = new Point(105, 48); fontSizeNumeric.Minimum = new decimal(new int[] { 4, 0, 0, 0 }); fontSizeNumeric.Size = new Size(118, 20); fontSizeNumeric.Value = new decimal(new int[] { 10, 0, 0, 0 }); FontSizeLabel.AutoSize = true; FontSizeLabel.Location = new Point(6, 51); FontSizeLabel.Size = new Size(52, 13); FontSizeLabel.Text = "Font size:"; TitleFontSizeLabel.AutoSize = true; TitleFontSizeLabel.Location = new Point(6, 77); TitleFontSizeLabel.Size = new Size(80, 13); TitleFontSizeLabel.Text = "Name font size:"; FontLabel.AutoSize = true; FontLabel.Location = new Point(6, 24); FontLabel.Size = new Size(31, 13); FontLabel.TabIndex = 2; FontLabel.Text = "Font:"; FontGroup.Controls.Add(fontComboBox); FontGroup.Controls.Add(titleFontSizeNumeric); FontGroup.Controls.Add(fontSizeNumeric); FontGroup.Controls.Add(FontSizeLabel); FontGroup.Controls.Add(TitleFontSizeLabel); FontGroup.Controls.Add(FontLabel); FontGroup.Location = new Point(9, 6); FontGroup.Margin = new Padding(0); FontGroup.Size = new Size(231, 104); FontGroup.Text = "Font"; grpConfigFiles.Controls.Add(lstConfigFiles); grpConfigFiles.Dock = DockStyle.Fill; grpConfigFiles.Location = new Point(3, 3); grpConfigFiles.Size = new Size(169, 502); grpConfigFiles.Text = "Config Files"; tabControl1.Controls.Add(tabPageSettingsLayout); tabControl1.Controls.Add(tabPageSettingsRunes); foreach (var p in di.plugins.CreateControls<IPluginConfigEditRenderer>()) { var c = new TabPage(); c.Controls.Add(p.Value); c.Dock = DockStyle.Fill; c.Text = p.Key; tabControl1.Controls.Add(c); } tabControl1.Dock = DockStyle.Fill; tabControl1.Location = new Point(3, 3); tabControl1.SelectedIndex = 0; tabControl1.Size = new Size(513, 502); foreach (TabPage c in tabControl1.Controls) c.UseVisualStyleBackColor = true; HorizontalSplitContainer.ColumnCount = 1; HorizontalSplitContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F)); HorizontalSplitContainer.Controls.Add(tabControl1, 0, 0); HorizontalSplitContainer.Dock = DockStyle.Fill; HorizontalSplitContainer.Location = new Point(175, 0); HorizontalSplitContainer.Margin = new Padding(0); HorizontalSplitContainer.RowCount = 2; HorizontalSplitContainer.RowStyles.Add(new RowStyle(SizeType.Percent, 100F)); HorizontalSplitContainer.RowStyles.Add(new RowStyle()); HorizontalSplitContainer.RowStyles.Add(new RowStyle(SizeType.Absolute, 20F)); HorizontalSplitContainer.Size = new Size(519, 508); VerticalSplitContainer.ColumnCount = 2; VerticalSplitContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 175F)); VerticalSplitContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F)); VerticalSplitContainer.Controls.Add(grpConfigFiles, 0, 0); VerticalSplitContainer.Controls.Add(HorizontalSplitContainer, 1, 0); VerticalSplitContainer.Dock = DockStyle.Fill; VerticalSplitContainer.Location = new Point(0, 0); VerticalSplitContainer.Margin = new Padding(0); VerticalSplitContainer.RowCount = 1; VerticalSplitContainer.RowStyles.Add(new RowStyle(SizeType.Percent, 100F)); VerticalSplitContainer.Size = new Size(694, 508); lstConfigFiles.ContextMenuStrip = ctxConfigFileList; lstConfigFiles.Dock = DockStyle.Fill; lstConfigFiles.FormattingEnabled = true; lstConfigFiles.Location = new Point(3, 16); lstConfigFiles.Size = new Size(163, 483); lstConfigFiles.MouseDoubleClick += new MouseEventHandler(lstConfigFiles_MouseDoubleClick); lstConfigFiles.MouseUp += new MouseEventHandler(lstConfigFiles_MouseUp); ctxConfigFileList.ImageScalingSize = new Size(20, 20); ctxConfigFileList.Items.AddRange(new ToolStripItem[] { menuNew, menuLoad, renameToolStripMenuItem, menuClone, menuDelete}); ctxConfigFileList.Size = new Size(118, 114); menuNew.Size = new Size(117, 22); menuNew.Text = "New"; menuNew.Click += new EventHandler(menuNew_Click); menuLoad.Size = new Size(117, 22); menuLoad.Text = "Load"; menuLoad.Click += new EventHandler(menuLoad_Click); renameToolStripMenuItem.Size = new Size(117, 22); renameToolStripMenuItem.Text = "Rename"; renameToolStripMenuItem.Click += new EventHandler(renameToolStripMenuItem_Click); menuClone.Size = new Size(117, 22); menuClone.Text = "Clone"; menuClone.Click += new EventHandler(menuClone_Click); menuDelete.Size = new Size(117, 22); menuDelete.Text = "Delete"; menuDelete.Click += new EventHandler(menuDelete_Click); tabPageSettingsLayout.Controls.Add(groupBox2); tabPageSettingsLayout.Controls.Add(FontGroup); tabPageSettingsLayout.Controls.Add(groupBox1); tabPageSettingsLayout.Dock = DockStyle.Fill; tabPageSettingsLayout.Text = "Layout"; groupBox2.Controls.Add(numericUpDownPaddingInVerticalLayout); groupBox2.Controls.Add(label3); groupBox2.Controls.Add(comboBoxRunesOrientation); groupBox2.Controls.Add(label2); groupBox2.Controls.Add(label1); groupBox2.Controls.Add(comboBoxLayout); groupBox2.Location = new Point(249, 6); groupBox2.Size = new Size(241, 104); groupBox2.Text = "Layout"; numericUpDownPaddingInVerticalLayout.Location = new Point(145, 75); numericUpDownPaddingInVerticalLayout.Size = new Size(81, 20); numericUpDownPaddingInVerticalLayout.TabIndex = 23; label3.AutoSize = true; label3.Location = new Point(6, 51); label3.Size = new Size(93, 13); label3.Text = "Runes orientation:"; comboBoxRunesOrientation.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxRunesOrientation.FormattingEnabled = true; comboBoxRunesOrientation.Items.AddRange(new object[] { "Horizontal", "Vertical" }); comboBoxRunesOrientation.Location = new Point(145, 48); comboBoxRunesOrientation.Size = new Size(80, 21); label2.AutoSize = true; label2.Location = new Point(6, 24); label2.Size = new Size(61, 13); label2.Text = "Orientation:"; label1.AutoSize = true; label1.Location = new Point(6, 77); label1.Size = new Size(128, 13); label1.Text = "Padding in vertical layout:"; comboBoxLayout.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxLayout.FormattingEnabled = true; comboBoxLayout.Items.AddRange(new object[] { "Horizontal", "Vertical" }); comboBoxLayout.Location = new Point(145, 21); comboBoxLayout.Size = new Size(80, 21); comboBoxLayout.SelectedIndexChanged += new EventHandler(comboBoxLayout_SelectedIndexChanged); btnColorCharCount.Location = new Point(155, 249); btnColorCharCount.Size = new Size(44, 22); btnColorCharCount.Text = "Color"; btnColorCharCount.Click += new EventHandler(btnSelectColor); chkDisplayCharCount.AutoSize = true; chkDisplayCharCount.Location = new Point(14, 253); chkDisplayCharCount.Size = new Size(116, 17); chkDisplayCharCount.Text = "Characters created"; var i = 1; btnSetSeedColor.Location = new Point(155, 249 + i * 23); btnSetSeedColor.Margin = new Padding(0); btnSetSeedColor.Size = new Size(44, 22); btnSetSeedColor.Text = "Color"; btnSetSeedColor.Click += new EventHandler(btnSelectColor); chkShowSeed.AutoSize = true; chkShowSeed.Location = new Point(14, 253 + i * 23); chkShowSeed.Size = new Size(136, 17); chkShowSeed.Text = "Seed (-seed)"; i++; btnSetLifeColor.Location = new Point(155, 249 + i * 23); btnSetLifeColor.Margin = new Padding(0); btnSetLifeColor.Size = new Size(44, 22); btnSetLifeColor.Text = "Color"; btnSetLifeColor.Click += new EventHandler(btnSelectColor); chkShowLife.AutoSize = true; chkShowLife.Location = new Point(14, 253 + i * 23); chkShowLife.Size = new Size(136, 17); chkShowLife.Text = "Life"; i++; btnSetManaColor.Location = new Point(155, 249 + i * 23); btnSetManaColor.Margin = new Padding(0); btnSetManaColor.Size = new Size(44, 22); btnSetManaColor.Text = "Color"; btnSetManaColor.Click += new EventHandler(btnSelectColor); chkShowMana.AutoSize = true; chkShowMana.Location = new Point(14, 253 + i * 23); chkShowMana.Size = new Size(136, 17); chkShowMana.Text = "Mana"; btnColorAll.Location = new Point(338, 280); btnColorAll.Size = new Size(136, 22); btnColorAll.Text = "Text Color (All)"; btnColorAll.Click += new EventHandler(btnColorAll_Click); chkDisplayExpansionClassic.AutoSize = true; chkDisplayExpansionClassic.Location = new Point(264, 138); chkDisplayExpansionClassic.Size = new Size(86, 17); chkDisplayExpansionClassic.Text = "Classic/LOD"; btnColorExpansionClassic.Location = new Point(397, 134); btnColorExpansionClassic.Size = new Size(44, 22); btnColorExpansionClassic.Text = "Color"; btnColorExpansionClassic.Click += new EventHandler(btnSelectColor); groupBox1.Controls.Add(btnColorCharCount); groupBox1.Controls.Add(chkDisplayCharCount); groupBox1.Controls.Add(btnColorAll); groupBox1.Controls.Add(chkDisplayExpansionClassic); groupBox1.Controls.Add(btnColorExpansionClassic); groupBox1.Controls.Add(chkDisplayHardcoreSoftcore); groupBox1.Controls.Add(btnColorHardcoreSoftcore); groupBox1.Controls.Add(checkBoxAttackerSelfDamage); groupBox1.Controls.Add(checkBoxMonsterGold); groupBox1.Controls.Add(checkBoxMagicFind); groupBox1.Controls.Add(btnSetAttackerSelfDamageColor); groupBox1.Controls.Add(btnSetExtraGoldColor); groupBox1.Controls.Add(btnSetMFColor); groupBox1.Controls.Add(btnSetPlayersXColor); groupBox1.Controls.Add(chkShowPlayersX); groupBox1.Controls.Add(btnSetSeedColor); groupBox1.Controls.Add(chkShowSeed); groupBox1.Controls.Add(btnSetLifeColor); groupBox1.Controls.Add(chkShowLife); groupBox1.Controls.Add(btnSetManaColor); groupBox1.Controls.Add(chkShowMana); groupBox1.Controls.Add(btnSetGameCounterColor); groupBox1.Controls.Add(chkShowGameCounter); groupBox1.Controls.Add(chkShowRealValues); groupBox1.Controls.Add(chkHighContrastRunes); groupBox1.Controls.Add(chkDisplayRunes); groupBox1.Controls.Add(btnSetBackgroundColor); groupBox1.Controls.Add(button1); groupBox1.Controls.Add(btnSetLevelColor); groupBox1.Controls.Add(btnSetDifficultyColor); groupBox1.Controls.Add(btnSetPoisonResColor); groupBox1.Controls.Add(btnSetLightningResColor); groupBox1.Controls.Add(btnSetColdResColor); groupBox1.Controls.Add(btnSetFireResColor); groupBox1.Controls.Add(btnSetDeathsColor); groupBox1.Controls.Add(btnSetAdvancedStatsColor); groupBox1.Controls.Add(btnSetBaseStatsColor); groupBox1.Controls.Add(btnSetGoldColor); groupBox1.Controls.Add(btnSetNameColor); groupBox1.Controls.Add(chkDisplayDifficultyPercents); groupBox1.Controls.Add(chkDisplayAdvancedStats); groupBox1.Controls.Add(chkDisplayLevel); groupBox1.Controls.Add(chkDisplayGold); groupBox1.Controls.Add(chkDisplayResistances); groupBox1.Controls.Add(chkDisplayBaseStats); groupBox1.Controls.Add(chkDisplayDeathCounter); groupBox1.Controls.Add(chkDisplayName); groupBox1.Location = new Point(9, 110); groupBox1.Margin = new Padding(0); groupBox1.Size = new Size(481, 366); groupBox1.Text = "Display"; chkDisplayHardcoreSoftcore.AutoSize = true; chkDisplayHardcoreSoftcore.Location = new Point(264, 115); chkDisplayHardcoreSoftcore.Size = new Size(60, 17); chkDisplayHardcoreSoftcore.Text = "HC/SC"; btnColorHardcoreSoftcore.Location = new Point(397, 111); btnColorHardcoreSoftcore.Size = new Size(44, 22); btnColorHardcoreSoftcore.Text = "Color"; btnColorHardcoreSoftcore.Click += new EventHandler(btnSelectColor); checkBoxAttackerSelfDamage.AutoSize = true; checkBoxAttackerSelfDamage.Location = new Point(264, 70); checkBoxAttackerSelfDamage.Size = new Size(130, 17); checkBoxAttackerSelfDamage.Text = "Attacker Self Damage"; checkBoxMonsterGold.AutoSize = true; checkBoxMonsterGold.Location = new Point(264, 47); checkBoxMonsterGold.Size = new Size(75, 17); checkBoxMonsterGold.Text = "Extra Gold"; checkBoxMagicFind.AutoSize = true; checkBoxMagicFind.Location = new Point(264, 24); checkBoxMagicFind.Size = new Size(78, 17); checkBoxMagicFind.Text = "Magic Find"; btnSetAttackerSelfDamageColor.Location = new Point(397, 66); btnSetAttackerSelfDamageColor.Margin = new Padding(0); btnSetAttackerSelfDamageColor.Size = new Size(44, 22); btnSetAttackerSelfDamageColor.Text = "Color"; btnSetAttackerSelfDamageColor.Click += new EventHandler(btnSelectColor); btnSetExtraGoldColor.Location = new Point(397, 43); btnSetExtraGoldColor.Margin = new Padding(0); btnSetExtraGoldColor.Size = new Size(44, 22); btnSetExtraGoldColor.Text = "Color"; btnSetExtraGoldColor.Click += new EventHandler(btnSelectColor); btnSetMFColor.Location = new Point(397, 20); btnSetMFColor.Margin = new Padding(0); btnSetMFColor.Size = new Size(44, 22); btnSetMFColor.Text = "Color"; btnSetMFColor.Click += new EventHandler(btnSelectColor); btnSetPlayersXColor.Location = new Point(155, 203); btnSetPlayersXColor.Margin = new Padding(0); btnSetPlayersXColor.Size = new Size(44, 22); btnSetPlayersXColor.Text = "Color"; btnSetPlayersXColor.Click += new EventHandler(btnSelectColor); chkShowPlayersX.AutoSize = true; chkShowPlayersX.Location = new Point(14, 207); chkShowPlayersX.Size = new Size(74, 17); chkShowPlayersX.Text = "/players X"; btnSetGameCounterColor.Location = new Point(155, 226); btnSetGameCounterColor.Margin = new Padding(0); btnSetGameCounterColor.Size = new Size(44, 22); btnSetGameCounterColor.Text = "Color"; btnSetGameCounterColor.Click += new EventHandler(btnSelectColor); chkShowGameCounter.AutoSize = true; chkShowGameCounter.Location = new Point(14, 230); chkShowGameCounter.Size = new Size(106, 17); chkShowGameCounter.Text = "Games launched"; chkShowRealValues.AutoSize = true; chkShowRealValues.Location = new Point(203, 92); chkShowRealValues.Size = new Size(109, 17); chkShowRealValues.Text = "calculated values"; chkHighContrastRunes.AutoSize = true; chkHighContrastRunes.Location = new Point(82, 341); chkHighContrastRunes.Size = new Size(89, 17); chkHighContrastRunes.Text = "High contrast"; chkDisplayRunes.AutoSize = true; chkDisplayRunes.Location = new Point(14, 341); chkDisplayRunes.Size = new Size(57, 17); chkDisplayRunes.Text = "Runes"; btnSetBackgroundColor.Location = new Point(339, 308); btnSetBackgroundColor.Size = new Size(136, 22); btnSetBackgroundColor.Text = "Background color"; btnSetBackgroundColor.Click += new EventHandler(backgroundColorButtonClick); button1.Location = new Point(339, 336); button1.Size = new Size(136, 22); button1.Text = "Reset to default colors"; button1.Click += new EventHandler(resetColorsButton); btnSetLevelColor.Location = new Point(155, 134); btnSetLevelColor.Size = new Size(44, 22); btnSetLevelColor.Text = "Color"; btnSetLevelColor.Click += new EventHandler(btnSelectColor); btnSetDifficultyColor.Location = new Point(155, 180); btnSetDifficultyColor.Size = new Size(44, 22); btnSetDifficultyColor.Text = "Color"; btnSetDifficultyColor.Click += new EventHandler(btnSelectColor); btnSetPoisonResColor.Location = new Point(287, 157); btnSetPoisonResColor.Size = new Size(44, 22); btnSetPoisonResColor.Text = "Pois."; btnSetPoisonResColor.Click += new EventHandler(btnSelectColor); btnSetLightningResColor.Location = new Point(243, 157); btnSetLightningResColor.Size = new Size(44, 22); btnSetLightningResColor.Text = "Light."; btnSetLightningResColor.Click += new EventHandler(btnSelectColor); btnSetColdResColor.Location = new Point(199, 157); btnSetColdResColor.Size = new Size(44, 22); btnSetColdResColor.Text = "Cold"; btnSetColdResColor.Click += new EventHandler(btnSelectColor); btnSetFireResColor.Location = new Point(155, 157); btnSetFireResColor.Size = new Size(44, 22); btnSetFireResColor.Text = "Fire"; btnSetFireResColor.Click += new EventHandler(btnSelectColor); btnSetDeathsColor.Location = new Point(155, 111); btnSetDeathsColor.Size = new Size(44, 22); btnSetDeathsColor.Text = "Color"; btnSetDeathsColor.Click += new EventHandler(btnSelectColor); btnSetAdvancedStatsColor.Location = new Point(155, 88); btnSetAdvancedStatsColor.Size = new Size(44, 22); btnSetAdvancedStatsColor.Text = "Color"; btnSetAdvancedStatsColor.Click += new EventHandler(btnSelectColor); btnSetBaseStatsColor.Location = new Point(155, 66); btnSetBaseStatsColor.Size = new Size(44, 22); btnSetBaseStatsColor.Text = "Color"; btnSetBaseStatsColor.Click += new EventHandler(btnSelectColor); btnSetGoldColor.Location = new Point(155, 43); btnSetGoldColor.Size = new Size(44, 22); btnSetGoldColor.Text = "Color"; btnSetGoldColor.Click += new EventHandler(btnSelectColor); btnSetNameColor.Location = new Point(155, 20); btnSetNameColor.Size = new Size(44, 22); btnSetNameColor.Text = "Color"; btnSetNameColor.Click += new EventHandler(btnSelectColor); chkDisplayDifficultyPercents.AutoSize = true; chkDisplayDifficultyPercents.Location = new Point(14, 184); chkDisplayDifficultyPercents.Size = new Size(77, 17); chkDisplayDifficultyPercents.Text = "Difficulty %"; chkDisplayAdvancedStats.AutoSize = true; chkDisplayAdvancedStats.Location = new Point(14, 92); chkDisplayAdvancedStats.Size = new Size(105, 17); chkDisplayAdvancedStats.Text = "Fcr, Frw, Fhr, Ias"; chkDisplayLevel.AutoSize = true; chkDisplayLevel.Location = new Point(14, 138); chkDisplayLevel.Size = new Size(101, 17); chkDisplayLevel.Text = "Character Level"; chkDisplayGold.AutoSize = true; chkDisplayGold.Location = new Point(14, 47); chkDisplayGold.Size = new Size(48, 17); chkDisplayGold.Text = "Gold"; chkDisplayResistances.AutoSize = true; chkDisplayResistances.Location = new Point(14, 161); chkDisplayResistances.Size = new Size(84, 17); chkDisplayResistances.Text = "Resistances"; chkDisplayBaseStats.AutoSize = true; chkDisplayBaseStats.Location = new Point(14, 70); chkDisplayBaseStats.Size = new Size(107, 17); chkDisplayBaseStats.Text = "Str, Dex, Vit, Ene"; chkDisplayDeathCounter.AutoSize = true; chkDisplayDeathCounter.Location = new Point(14, 115); chkDisplayDeathCounter.Size = new Size(60, 17); chkDisplayDeathCounter.Text = "Deaths"; chkDisplayName.AutoSize = true; chkDisplayName.Location = new Point(14, 24); chkDisplayName.Size = new Size(54, 17); chkDisplayName.Text = "Name"; tabPageSettingsRunes.Controls.Add(runeSettingsPage); tabPageSettingsRunes.Location = new Point(4, 22); tabPageSettingsRunes.Size = new Size(505, 476); tabPageSettingsRunes.Text = "Runes"; runeSettingsPage.Dock = DockStyle.Fill; runeSettingsPage.Location = new Point(0, 0); runeSettingsPage.Margin = new Padding(4); runeSettingsPage.SettingsList = new List<ClassRuneSettings>(); runeSettingsPage.Size = new Size(505, 476); mainPanel.ColumnCount = 1; mainPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F)); mainPanel.Controls.Add(VerticalSplitContainer, 0, 0); mainPanel.Controls.Add(panel1, 0, 1); mainPanel.Dock = DockStyle.Fill; mainPanel.Location = new Point(0, 0); mainPanel.Margin = new Padding(0); mainPanel.RowCount = 2; mainPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100F)); mainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 32F)); mainPanel.Size = new Size(694, 540); panel1.Controls.Add(btnSaveAs); panel1.Controls.Add(btnUndo); panel1.Controls.Add(btnSave); panel1.Dock = DockStyle.Fill; panel1.Location = new Point(0, 508); panel1.Margin = new Padding(0); panel1.Size = new Size(694, 32); btnSaveAs.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; btnSaveAs.Location = new Point(520, 6); btnSaveAs.Size = new Size(75, 23); btnSaveAs.Text = "Save As"; btnSaveAs.Click += new EventHandler(SaveConfigAsMenuItem_Click); btnUndo.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; btnUndo.Location = new Point(600, 6); btnUndo.Size = new Size(90, 23); btnUndo.Text = "Undo Changes"; btnUndo.Click += new EventHandler(btnCancel_Click); btnSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; btnSave.Location = new Point(438, 6); btnSave.Size = new Size(75, 23); btnSave.Text = "Save"; btnSave.Click += new EventHandler(btnSave_Click); AutoScaleDimensions = new SizeF(6F, 13F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(694, 540); Controls.Add(mainPanel); Icon = Properties.Resources.di; MinimumSize = new Size(700, 538); Text = "Config"; FormClosing += new FormClosingEventHandler(ConfigWindowOnFormClosing); FontGroup.ResumeLayout(false); FontGroup.PerformLayout(); ((System.ComponentModel.ISupportInitialize)titleFontSizeNumeric).EndInit(); ((System.ComponentModel.ISupportInitialize)fontSizeNumeric).EndInit(); VerticalSplitContainer.ResumeLayout(false); grpConfigFiles.ResumeLayout(false); ctxConfigFileList.ResumeLayout(false); HorizontalSplitContainer.ResumeLayout(false); tabControl1.ResumeLayout(false); tabPageSettingsLayout.ResumeLayout(false); groupBox2.ResumeLayout(false); groupBox2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)numericUpDownPaddingInVerticalLayout).EndInit(); groupBox1.ResumeLayout(false); groupBox1.PerformLayout(); tabPageSettingsRunes.ResumeLayout(false); mainPanel.ResumeLayout(false); panel1.ResumeLayout(false); ResumeLayout(false); } bool IsDirty { get { var config = di.configService.CurrentConfig; return dirty || di.plugins.EditedConfigsDirty || !CompareClassRuneSettings(config) || config.FontName != GetFontName() || config.FontSize != (int)fontSizeNumeric.Value || config.FontSizeTitle != (int)titleFontSizeNumeric.Value || config.DisplayName != chkDisplayName.Checked || config.DisplayGold != chkDisplayGold.Checked || config.DisplayDeathCounter != chkDisplayDeathCounter.Checked || config.DisplayLevel != chkDisplayLevel.Checked || config.DisplayResistances != chkDisplayResistances.Checked || config.DisplayBaseStats != chkDisplayBaseStats.Checked || config.DisplayAdvancedStats != chkDisplayAdvancedStats.Checked || config.DisplayRunes != chkDisplayRunes.Checked || config.DisplayRunesHorizontal != (comboBoxRunesOrientation.SelectedIndex == 0) || config.DisplayRunesHighContrast != chkHighContrastRunes.Checked || config.DisplayDifficultyPercentages != chkDisplayDifficultyPercents.Checked || config.DisplayLayoutHorizontal != (comboBoxLayout.SelectedIndex == 0) || config.VerticalLayoutPadding != (int)numericUpDownPaddingInVerticalLayout.Value || config.DisplayRealFrwIas != chkShowRealValues.Checked || config.DisplayPlayersX != chkShowPlayersX.Checked || config.DisplaySeed != chkShowSeed.Checked || config.DisplayLife != chkShowLife.Checked || config.DisplayMana != chkShowMana.Checked || config.DisplayGameCounter != chkShowGameCounter.Checked || config.DisplayCharCounter != chkDisplayCharCount.Checked || config.DisplayMagicFind != checkBoxMagicFind.Checked || config.DisplayMonsterGold != checkBoxMonsterGold.Checked || config.DisplayAttackerSelfDamage != checkBoxAttackerSelfDamage.Checked || config.DisplayHardcoreSoftcore != chkDisplayHardcoreSoftcore.Checked || config.DisplayExpansionClassic != chkDisplayExpansionClassic.Checked || config.ColorName != btnSetNameColor.ForeColor || config.ColorDeaths != btnSetDeathsColor.ForeColor || config.ColorLevel != btnSetLevelColor.ForeColor || config.ColorDifficultyPercentages != btnSetDifficultyColor.ForeColor || config.ColorGold != btnSetGoldColor.ForeColor || config.ColorBaseStats != btnSetBaseStatsColor.ForeColor || config.ColorAdvancedStats != btnSetAdvancedStatsColor.ForeColor || config.ColorFireRes != btnSetFireResColor.ForeColor || config.ColorColdRes != btnSetColdResColor.ForeColor || config.ColorLightningRes != btnSetLightningResColor.ForeColor || config.ColorPoisonRes != btnSetPoisonResColor.ForeColor || config.ColorPlayersX != btnSetPlayersXColor.ForeColor || config.ColorSeed != btnSetSeedColor.ForeColor || config.ColorLife != btnSetLifeColor.ForeColor || config.ColorMana != btnSetManaColor.ForeColor || config.ColorGameCounter != btnSetGameCounterColor.ForeColor || config.ColorCharCounter != btnColorCharCount.ForeColor || config.ColorMagicFind != btnSetMFColor.ForeColor || config.ColorMonsterGold != btnSetExtraGoldColor.ForeColor || config.ColorAttackerSelfDamage != btnSetAttackerSelfDamageColor.ForeColor || config.ColorHardcoreSoftcore != btnColorHardcoreSoftcore.ForeColor || config.ColorExpansionClassic != btnColorExpansionClassic.ForeColor || config.ColorBackground != btnSetBackgroundColor.BackColor ; } } bool CompareClassRuneSettings(ApplicationConfig config) { IReadOnlyList<IClassRuneSettings> a = config.ClassRunes; IReadOnlyList<IClassRuneSettings> b = runeSettingsPage.SettingsList; if (a.Count != b.Count) return false; for (var i = 0; i < a.Count; ++i) { var settingsA = a[i]; var settingsB = b[i]; if (settingsA.Class != settingsB.Class) return false; if (settingsA.Difficulty != settingsB.Difficulty) return false; if (settingsA.Runes.Count != settingsB.Runes.Count) return false; if (!settingsA.Runes.SequenceEqual(settingsB.Runes)) return false; } return true; } void RegisterServiceEventHandlers() { di.configService.Changed += ConfigChanged; di.configService.CollectionChanged += ConfigCollectionChanged; } void UnregisterServiceEventHandlers() { di.configService.Changed -= ConfigChanged; di.configService.CollectionChanged -= ConfigCollectionChanged; } void ConfigChanged(object sender, ApplicationConfigEventArgs e) { if (InvokeRequired) { Invoke((Action)(() => ConfigChanged(sender, e))); return; } // NOTE: This may have been due to loading config from elsewhere. For now the //// behavior will be to refresh the config window in that case. ReloadWithConfig(e.Config); } void ReloadWithConfig(ApplicationConfig c) { Text = $@"Config ({Path.GetFileName(di.configService.CurrentConfigFile)})"; var config = c.DeepCopy(); runeSettingsPage.SettingsList = config.ClassRunes; if (config.FontName != null) fontComboBox.SelectedIndex = fontComboBox.Items.IndexOf(config.FontName); fontSizeNumeric.Value = config.FontSize; titleFontSizeNumeric.Value = config.FontSizeTitle; numericUpDownPaddingInVerticalLayout.Value = config.VerticalLayoutPadding; chkDisplayName.Checked = config.DisplayName; chkDisplayGold.Checked = config.DisplayGold; chkDisplayDeathCounter.Checked = config.DisplayDeathCounter; chkDisplayLevel.Checked = config.DisplayLevel; chkDisplayResistances.Checked = config.DisplayResistances; chkDisplayBaseStats.Checked = config.DisplayBaseStats; chkDisplayAdvancedStats.Checked = config.DisplayAdvancedStats; chkDisplayRunes.Checked = config.DisplayRunes; comboBoxRunesOrientation.SelectedIndex = config.DisplayRunesHorizontal ? 0 : 1; chkDisplayDifficultyPercents.Checked = config.DisplayDifficultyPercentages; chkHighContrastRunes.Checked = config.DisplayRunesHighContrast; comboBoxLayout.SelectedIndex = config.DisplayLayoutHorizontal ? 0 : 1; chkShowRealValues.Checked = config.DisplayRealFrwIas; chkShowPlayersX.Checked = config.DisplayPlayersX; chkShowSeed.Checked = config.DisplaySeed; chkShowLife.Checked = config.DisplayLife; chkShowMana.Checked = config.DisplayMana; chkShowGameCounter.Checked = config.DisplayGameCounter; chkDisplayCharCount.Checked = config.DisplayCharCounter; checkBoxMagicFind.Checked = config.DisplayMagicFind; checkBoxMonsterGold.Checked = config.DisplayMonsterGold; checkBoxAttackerSelfDamage.Checked = config.DisplayAttackerSelfDamage; chkDisplayHardcoreSoftcore.Checked = config.DisplayHardcoreSoftcore; chkDisplayExpansionClassic.Checked = config.DisplayExpansionClassic; btnSetNameColor.ForeColor = config.ColorName; btnSetDeathsColor.ForeColor = config.ColorDeaths; btnSetLevelColor.ForeColor = config.ColorLevel; btnSetDifficultyColor.ForeColor = config.ColorDifficultyPercentages; btnSetGoldColor.ForeColor = config.ColorGold; btnSetBaseStatsColor.ForeColor = config.ColorBaseStats; btnSetAdvancedStatsColor.ForeColor = config.ColorAdvancedStats; btnSetFireResColor.ForeColor = config.ColorFireRes; btnSetColdResColor.ForeColor = config.ColorColdRes; btnSetLightningResColor.ForeColor = config.ColorLightningRes; btnSetPoisonResColor.ForeColor = config.ColorPoisonRes; btnSetPlayersXColor.ForeColor = config.ColorPlayersX; btnSetSeedColor.ForeColor = config.ColorSeed; btnSetLifeColor.ForeColor = config.ColorLife; btnSetManaColor.ForeColor = config.ColorMana; btnSetGameCounterColor.ForeColor = config.ColorGameCounter; btnColorCharCount.ForeColor = config.ColorCharCounter; btnSetMFColor.ForeColor = config.ColorMagicFind; btnSetExtraGoldColor.ForeColor = config.ColorMonsterGold; btnSetAttackerSelfDamageColor.ForeColor = config.ColorAttackerSelfDamage; btnColorHardcoreSoftcore.ForeColor = config.ColorHardcoreSoftcore; btnColorExpansionClassic.ForeColor = config.ColorExpansionClassic; SetBackgroundColor(config.ColorBackground); // Loading the settings will dirty mark pretty much everything, here // we just verify that nothing has actually changed yet. dirty = false; } private string GetFontName() { if (fontComboBox.SelectedItem != null) return fontComboBox.SelectedItem.ToString(); foreach (string comboBoxFontName in fontComboBox.Items) if (comboBoxFontName.Equals(fontComboBox.Text)) return fontComboBox.Text; return null; } ApplicationConfig CopyModifiedConfig() { var config = di.configService.CurrentConfig.DeepCopy(); foreach (var p in di.plugins.GetEditedConfigs) config.Plugins[p.Key] = p.Value; config.ClassRunes = runeSettingsPage.SettingsList ?? new List<ClassRuneSettings>(); config.FontSize = (int)fontSizeNumeric.Value; config.FontSizeTitle = (int)titleFontSizeNumeric.Value; config.VerticalLayoutPadding = (int)numericUpDownPaddingInVerticalLayout.Value; config.FontName = GetFontName(); config.DisplayName = chkDisplayName.Checked; config.DisplayGold = chkDisplayGold.Checked; config.DisplayDeathCounter = chkDisplayDeathCounter.Checked; config.DisplayLevel = chkDisplayLevel.Checked; config.DisplayResistances = chkDisplayResistances.Checked; config.DisplayBaseStats = chkDisplayBaseStats.Checked; config.DisplayAdvancedStats = chkDisplayAdvancedStats.Checked; config.DisplayDifficultyPercentages = chkDisplayDifficultyPercents.Checked; config.DisplayRealFrwIas = chkShowRealValues.Checked; config.DisplayPlayersX = chkShowPlayersX.Checked; config.DisplaySeed = chkShowSeed.Checked; config.DisplayLife = chkShowLife.Checked; config.DisplayMana = chkShowMana.Checked; config.DisplayGameCounter = chkShowGameCounter.Checked; config.DisplayCharCounter = chkDisplayCharCount.Checked; config.DisplayMagicFind = checkBoxMagicFind.Checked; config.DisplayMonsterGold = checkBoxMonsterGold.Checked; config.DisplayAttackerSelfDamage = checkBoxAttackerSelfDamage.Checked; config.DisplayHardcoreSoftcore = chkDisplayHardcoreSoftcore.Checked; config.DisplayExpansionClassic = chkDisplayExpansionClassic.Checked; config.DisplayRunes = chkDisplayRunes.Checked; config.DisplayRunesHorizontal = comboBoxRunesOrientation.SelectedIndex == 0; config.DisplayRunesHighContrast = chkHighContrastRunes.Checked; config.DisplayLayoutHorizontal = comboBoxLayout.SelectedIndex == 0; config.ColorName = btnSetNameColor.ForeColor; config.ColorDeaths = btnSetDeathsColor.ForeColor; config.ColorLevel = btnSetLevelColor.ForeColor; config.ColorDifficultyPercentages = btnSetDifficultyColor.ForeColor; config.ColorGold = btnSetGoldColor.ForeColor; config.ColorBaseStats = btnSetBaseStatsColor.ForeColor; config.ColorAdvancedStats = btnSetAdvancedStatsColor.ForeColor; config.ColorFireRes = btnSetFireResColor.ForeColor; config.ColorColdRes = btnSetColdResColor.ForeColor; config.ColorLightningRes = btnSetLightningResColor.ForeColor; config.ColorPoisonRes = btnSetPoisonResColor.ForeColor; config.ColorPlayersX = btnSetPlayersXColor.ForeColor; config.ColorSeed = btnSetSeedColor.ForeColor; config.ColorLife = btnSetLifeColor.ForeColor; config.ColorMana = btnSetManaColor.ForeColor; config.ColorGameCounter = btnSetGameCounterColor.ForeColor; config.ColorCharCounter = btnColorCharCount.ForeColor; config.ColorMagicFind = btnSetMFColor.ForeColor; config.ColorMonsterGold = btnSetExtraGoldColor.ForeColor; config.ColorAttackerSelfDamage = btnSetAttackerSelfDamageColor.ForeColor; config.ColorHardcoreSoftcore = btnColorHardcoreSoftcore.ForeColor; config.ColorExpansionClassic = btnColorExpansionClassic.ForeColor; config.ColorBackground = btnSetBackgroundColor.BackColor; return config; } void ConfigWindowOnFormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason != CloseReason.UserClosing || !IsDirty) return; DialogResult result = MessageBox.Show( @"Would you like to save your config before closing?", @"Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question ); switch (result) { case DialogResult.Yes: SaveConfig(di.configService.CurrentConfigFile); break; case DialogResult.No: break; case DialogResult.Cancel: e.Cancel = true; break; } } void SaveConfig(string path) { UseWaitCursor = true; di.configService.Save(path, CopyModifiedConfig()); UseWaitCursor = false; } void LoadConfig(string path) { UseWaitCursor = true; di.configService.Load(path); UseWaitCursor = false; } void NewConfig(string path) { UseWaitCursor = true; di.configService.Save(path, new ApplicationConfig()); UseWaitCursor = false; } void DeleteConfig(string path) { UseWaitCursor = true; di.configService.Delete(path); UseWaitCursor = false; } void Rename(string oldPath, string newPath) { UseWaitCursor = true; di.configService.Rename(oldPath, newPath); di.configService.Load(newPath); UseWaitCursor = false; } void Clone(string oldPath, string newPath) { UseWaitCursor = true; di.configService.Clone(oldPath, newPath); di.configService.Load(newPath); UseWaitCursor = false; } void SaveConfigAsMenuItem_Click(object sender, EventArgs e) { using (var d = new SimpleSaveDialog("Save as", string.Empty)) { d.StartPosition = FormStartPosition.CenterParent; if (d.ShowDialog() == DialogResult.OK) SaveConfig(Path.Combine(ConfigFilePath, d.NewFileName) + ".conf"); } } private void btnCancel_Click(object sender, EventArgs e) { if (IsDirty) LoadConfig(Properties.Settings.Default.SettingsFile); } private void btnSave_Click(object sender, EventArgs e) { SaveConfig(di.configService.CurrentConfigFile); } void ConfigCollectionChanged(object sender, ConfigCollectionEventArgs e) { if (InvokeRequired) { Invoke((Action)(() => ConfigCollectionChanged(sender, e))); return; } PopulateConfigFileList(e.Collection); } void PopulateConfigFileList(IEnumerable<FileInfo> configFileCollection) { lstConfigFiles.Items.Clear(); IEnumerable<ConfigEntry> items = configFileCollection.Select(CreateConfigEntry); lstConfigFiles.Items.AddRange(items.Cast<object>().ToArray()); } static ConfigEntry CreateConfigEntry(FileInfo fileInfo) => new ConfigEntry() { DisplayName = Path.GetFileNameWithoutExtension(fileInfo.Name), Path = fileInfo.FullName }; class ConfigEntry { public string DisplayName { get; set; } public string Path { get; set; } public override string ToString() { return DisplayName; } } private void lstConfigFiles_MouseDoubleClick(object sender, MouseEventArgs e) { // make sure we actually dbl click an item, not just anywhere in the box. int index = lstConfigFiles.IndexFromPoint(e.Location); if (index != ListBox.NoMatches) LoadConfig(((ConfigEntry)lstConfigFiles.Items[index]).Path); } private void lstConfigFiles_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { int index = lstConfigFiles.IndexFromPoint(e.Location); if (index != ListBox.NoMatches) { menuClone.Enabled = true; menuLoad.Enabled = true; menuNew.Enabled = true; menuDelete.Enabled = true; } else { menuClone.Enabled = false; menuLoad.Enabled = false; menuNew.Enabled = true; menuDelete.Enabled = false; } lstConfigFiles.ContextMenuStrip.Show(lstConfigFiles, new Point(e.X, e.Y)); } } void menuNew_Click(object sender, EventArgs e) { using (var d = new SimpleSaveDialog("New config", string.Empty)) if (d.ShowDialog() == DialogResult.OK) NewConfig(Path.Combine(ConfigFilePath, d.NewFileName) + ".conf"); } private void menuLoad_Click(object sender, EventArgs e) { LoadConfig(((ConfigEntry)lstConfigFiles.SelectedItem).Path); } void menuClone_Click(object sender, EventArgs e) { using (var d = new SimpleSaveDialog("Clone config", string.Empty)) if (d.ShowDialog() == DialogResult.OK) Clone( ((ConfigEntry)lstConfigFiles.SelectedItem).Path, Path.Combine(ConfigFilePath, d.NewFileName) + ".conf" ); } private void menuDelete_Click(object sender, EventArgs e) { DeleteConfig(((ConfigEntry)lstConfigFiles.SelectedItem).Path); } void SetBackgroundColor(Color c) { btnColorAll.BackColor = c; btnColorAll.ForeColor = (384 - c.R - c.G - c.B) > 0 ? Color.White : Color.Black; btnSetBackgroundColor.BackColor = c; btnSetBackgroundColor.ForeColor = (384 - c.R - c.G - c.B) > 0 ? Color.White : Color.Black; btnSetNameColor.BackColor = c; btnSetDeathsColor.BackColor = c; btnSetLevelColor.BackColor = c; btnSetDifficultyColor.BackColor = c; btnSetGoldColor.BackColor = c; btnSetBaseStatsColor.BackColor = c; btnSetAdvancedStatsColor.BackColor = c; btnSetFireResColor.BackColor = c; btnSetColdResColor.BackColor = c; btnSetLightningResColor.BackColor = c; btnSetPoisonResColor.BackColor = c; btnSetPlayersXColor.BackColor = c; btnSetSeedColor.BackColor = c; btnSetLifeColor.BackColor = c; btnSetManaColor.BackColor = c; btnSetGameCounterColor.BackColor = c; btnColorCharCount.BackColor = c; btnSetAttackerSelfDamageColor.BackColor = c; btnSetMFColor.BackColor = c; btnSetExtraGoldColor.BackColor = c; btnColorHardcoreSoftcore.BackColor = c; btnColorExpansionClassic.BackColor = c; } void SetForegroundColor(Color c) { btnSetNameColor.ForeColor = c; btnSetDeathsColor.ForeColor = c; btnSetLevelColor.ForeColor = c; btnSetDifficultyColor.ForeColor = c; btnSetGoldColor.ForeColor = c; btnSetBaseStatsColor.ForeColor = c; btnSetAdvancedStatsColor.ForeColor = c; btnSetFireResColor.ForeColor = c; btnSetColdResColor.ForeColor = c; btnSetLightningResColor.ForeColor = c; btnSetPoisonResColor.ForeColor = c; btnSetPlayersXColor.ForeColor = c; btnSetSeedColor.ForeColor = c; btnSetLifeColor.ForeColor = c; btnSetManaColor.ForeColor = c; btnSetGameCounterColor.ForeColor = c; btnColorCharCount.ForeColor = c; btnSetAttackerSelfDamageColor.ForeColor = c; btnSetMFColor.ForeColor = c; btnSetExtraGoldColor.ForeColor = c; btnColorHardcoreSoftcore.ForeColor = c; btnColorExpansionClassic.ForeColor = c; } private void btnSelectColor(object sender, EventArgs e) { using (var d = new ColorDialog()) if (d.ShowDialog() == DialogResult.OK) ((Control)sender).ForeColor = d.Color; } private void resetColorsButton(object sender, EventArgs e) { btnSetNameColor.ForeColor = Color.RoyalBlue; btnSetDeathsColor.ForeColor = Color.Snow; btnSetLevelColor.ForeColor = Color.Snow; btnSetDifficultyColor.ForeColor = Color.Snow; btnSetGoldColor.ForeColor = Color.Gold; btnSetBaseStatsColor.ForeColor = Color.Coral; btnSetAdvancedStatsColor.ForeColor = Color.Coral; btnSetFireResColor.ForeColor = Color.Red; btnSetColdResColor.ForeColor = Color.DodgerBlue; btnSetLightningResColor.ForeColor = Color.Yellow; btnSetPoisonResColor.ForeColor = Color.YellowGreen; btnSetPlayersXColor.ForeColor = Color.Snow; btnSetSeedColor.ForeColor = Color.Snow; btnSetLifeColor.ForeColor = Color.Snow; btnSetManaColor.ForeColor = Color.Snow; btnSetGameCounterColor.ForeColor = Color.Snow; btnColorCharCount.ForeColor = Color.Snow; btnSetAttackerSelfDamageColor.ForeColor = Color.Snow; btnSetMFColor.ForeColor = Color.Gold; btnSetExtraGoldColor.ForeColor = Color.Gold; btnColorHardcoreSoftcore.ForeColor = Color.Snow; btnColorExpansionClassic.ForeColor = Color.Snow; SetBackgroundColor(Color.Black); } private void backgroundColorButtonClick(object sender, EventArgs e) { using (var d = new ColorDialog()) if (d.ShowDialog() == DialogResult.OK) SetBackgroundColor(d.Color); } private void btnColorAll_Click(object sender, EventArgs e) { using (var d = new ColorDialog()) if (d.ShowDialog() == DialogResult.OK) SetForegroundColor(d.Color); } void renameToolStripMenuItem_Click(object sender, EventArgs e) { string current = ((ConfigEntry)lstConfigFiles.SelectedItem).Path; string fileName = Path.GetFileNameWithoutExtension(current); using (var d = new SimpleSaveDialog("Rename config", fileName)) if (d.ShowDialog() == DialogResult.OK) Rename(current, Path.Combine(ConfigFilePath, d.NewFileName) + ".conf"); } private void comboBoxLayout_SelectedIndexChanged(object sender, EventArgs e) { comboBoxRunesOrientation.Enabled = comboBoxLayout.SelectedIndex == 0; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration using VB = Microsoft.VisualBasic; namespace _4PosBackOffice.NET { internal partial class frmGlobalCost : System.Windows.Forms.Form { string strPath_DB1; private void loadLanguage() { //frmGlobalCost = No Code [Update Cost] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmGlobalCost.Caption = rsLang("LanguageLayoutLnk_Description"): frmGlobalCost.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Closest Match DB entry 2490 = Password //Frame1 = No Code [Passwords] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Frame11.Caption = rsLang("LanguageLayoutLnk_Description"): Frame1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Closest Match DB entry 2490 = Password //Label2 = No Code [Passwords] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Labels2.Caption = rsLang("LanguageLayoutLnk_Description"): Labels2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmGlobalCost.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } public bool ShowOpen() { bool functionReturnValue = false; string Extention = null; // ERROR: Not supported in C#: OnErrorStatement var _with1 = cmdDlgOpen; //.CancelError = True _with1.Title = "Upload Cost File"; _with1.FileName = ""; _with1.Filter = "CSV File (*.csv)|*.csv|CSV (*.csv)|*.csv|"; _with1.FilterIndex = 0; _with1.ShowDialog(); strPath_DB1 = _with1.FileName; if (!string.IsNullOrEmpty(strPath_DB1)) { this.txtFileName.Text = strPath_DB1; functionReturnValue = true; } else { functionReturnValue = false; } return functionReturnValue; Extracter: if (MsgBoxResult.Cancel) { return functionReturnValue; } Interaction.MsgBox(Err().Description); return functionReturnValue; } public bool ImportCSVtoAccess(ref string strFilePath) { bool functionReturnValue = false; bool dReceipt = false; Scripting.FileSystemObject oFileSys = new Scripting.FileSystemObject(); Scripting.TextStream oFile = default(Scripting.TextStream); string strCSV = null; string strFldName = null; //String of fields' name string strFV = null; //String of fields' values short iCount = 0; short x = 0; string strStr_1 = null; string strStr_2 = null; string temp = null; string strIn = null; bool blEmpty = false; bool blTrue = false; // ERROR: Not supported in C#: OnErrorStatement System.Windows.Forms.Application.DoEvents(); System.Windows.Forms.Application.DoEvents(); blTrue = false; blEmpty = true; dReceipt = false; if (oFileSys.FileExists(strFilePath)) { oFile = oFileSys.OpenTextFile(strFilePath, Scripting.IOMode.ForReading, false, Scripting.Tristate.TristateUseDefault); while (!oFile.AtEndOfLine) { if (prgUpload.Value == 300) { prgUpload.Value = 0; } else { prgUpload.Value = prgUpload.Value + 1; } blEmpty = false; strCSV = oFile.ReadLine; strFV = strCSV; strFldName = "Barcode Text,CostPrice Currency"; if (blTrue == false) { strFldName = "Barcode Text,CostPrice Currency"; modRecordSet.cnnDB.Execute("CREATE TABLE FRIENDYFOODHALL (" + strFldName + ")"); blTrue = true; dReceipt = true; //2 Read header strCSV = oFile.ReadLine; } if (strCSV != Constants.vbNullString) { //Repeat 4 Times // strStr_1 = strCSV; x = Strings.Len(strCSV) - Strings.Len(Strings.Right(strCSV, Strings.Len(strCSV) - Strings.InStr(strCSV, ","))); strStr_1 = Strings.Mid(strStr_1, 1, x - 1); strStr_2 = Strings.Right(strCSV, Strings.Len(strCSV) - Strings.InStr(strCSV, ",")); temp = strStr_2; strIn = "INSERT INTO FRIENDYFOODHALL (Barcode,CostPrice) VALUES ('" + Strings.Trim(strStr_1) + "'," + Convert.ToDecimal(Strings.Trim(strStr_2)) + ")"; modRecordSet.cnnDB.Execute(strIn); } } if (blEmpty == true) { Interaction.MsgBox("Your CSV file is empty", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information + MsgBoxStyle.OkOnly, _4PosBackOffice.NET.My.MyProject.Application.Info.Title); functionReturnValue = false; return functionReturnValue; } prgUpload.Value = 300; functionReturnValue = true; return functionReturnValue; } else if (!oFileSys.FileExists(strFilePath)) { Interaction.MsgBox("CSV File does not exist", MsgBoxStyle.Information, _4PosBackOffice.NET.My.MyProject.Application.Info.Title); functionReturnValue = false; return functionReturnValue; } ImportError: Interaction.MsgBox("Export Aborted Because " + Err().Description, MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information + MsgBoxStyle.OkOnly, _4PosBackOffice.NET.My.MyProject.Application.Info.Title); modRecordSet.cnnDB.Execute("DROP TABLE FRIENDYFOODHALL"); return functionReturnValue; } private void Command1_Click(System.Object eventSender, System.EventArgs eventArgs) { if (ShowOpen() == true) { if (ImportCSVtoAccess(ref Strings.Trim(txtFileName.Text)) == true) { DoCostingUpdate(); this.Close(); } } else { return; } } private void Command3_Click(System.Object eventSender, System.EventArgs eventArgs) { this.Close(); } public void DoCostingUpdate() { ADODB.Recordset rj = default(ADODB.Recordset); rj = modRecordSet.getRS(ref "SELECT StockItem.StockItem_ListCost, StockItem.StockItem_ActualCost FROM (StockItem INNER JOIN Catalogue ON StockItem.StockItemID = Catalogue.Catalogue_StockItemID) INNER JOIN FRIENDYFOODHALL ON Catalogue.Catalogue_Barcode = FRIENDYFOODHALL.BARCODE WHERE FRIENDYFOODHALL.BARCODE IS NOT NULL;"); if (rj.RecordCount) { if (Interaction.MsgBox("Your about to update [ " + rj.RecordCount + " ] Records do you want to continue?", MsgBoxStyle.ApplicationModal + MsgBoxStyle.YesNo + MsgBoxStyle.Question, _4PosBackOffice.NET.My.MyProject.Application.Info.Title) == MsgBoxResult.Yes) { modRecordSet.cnnDB.Execute("UPDATE (StockItem INNER JOIN Catalogue ON [StockItem].[StockItemID]=[Catalogue].[Catalogue_StockItemID]) INNER JOIN FRIENDYFOODHALL ON [Catalogue].[Catalogue_Barcode]=[FRIENDYFOODHALL].[BARCODE] SET StockItem.StockItem_ListCost = [FRIENDYFOODHALL]![CostPrice], StockItem.StockItem_ActualCost = [FRIENDYFOODHALL]![CostPrice] WHERE [FRIENDYFOODHALL].[BARCODE] IS NOT NULL;"); modRecordSet.cnnDB.Execute("UPDATE StockItem SET StockItem_ActualCost = 1,StockItem_ListCost= 1 WHERE StockItem.StockItem_ListCost = 0 OR StockItem.StockItem_ListCost = 0;"); Interaction.MsgBox("Update Completed successfully"); modRecordSet.cnnDB.Execute("DROP TABLE FRIENDYFOODHALL"); } } } private void txtPassword_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs) { short KeyCode = eventArgs.KeyCode; short Shift = eventArgs.KeyData / 0x10000; if (KeyCode == 27) this.Close(); } private void txtPassword_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); string dtDate = null; string dtMonth = null; string stPass = null; //Construct password........... if (KeyAscii == 13) { if (Strings.Len(DateAndTime.Day(DateAndTime.Today)) == 1) dtDate = "0" + Conversion.Str(DateAndTime.Day(DateAndTime.Today)); else dtDate = Strings.Trim(Conversion.Str(DateAndTime.Day(DateAndTime.Today))); if (Strings.Len(DateAndTime.Month(DateAndTime.Today)) == 1) dtMonth = "0" + Conversion.Str(DateAndTime.Month(DateAndTime.Today)); else dtMonth = Strings.Trim(Conversion.Str(DateAndTime.Month(DateAndTime.Today))); //Create password stPass = dtDate + "##" + dtMonth; stPass = Strings.Replace(stPass, " ", ""); if (Strings.Trim(this.txtPassword.Text) == stPass) { //Call intialize process... Frame1.Visible = false; } else { Interaction.MsgBox("Incorrect password was entered!!!", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "4POS Stock Fix"); } } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcgv = Google.Cloud.GkeHub.V1Beta1; using sys = System; namespace Google.Cloud.GkeHub.V1Beta1 { /// <summary>Resource name for the <c>Membership</c> resource.</summary> public sealed partial class MembershipName : gax::IResourceName, sys::IEquatable<MembershipName> { /// <summary>The possible contents of <see cref="MembershipName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/memberships/{membership}</c>. /// </summary> ProjectLocationMembership = 1, } private static gax::PathTemplate s_projectLocationMembership = new gax::PathTemplate("projects/{project}/locations/{location}/memberships/{membership}"); /// <summary>Creates a <see cref="MembershipName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="MembershipName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static MembershipName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new MembershipName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="MembershipName"/> with the pattern /// <c>projects/{project}/locations/{location}/memberships/{membership}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="membershipId">The <c>Membership</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="MembershipName"/> constructed from the provided ids.</returns> public static MembershipName FromProjectLocationMembership(string projectId, string locationId, string membershipId) => new MembershipName(ResourceNameType.ProjectLocationMembership, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), membershipId: gax::GaxPreconditions.CheckNotNullOrEmpty(membershipId, nameof(membershipId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="MembershipName"/> with pattern /// <c>projects/{project}/locations/{location}/memberships/{membership}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="membershipId">The <c>Membership</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MembershipName"/> with pattern /// <c>projects/{project}/locations/{location}/memberships/{membership}</c>. /// </returns> public static string Format(string projectId, string locationId, string membershipId) => FormatProjectLocationMembership(projectId, locationId, membershipId); /// <summary> /// Formats the IDs into the string representation of this <see cref="MembershipName"/> with pattern /// <c>projects/{project}/locations/{location}/memberships/{membership}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="membershipId">The <c>Membership</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MembershipName"/> with pattern /// <c>projects/{project}/locations/{location}/memberships/{membership}</c>. /// </returns> public static string FormatProjectLocationMembership(string projectId, string locationId, string membershipId) => s_projectLocationMembership.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(membershipId, nameof(membershipId))); /// <summary>Parses the given resource name string into a new <see cref="MembershipName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/memberships/{membership}</c></description> /// </item> /// </list> /// </remarks> /// <param name="membershipName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="MembershipName"/> if successful.</returns> public static MembershipName Parse(string membershipName) => Parse(membershipName, false); /// <summary> /// Parses the given resource name string into a new <see cref="MembershipName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/memberships/{membership}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="membershipName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="MembershipName"/> if successful.</returns> public static MembershipName Parse(string membershipName, bool allowUnparsed) => TryParse(membershipName, allowUnparsed, out MembershipName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MembershipName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/memberships/{membership}</c></description> /// </item> /// </list> /// </remarks> /// <param name="membershipName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="MembershipName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string membershipName, out MembershipName result) => TryParse(membershipName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MembershipName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/memberships/{membership}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="membershipName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="MembershipName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string membershipName, bool allowUnparsed, out MembershipName result) { gax::GaxPreconditions.CheckNotNull(membershipName, nameof(membershipName)); gax::TemplatedResourceName resourceName; if (s_projectLocationMembership.TryParseName(membershipName, out resourceName)) { result = FromProjectLocationMembership(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(membershipName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private MembershipName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string membershipId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; MembershipId = membershipId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="MembershipName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/memberships/{membership}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="membershipId">The <c>Membership</c> ID. Must not be <c>null</c> or empty.</param> public MembershipName(string projectId, string locationId, string membershipId) : this(ResourceNameType.ProjectLocationMembership, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), membershipId: gax::GaxPreconditions.CheckNotNullOrEmpty(membershipId, nameof(membershipId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Membership</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string MembershipId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationMembership: return s_projectLocationMembership.Expand(ProjectId, LocationId, MembershipId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as MembershipName); /// <inheritdoc/> public bool Equals(MembershipName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(MembershipName a, MembershipName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(MembershipName a, MembershipName b) => !(a == b); } public partial class Membership { /// <summary> /// <see cref="gcgv::MembershipName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcgv::MembershipName MembershipName { get => string.IsNullOrEmpty(Name) ? null : gcgv::MembershipName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
/* * 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 OpenMetaverse; using OpenSim.Framework; using OpenSim.Data.SimpleDB; using System.Data; namespace InWorldz.Data.Inventory.Cassandra { /// <summary> /// A MySQL interface for the inventory server /// </summary> public class LegacyMysqlStorageImpl { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); ConnectionFactory _connFactory; private string _connectString; public LegacyMysqlStorageImpl(string connStr) { _connectString = connStr; _connFactory = new ConnectionFactory("MySQL", _connectString); } public InventoryFolderBase findUserFolderForType(UUID userId, int typeId) { string query = "SELECT * FROM inventoryfolders WHERE agentID = ?agentId AND type = ?type;"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?agentId", userId); parms.Add("?type", typeId); try { using (ISimpleDB conn = _connFactory.GetConnection()) { using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { if (reader.Read()) { // A null item (because something went wrong) breaks everything in the folder return readInventoryFolder(reader); } else { return null; } } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Returns the most appropriate folder for the given inventory type, or null if one could not be found /// </summary> /// <param name="userId"></param> /// <param name="type"></param> /// <returns></returns> public InventoryFolderBase findUserTopLevelFolderFor(UUID owner, UUID folderID) { // this is a stub, not supported in MySQL legacy storage m_log.ErrorFormat("[MySQLInventoryData]: Inventory for user {0} needs to be migrated to Cassandra.", owner.ToString()); return null; } /// <summary> /// Returns a list of items in the given folders /// </summary> /// <param name="folders"></param> /// <returns></returns> public List<InventoryItemBase> getItemsInFolders(IEnumerable<InventoryFolderBase> folders) { string inList = String.Empty; foreach (InventoryFolderBase folder in folders) { if (!String.IsNullOrEmpty(inList)) inList += ","; inList += "'" + folder.ID.ToString() + "'"; } if (String.IsNullOrEmpty(inList)) return new List<InventoryItemBase>(); string query = "SELECT * FROM inventoryitems WHERE parentFolderID IN (" + inList + ");"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { using (IDataReader reader = conn.QueryAndUseReader(query)) { List<InventoryItemBase> items = new List<InventoryItemBase>(); while (reader.Read()) { // A null item (because something went wrong) breaks everything in the folder InventoryItemBase item = readInventoryItem(reader); if (item != null) items.Add(item); } return items; } } } catch (Exception e) { m_log.Error(e.ToString()); return new List<InventoryItemBase>(); } } /// <summary> /// Returns a list of items in a specified folder /// </summary> /// <param name="folderID">The folder to search</param> /// <returns>A list containing inventory items</returns> public List<InventoryItemBase> getInventoryInFolder(UUID folderID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", folderID.ToString()); List<InventoryItemBase> items = new List<InventoryItemBase>(); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { while (reader.Read()) { // A null item (because something went wrong) breaks everything in the folder InventoryItemBase item = readInventoryItem(reader); if (item != null) items.Add(item); } } return items; } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Returns a list of the root folders within a users inventory (folders that only have the root as their parent) /// </summary> /// <param name="user">The user whos inventory is to be searched</param> /// <returns>A list of folder objects</returns> public List<InventoryFolderBase> getUserRootFolders(UUID user, UUID root) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryfolders WHERE parentFolderID = ?root AND agentID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", user.ToString()); parms.Add("?root", root.ToString()); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { List<InventoryFolderBase> items = new List<InventoryFolderBase>(); while (reader.Read()) items.Add(readInventoryFolder(reader)); return items; } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// see <see cref="InventoryItemBase.getUserRootFolder"/> /// </summary> /// <param name="user">The user UUID</param> /// <returns></returns> public InventoryFolderBase getUserRootFolder(UUID user) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", user.ToString()); parms.Add("?zero", UUID.Zero.ToString()); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { List<InventoryFolderBase> items = new List<InventoryFolderBase>(); while (reader.Read()) items.Add(readInventoryFolder(reader)); InventoryFolderBase rootFolder = null; // There should only ever be one root folder for a user. However, if there's more // than one we'll simply use the first one rather than failing. It would be even // nicer to print some message to this effect, but this feels like it's too low a // to put such a message out, and it's too minor right now to spare the time to // suitably refactor. if (items.Count > 0) { rootFolder = items[0]; } return rootFolder; } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Return a list of folders in a users inventory contained within the specified folder. /// This method is only used in tests - in normal operation the user always have one, /// and only one, root folder. /// </summary> /// <param name="parentID">The folder to search</param> /// <returns>A list of inventory folders</returns> public List<InventoryFolderBase> getInventoryFolders(UUID parentID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", parentID.ToString()); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { List<InventoryFolderBase> items = new List<InventoryFolderBase>(); while (reader.Read()) items.Add(readInventoryFolder(reader)); return items; } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Reads a one item from an SQL result /// </summary> /// <param name="reader">The SQL Result</param> /// <returns>the item read</returns> private static InventoryItemBase readInventoryItem(IDataReader reader) { try { InventoryItemBase item = new InventoryItemBase(); // TODO: this is to handle a case where NULLs creep in there, which we are not sure is indemic to the system, or legacy. It would be nice to live fix these. if (reader["creatorID"] == null) { item.CreatorId = UUID.Zero.ToString(); } else { item.CreatorId = (string)reader["creatorID"]; } // Be a bit safer in parsing these because the // database doesn't enforce them to be not null, and // the inventory still works if these are weird in the // db UUID Owner = UUID.Zero; UUID GroupID = UUID.Zero; UUID.TryParse(Convert.ToString(reader["avatarID"]), out Owner); UUID.TryParse(Convert.ToString(reader["groupID"]), out GroupID); item.Owner = Owner; item.GroupID = GroupID; // Rest of the parsing. If these UUID's fail, we're dead anyway item.ID = new UUID(Convert.ToString(reader["inventoryID"])); item.AssetID = new UUID(Convert.ToString(reader["assetID"])); item.AssetType = (int)reader["assetType"]; item.Folder = new UUID(Convert.ToString(reader["parentFolderID"])); item.Name = (string)reader["inventoryName"]; item.Description = (string)reader["inventoryDescription"]; item.NextPermissions = (uint)reader["inventoryNextPermissions"]; item.CurrentPermissions = (uint)reader["inventoryCurrentPermissions"]; item.InvType = (int)reader["invType"]; item.BasePermissions = (uint)reader["inventoryBasePermissions"]; item.EveryOnePermissions = (uint)reader["inventoryEveryOnePermissions"]; item.GroupPermissions = (uint)reader["inventoryGroupPermissions"]; item.SalePrice = (int)reader["salePrice"]; item.SaleType = Convert.ToByte(reader["saleType"]); item.CreationDate = (int)reader["creationDate"]; item.GroupOwned = Convert.ToBoolean(reader["groupOwned"]); item.Flags = (uint)reader["flags"]; return item; } catch (Exception e) { m_log.Error(e.ToString()); } return null; } /// <summary> /// Returns a specified inventory item /// </summary> /// <param name="item">The item to return</param> /// <returns>An inventory item</returns> public InventoryItemBase getInventoryItem(UUID itemID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryitems WHERE inventoryID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", itemID.ToString()); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { InventoryItemBase item = null; if (reader.Read()) item = readInventoryItem(reader); return item; } } } catch (Exception e) { m_log.Error(e.ToString()); } return null; } /// <summary> /// Reads a list of inventory folders returned by a query. /// </summary> /// <param name="reader">A MySQL Data Reader</param> /// <returns>A List containing inventory folders</returns> protected static InventoryFolderBase readInventoryFolder(IDataReader reader) { try { InventoryFolderBase folder = new InventoryFolderBase(); folder.Owner = new UUID(Convert.ToString(reader["agentID"])); folder.ParentID = new UUID(Convert.ToString(reader["parentFolderID"])); folder.ID = new UUID(Convert.ToString(reader["folderID"])); folder.Name = (string)reader["folderName"]; folder.Type = (short)reader["type"]; folder.Version = (ushort)((int)reader["version"]); return folder; } catch (Exception e) { m_log.Error(e.ToString()); } return null; } /// <summary> /// Returns a specified inventory folder /// </summary> /// <param name="folder">The folder to return</param> /// <returns>A folder class</returns> public InventoryFolderBase getInventoryFolder(UUID folderID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryfolders WHERE folderID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", folderID.ToString()); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { if (reader.Read()) { InventoryFolderBase folder = readInventoryFolder(reader); return folder; } else { return null; } } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Adds a specified item to the database /// </summary> /// <param name="item">The inventory item</param> public void addInventoryItem(InventoryItemBase item) { string sql = "REPLACE INTO inventoryitems (inventoryID, assetID, assetType, parentFolderID, avatarID, inventoryName" + ", inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType" + ", creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, inventoryGroupPermissions, salePrice, saleType" + ", creationDate, groupID, groupOwned, flags) VALUES "; sql += "(?inventoryID, ?assetID, ?assetType, ?parentFolderID, ?avatarID, ?inventoryName, ?inventoryDescription" + ", ?inventoryNextPermissions, ?inventoryCurrentPermissions, ?invType, ?creatorID" + ", ?inventoryBasePermissions, ?inventoryEveryOnePermissions, ?inventoryGroupPermissions, ?salePrice, ?saleType, ?creationDate" + ", ?groupID, ?groupOwned, ?flags)"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?inventoryID", item.ID.ToString()); parms.Add("?assetID", item.AssetID.ToString()); parms.Add("?assetType", item.AssetType.ToString()); parms.Add("?parentFolderID", item.Folder.ToString()); parms.Add("?avatarID", item.Owner.ToString()); parms.Add("?inventoryName", item.Name); parms.Add("?inventoryDescription", item.Description); parms.Add("?inventoryNextPermissions", item.NextPermissions.ToString()); parms.Add("?inventoryCurrentPermissions", item.CurrentPermissions.ToString()); parms.Add("?invType", item.InvType); parms.Add("?creatorID", item.CreatorId); parms.Add("?inventoryBasePermissions", item.BasePermissions); parms.Add("?inventoryEveryOnePermissions", item.EveryOnePermissions); parms.Add("?inventoryGroupPermissions", item.GroupPermissions); parms.Add("?salePrice", item.SalePrice); parms.Add("?saleType", item.SaleType); parms.Add("?creationDate", item.CreationDate); parms.Add("?groupID", item.GroupID); parms.Add("?groupOwned", item.GroupOwned); parms.Add("?flags", item.Flags); conn.QueryNoResults(sql, parms); // Also increment the parent version number if not null. this.IncrementSpecifiedFolderVersion(conn, item.Folder); } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Updates the specified inventory item /// </summary> /// <param name="item">Inventory item to update</param> public void updateInventoryItem(InventoryItemBase item) { //addInventoryItem(item); /* 12/9/2009 - Ele's Edit - Rather than simply adding a whole new item, which seems kind of pointless to me, let's actually try UPDATING the item as it should be. This is not fully functioning yet from the updating of items * within Scene.Inventory.cs MoveInventoryItem yet. Not sure the effect it will have on the rest of the updates either, as they * originally pointed back to addInventoryItem above. */ string sql = "UPDATE inventoryitems SET assetID=?assetID, assetType=?assetType, parentFolderID=?parentFolderID, " + "avatarID=?avatarID, inventoryName=?inventoryName, inventoryDescription=?inventoryDescription, inventoryNextPermissions=?inventoryNextPermissions, " + "inventoryCurrentPermissions=?inventoryCurrentPermissions, invType=?invType, creatorID=?creatorID, inventoryBasePermissions=?inventoryBasePermissions, " + "inventoryEveryOnePermissions=?inventoryEveryOnePermissions, inventoryGroupPermissions=?inventoryGroupPermissions, salePrice=?salePrice, " + "saleType=?saleType, creationDate=?creationDate, groupID=?groupID, groupOwned=?groupOwned, flags=?flags " + "WHERE inventoryID=?inventoryID"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?inventoryID", item.ID.ToString()); parms.Add("?assetID", item.AssetID.ToString()); parms.Add("?assetType", item.AssetType.ToString()); parms.Add("?parentFolderID", item.Folder.ToString()); parms.Add("?avatarID", item.Owner.ToString()); parms.Add("?inventoryName", item.Name); parms.Add("?inventoryDescription", item.Description); parms.Add("?inventoryNextPermissions", item.NextPermissions.ToString()); parms.Add("?inventoryCurrentPermissions", item.CurrentPermissions.ToString()); parms.Add("?invType", item.InvType); parms.Add("?creatorID", item.CreatorId); parms.Add("?inventoryBasePermissions", item.BasePermissions); parms.Add("?inventoryEveryOnePermissions", item.EveryOnePermissions); parms.Add("?inventoryGroupPermissions", item.GroupPermissions); parms.Add("?salePrice", item.SalePrice); parms.Add("?saleType", item.SaleType); parms.Add("?creationDate", item.CreationDate); parms.Add("?groupID", item.GroupID); parms.Add("?groupOwned", item.GroupOwned); parms.Add("?flags", item.Flags); conn.QueryNoResults(sql, parms); // Also increment the parent version number if not null. this.IncrementSpecifiedFolderVersion(conn, item.Folder); } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Detele the specified inventory item /// </summary> /// <param name="item">The inventory item UUID to delete</param> public void deleteInventoryItem(InventoryItemBase item) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "DELETE FROM inventoryitems WHERE inventoryID=?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", item.ID.ToString()); conn.QueryNoResults(query, parms); // Also increment the parent version number if not null. this.IncrementSpecifiedFolderVersion(conn, item.Folder); } } catch (Exception e) { m_log.Error(e.ToString()); } } public InventoryItemBase queryInventoryItem(UUID itemID) { return getInventoryItem(itemID); } public InventoryFolderBase queryInventoryFolder(UUID folderID) { return getInventoryFolder(folderID); } /// <summary> /// Creates a new inventory folder /// </summary> /// <param name="folder">Folder to create</param> public void addInventoryFolder(InventoryFolderBase folder) { if (folder.ID == UUID.Zero) { m_log.Error("Not storing zero UUID folder for " + folder.Owner.ToString()); return; } string sql = "REPLACE INTO inventoryfolders (folderID, agentID, parentFolderID, folderName, type, version) VALUES "; sql += "(?folderID, ?agentID, ?parentFolderID, ?folderName, ?type, ?version)"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?folderID", folder.ID.ToString()); parms.Add("?agentID", folder.Owner.ToString()); parms.Add("?parentFolderID", folder.ParentID.ToString()); parms.Add("?folderName", folder.Name); parms.Add("?type", (short)folder.Type); parms.Add("?version", folder.Version); conn.QueryNoResults(sql, parms); // Also increment the parent version number if not null. this.IncrementSpecifiedFolderVersion(conn, folder.ParentID); } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Increments the version of the passed folder, making sure the folder isn't Zero. Must be called from within a using{} block! /// </summary> /// <param name="conn">Database connection.</param> /// <param name="folderId">Folder UUID to increment</param> private void IncrementSpecifiedFolderVersion(ISimpleDB conn, UUID folderId) { if (folderId != UUID.Zero) { string query = "update inventoryfolders set version=version+1 where folderID = ?folderID"; Dictionary<string, object> updParms = new Dictionary<string, object>(); updParms.Add("?folderID", folderId.ToString()); conn.QueryNoResults(query, updParms); } } /// <summary> /// Updates an inventory folder /// </summary> /// <param name="folder">Folder to update</param> public void updateInventoryFolder(InventoryFolderBase folder) { string sql = "update inventoryfolders set folderName=?folderName where folderID=?folderID"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?folderName", folder.Name); parms.Add("?folderID", folder.ID.ToString()); conn.QueryNoResults(sql, parms); // Also increment the version number if not null. this.IncrementSpecifiedFolderVersion(conn, folder.ID); } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Move an inventory folder /// </summary> /// <param name="folder">Folder to move</param> /// <remarks>UPDATE inventoryfolders SET parentFolderID=?parentFolderID WHERE folderID=?folderID</remarks> public void moveInventoryFolder(InventoryFolderBase folder, UUID parentId) { string sql = "UPDATE inventoryfolders SET parentFolderID=?parentFolderID WHERE folderID=?folderID"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?folderID", folder.ID.ToString()); parms.Add("?parentFolderID", parentId.ToString()); conn.QueryNoResults(sql, parms); folder.ParentID = parentId; // Only change if the above succeeded. // Increment both the old and the new parents - checking for null. this.IncrementSpecifiedFolderVersion(conn, parentId); this.IncrementSpecifiedFolderVersion(conn, folder.ParentID); } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Append a list of all the child folders of a parent folder /// </summary> /// <param name="folders">list where folders will be appended</param> /// <param name="parentID">ID of parent</param> protected void getInventoryFolders(ref List<InventoryFolderBase> folders, UUID parentID) { List<InventoryFolderBase> subfolderList = getInventoryFolders(parentID); foreach (InventoryFolderBase f in subfolderList) folders.Add(f); } /// <summary> /// See IInventoryDataPlugin /// </summary> /// <param name="parentID"></param> /// <returns></returns> public List<InventoryFolderBase> getFolderHierarchy(UUID parentID) { /* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one * - We will only need to hit the database twice instead of n times. * - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned * by the same person, each user only has 1 inventory heirarchy * - The returned list is not ordered, instead of breadth-first ordered There are basically 2 usage cases for getFolderHeirarchy: 1) Getting the user's entire inventory heirarchy when they log in 2) Finding a subfolder heirarchy to delete when emptying the trash. This implementation will pull all inventory folders from the database, and then prune away any folder that is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the database than to make n requests. This pays off only if requested heirarchy is large. By making this choice, we are making the worst case better at the cost of making the best case worse. This way is generally better because we don't have to rebuild the connection/sql query per subfolder, even if we end up getting more data from the SQL server than we need. - Francis */ try { List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); Dictionary<UUID, List<InventoryFolderBase>> hashtable = new Dictionary<UUID, List<InventoryFolderBase>>(); ; List<InventoryFolderBase> parentFolder = new List<InventoryFolderBase>(); using (ISimpleDB conn = _connFactory.GetConnection()) { bool buildResultsFromHashTable = false; /* Fetch the parent folder from the database to determine the agent ID, and if * we're querying the root of the inventory folder tree */ string query = "SELECT * FROM inventoryfolders WHERE folderID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", parentID.ToString()); IDataReader reader; using (reader = conn.QueryAndUseReader(query, parms)) { while (reader.Read()) // Should be at most 1 result parentFolder.Add(readInventoryFolder(reader)); } if (parentFolder.Count >= 1) // No result means parent folder does not exist { if (parentFolder[0].ParentID == UUID.Zero) // We are querying the root folder { /* Get all of the agent's folders from the database, put them in a list and return it */ parms.Clear(); query = "SELECT * FROM inventoryfolders WHERE agentID = ?uuid"; parms.Add("?uuid", parentFolder[0].Owner.ToString()); using (reader = conn.QueryAndUseReader(query, parms)) { while (reader.Read()) { InventoryFolderBase curFolder = readInventoryFolder(reader); if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list folders.Add(curFolder); } } } // if we are querying the root folder else // else we are querying a subtree of the inventory folder tree { /* Get all of the agent's folders from the database, put them all in a hash table * indexed by their parent ID */ parms.Clear(); query = "SELECT * FROM inventoryfolders WHERE agentID = ?uuid"; parms.Add("?uuid", parentFolder[0].Owner.ToString()); using (reader = conn.QueryAndUseReader(query, parms)) { while (reader.Read()) { InventoryFolderBase curFolder = readInventoryFolder(reader); if (hashtable.ContainsKey(curFolder.ParentID)) // Current folder already has a sibling hashtable[curFolder.ParentID].Add(curFolder); // append to sibling list else // else current folder has no known (yet) siblings { List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>(); siblingList.Add(curFolder); // Current folder has no known (yet) siblings hashtable.Add(curFolder.ParentID, siblingList); } } // while more items to read from the database } // Set flag so we know we need to build the results from the hash table after // we unlock the database buildResultsFromHashTable = true; } // else we are querying a subtree of the inventory folder tree } // if folder parentID exists if (buildResultsFromHashTable) { /* We have all of the user's folders stored in a hash table indexed by their parent ID * and we need to return the requested subtree. We will build the requested subtree * by performing a breadth-first-search on the hash table */ if (hashtable.ContainsKey(parentID)) folders.AddRange(hashtable[parentID]); for (int i = 0; i < folders.Count; i++) // **Note: folders.Count is *not* static if (hashtable.ContainsKey(folders[i].ID)) folders.AddRange(hashtable[folders[i].ID]); } } // lock (database) return folders; } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Delete a folder from database. Must be called from within a using{} block for the database connection. /// </summary> /// Passing in the connection allows for consolidation of the DB connections, important as this method is often called from an inner loop. /// <param name="folderID">the folder UUID</param> /// <param name="conn">the database connection</param> private void deleteOneFolder(ISimpleDB conn, InventoryFolderBase folder) { string query = "DELETE FROM inventoryfolders WHERE folderID=?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", folder.ID.ToString()); conn.QueryNoResults(query, parms); // As the callers of this function will increment the version, there's no need to do so here. } /// <summary> /// Delete all subfolders and items in a folder. Must be called from within a using{} block for the database connection. /// </summary> /// Passing in the connection allows for consolidation of the DB connections, important as this method is often called from an inner loop. /// <param name="folderID">the folder UUID</param> /// <param name="conn">the database connection</param> private void deleteFolderContents(ISimpleDB conn, UUID folderID) { // Get a flattened list of all subfolders. List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID); // Delete all sub-folders foreach (InventoryFolderBase f in subFolders) { deleteFolderContents(conn, f.ID); // Recurse! deleteOneFolder(conn, f); } // Delete the actual items in this folder. string query = "DELETE FROM inventoryitems WHERE parentFolderID=?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", folderID.ToString()); conn.QueryNoResults(query, parms); // As the callers of this function will increment the version, there's no need to do so here where this is most often ceing called from an inner loop! } /// <summary> /// Delete all subfolders and items in a folder. /// </summary> /// <param name="folderID">the folder UUID</param> public void deleteFolderContents(UUID folderID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { using (ITransaction transaction = conn.BeginTransaction()) // Use a transaction to guarantee that the following it atomic - it'd be bad to have a partial delete of the tree! { deleteFolderContents(conn, folderID); // Increment the version of the purged folder. this.IncrementSpecifiedFolderVersion(conn, folderID); transaction.Commit(); } } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Deletes an inventory folder /// </summary> /// <param name="folderId">Id of folder to delete</param> public void deleteInventoryFolder(InventoryFolderBase folder) { // Get a flattened list of all subfolders. List<InventoryFolderBase> subFolders = getFolderHierarchy(folder.ID); try { using (ISimpleDB conn = _connFactory.GetConnection()) { using (ITransaction transaction = conn.BeginTransaction()) // Use a transaction to guarantee that the following it atomic - it'd be bad to have a partial delete of the tree! { // Since the DB doesn't currently have foreign key constraints the order of delete ops doean't matter, // however it's better practice to remove the contents and then remove the folder itself. // Delete all sub-folders foreach (InventoryFolderBase f in subFolders) { deleteFolderContents(conn, f.ID); deleteOneFolder(conn, f); } // Delete the actual row deleteFolderContents(conn, folder.ID); deleteOneFolder(conn, folder); // Increment the version of the parent of the purged folder. this.IncrementSpecifiedFolderVersion(conn, folder.ParentID); transaction.Commit(); } } } catch (Exception e) { m_log.Error(e.ToString()); } } public List<InventoryItemBase> fetchActiveGestures(UUID avatarID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags & 1"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", avatarID.ToString()); parms.Add("?type", (int)AssetType.Gesture); using (IDataReader result = conn.QueryAndUseReader(query, parms)) { List<InventoryItemBase> list = new List<InventoryItemBase>(); while (result.Read()) { InventoryItemBase item = readInventoryItem(result); if (item != null) list.Add(item); } return list; } } } catch (Exception e) { m_log.Error(e.ToString()); return new List<InventoryItemBase>(); } } public List<InventoryItemBase> getAllItems(UUID avatarID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryitems WHERE avatarId = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", avatarID.ToString()); using (IDataReader result = conn.QueryAndUseReader(query, parms)) { List<InventoryItemBase> list = new List<InventoryItemBase>(); while (result.Read()) { InventoryItemBase item = readInventoryItem(result); if (item != null) list.Add(item); } return list; } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } } }
using System; using System.Collections.Generic; using System.Linq; using Starcounter; using Starcounter.Linq; namespace People { partial class PersonPage : Json, IBound<Person>, IConfirmPage { public Action ConfirmAction = null; public ContactInfoProvider ContactInfoProvider { get; protected set; } = new ContactInfoProvider(); protected override void OnData() { base.OnData(); this.ObjectId = this.Data?.GetObjectID(); this.CountryList.Data = CountryListUtil.BuildCollection(); if (this.Data.Birthdate != DateTime.MinValue) { this.BirthDate = this.Data.Birthdate.ToString("yyyy-MM-dd"); } var personSelectOrganizationPage = Self.GET<PersonSelectOrganizationPage>("/people/partial/personSelectOrganizationPage"); personSelectOrganizationPage.Data = null; personSelectOrganizationPage.SelectOrganization = (Organization org) => { if (this.Organizations.Any(x => x.Parent.Equals(org))) { return; } new ParentRelation() { Parent = org, Child = this.Data }; }; this.PersonSelectOrganizationPage = personSelectOrganizationPage; } void Handle(Input.Save action) { AttachedScope.Commit(); DeleteUnused(); } void Handle(Input.Cancel action) { this.GoBack(); } void Handle(Input.AddAddress action) { Address a = this.ContactInfoProvider.CreateAddress(this.Data); this.AddAddressElement(a); } void Handle(Input.AddEmailAddress action) { EmailAddress ea = this.ContactInfoProvider.CreateEmailAddress(this.Data); this.AddEmailAddressElement(ea); } void Handle(Input.AddPhoneNumber action) { PhoneNumber pn = this.ContactInfoProvider.CreatePhoneNumber(this.Data); this.AddPhoneNumberElement(pn); } void Handle(Input.AddCustomContactInfo action) { CustomContactInfo customContactInfo = this.ContactInfoProvider.CreateCustomContactInfo(this.Data); this.AddCustomContactInfoElement(customContactInfo); } void Handle(Input.BirthDate action) { var birthday = new DateTime(); DateTime.TryParse(action.Value, out birthday); this.Data.Birthdate = birthday; } void DeleteUnused() { this.ContactInfoProvider.DeleteEmptyContactInfoItems(); this.RefreshContactInfos(); } public void GoBack() { this.RedirectUrl = "/people/persons"; } public void RefreshContactInfos() { this.Addresses.Clear(); this.EmailAddresses.Clear(); this.PhoneNumbers.Clear(); this.CustomContactInfos.Clear(); foreach (ContactInfo ci in this.Data.ContactInfos) { switch (ci) { case EmailAddress emailAddress: { this.AddEmailAddressElement(emailAddress); break; } case Address address: { this.AddAddressElement(address); break; } case PhoneNumber phoneNumber: { this.AddPhoneNumberElement(phoneNumber); break; } case CustomContactInfo customContactInfo: { this.AddCustomContactInfoElement(customContactInfo); break; } } } } public IEnumerable<ParentRelation> Organizations => DbLinq.Objects<ParentRelation>().Where(x => x.Child == this.Data); [PersonPage_json.Organizations] partial class PersonOrgPage : Json, IBound<ParentRelation> { private OrganizationsProvider organizationsProvider = new OrganizationsProvider(); public string Key => this.Data.GetObjectID(); public string EditUrl => $"/people/organizations/{this.Data.Parent.GetObjectID()}"; public string ParentName => this.Data.Parent.Name; void Handle(Input.Delete Action) { this.ParentPage.Confirm.Message = "Are you sure want to delete [" + this.Data.Parent.Name + "]?"; this.ParentPage.ConfirmAction = () => { organizationsProvider.DeleteParentRelation(this.Data); }; } public PersonPage ParentPage => this.Parent.Parent as PersonPage; } public void RefreshTags() { this.TagsPage = Self.GET<TagsPage>("/people/partial/tagsPage/" + this.Data.GetObjectID()); } public void AddAddressElement(Address data) { AddressPage page = Self.GET<AddressPage>("/people/partials/address-relations/" + data.GetObjectID()); page.Deleted += (s, e) => { this.RefreshContactInfos(); }; this.Addresses.Add(page); } public void AddEmailAddressElement(EmailAddress data) { EmailAddressPage page = Self.GET<EmailAddressPage>("/people/partials/email-address-relations/" + data.GetObjectID()); page.Deleted += (s, a) => { this.RefreshContactInfos(); }; this.EmailAddresses.Add(page); } public void AddPhoneNumberElement(PhoneNumber data) { PhoneNumberPage page = Self.GET<PhoneNumberPage>("/people/partials/phone-number-relations/" + data.GetObjectID()); page.Deleted += (s, a) => { this.RefreshContactInfos(); }; this.PhoneNumbers.Add(page); } public void AddCustomContactInfoElement(CustomContactInfo data) { CustomContactInfoPage page = Self.GET<CustomContactInfoPage>("/people/partials/custom-contact-info-relations/" + data.GetObjectID()); page.Deleted += (s, a) => { this.RefreshContactInfos(); }; this.CustomContactInfos.Add(page); } public void SetConfirmMessage(string message) { this.Confirm.Message = message; } public void SetConfirmAction(Action action) { this.ConfirmAction = action; } [PersonPage_json.Confirm] partial class PersonConfirmPage : Json { public PersonPage ParentPage => this.Parent as PersonPage; void Cancel() { this.ParentPage.Confirm.Message = null; this.ParentPage.ConfirmAction = null; } void Handle(Input.Reject action) { Cancel(); } void Handle(Input.Ok action) { this.ParentPage.ConfirmAction?.Invoke(); Cancel(); } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.WindowsAzure.Commands.Tools.Vhd.Model; using Microsoft.WindowsAzure.Commands.Tools.Vhd.Model.Persistence; using System; using System.Collections.Generic; using System.IO; namespace Microsoft.WindowsAzure.Commands.Tools.Vhd { /// <summary> /// Provides a logical stream over a virtual hard disk (VHD). /// </summary> /// <remarks> /// This stream implementation provides a "view" over a VHD, such that the /// VHD appears to be an ordinary fixed VHD file, regardless of the true physical layout. /// This stream supports any combination of differencing, dynamic disks, and fixed disks. /// </remarks> public class VirtualDiskStream : SparseStream { private long position; private VhdFile vhdFile; private IBlockFactory blockFactory; private IndexRange footerRange; private IndexRange fileDataRange; private bool isDisposed; public VirtualDiskStream(string vhdPath) { this.vhdFile = new VhdFileFactory().Create(vhdPath); this.blockFactory = vhdFile.GetBlockFactory(); footerRange = this.blockFactory.GetFooterRange(); fileDataRange = IndexRange.FromLength(0, this.Length - footerRange.Length); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return false; } } public override void Flush() { } public override sealed long Length { get { return this.footerRange.EndIndex + 1; } } public override long Position { get { return this.position; } set { if (value < 0) throw new ArgumentException(); if (value >= this.Length) throw new EndOfStreamException(); this.position = value; } } /// <summary> /// Gets the extents of the stream that contain data. /// </summary> public override IEnumerable<StreamExtent> Extents { get { for (uint index = 0; index < blockFactory.BlockCount; index++) { var block = blockFactory.Create(index); if (!block.Empty) { yield return new StreamExtent { Owner = block.VhdUniqueId, StartOffset = block.LogicalRange.StartIndex, EndOffset = block.LogicalRange.EndIndex, Range = block.LogicalRange }; } } yield return new StreamExtent { Owner = vhdFile.Footer.UniqueId, StartOffset = this.footerRange.StartIndex, EndOffset = this.footerRange.EndIndex, Range = this.footerRange }; } } public DiskType DiskType { get { return this.vhdFile.DiskType; } } public DiskType RootDiskType { get { var diskType = this.vhdFile.DiskType; for (var parent = this.vhdFile.Parent; parent != null; parent = parent.Parent) { diskType = parent.DiskType; } return diskType; } } /// <summary> /// Reads the specified number of bytes from the current position. /// </summary> public override int Read(byte[] buffer, int offset, int count) { if (count <= 0) { return 0; } try { var rangeToRead = IndexRange.FromLength(this.position, count); int writtenCount = 0; if (fileDataRange.Intersection(rangeToRead) == null) { int readCountFromFooter; if (TryReadFromFooter(rangeToRead, buffer, offset, out readCountFromFooter)) { writtenCount += readCountFromFooter; } return writtenCount; } rangeToRead = fileDataRange.Intersection(rangeToRead); var startingBlock = ByteToBlock(rangeToRead.StartIndex); var endingBlock = ByteToBlock(rangeToRead.EndIndex); for (var blockIndex = startingBlock; blockIndex <= endingBlock; blockIndex++) { var currentBlock = blockFactory.Create(blockIndex); var rangeToReadInBlock = currentBlock.LogicalRange.Intersection(rangeToRead); var copyStartIndex = rangeToReadInBlock.StartIndex % blockFactory.GetBlockSize(); Buffer.BlockCopy(currentBlock.Data, (int)copyStartIndex, buffer, offset + writtenCount, (int)rangeToReadInBlock.Length); writtenCount += (int)rangeToReadInBlock.Length; } this.position += writtenCount; return writtenCount; } catch (Exception e) { throw new VhdParsingException("Invalid or Corrupted VHD file", e); } } public bool TryReadFromFooter(IndexRange rangeToRead, byte[] buffer, int offset, out int readCount) { readCount = 0; var rangeToReadFromFooter = this.footerRange.Intersection(rangeToRead); if (rangeToReadFromFooter != null) { var footerData = GenerateFooter(); var copyStartIndex = rangeToReadFromFooter.StartIndex - footerRange.StartIndex; Buffer.BlockCopy(footerData, (int)copyStartIndex, buffer, offset, (int)rangeToReadFromFooter.Length); this.position += (int)rangeToReadFromFooter.Length; readCount = (int)rangeToReadFromFooter.Length; return true; } return false; } private uint ByteToBlock(long position) { uint sectorsPerBlock = (uint)(this.blockFactory.GetBlockSize() / VhdConstants.VHD_SECTOR_LENGTH); return (uint)Math.Floor((position / VhdConstants.VHD_SECTOR_LENGTH) * 1.0m / sectorsPerBlock); } private byte[] GenerateFooter() { var footer = vhdFile.Footer.CreateCopy(); if (vhdFile.Footer.DiskType != DiskType.Fixed) { footer.HeaderOffset = VhdConstants.VHD_NO_DATA_LONG; footer.DiskType = DiskType.Fixed; footer.CreatorApplication = VhdFooterFactory.WindowsAzureCreatorApplicationName; } var serializer = new VhdFooterSerializer(footer); return serializer.ToByteArray(); } public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: this.Position = offset; break; case SeekOrigin.Current: this.Position += offset; break; case SeekOrigin.End: this.Position -= offset; break; default: throw new NotSupportedException(); } return this.Position; } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } protected override void Dispose(bool disposing) { if (!isDisposed) { if (disposing) { this.vhdFile.Dispose(); isDisposed = true; } } } } }
#if NET45PLUS using System.Collections.Immutable; using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(ImmutableInterlocked))] #else // 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.Threading; using Validation; namespace System.Collections.Immutable { /// <summary> /// Contains interlocked exchange mechanisms for immutable collections. /// </summary> public static class ImmutableInterlocked { /// <summary> /// Mutates a value in-place with optimistic locking transaction semantics /// via a specified transformation function. /// The transformation is retried as many times as necessary to win the optimistic locking race. /// </summary> /// <typeparam name="T">The type of data.</typeparam> /// <param name="location"> /// The variable or field to be changed, which may be accessed by multiple threads. /// </param> /// <param name="transformer"> /// A function that mutates the value. This function should be side-effect free, /// as it may run multiple times when races occur with other threads.</param> /// <returns> /// <c>true</c> if the location's value is changed by applying the result of the /// <paramref name="transformer"/> function; /// <c>false</c> if the location's value remained the same because the last /// invocation of <paramref name="transformer"/> returned the existing value. /// </returns> public static bool Update<T>(ref T location, Func<T, T> transformer) where T : class { Requires.NotNull(transformer, "transformer"); bool successful; T oldValue = Volatile.Read(ref location); do { T newValue = transformer(oldValue); if (ReferenceEquals(oldValue, newValue)) { // No change was actually required. return false; } T interlockedResult = Interlocked.CompareExchange(ref location, newValue, oldValue); successful = ReferenceEquals(oldValue, interlockedResult); oldValue = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); return true; } /// <summary> /// Mutates a value in-place with optimistic locking transaction semantics /// via a specified transformation function. /// The transformation is retried as many times as necessary to win the optimistic locking race. /// </summary> /// <typeparam name="T">The type of data.</typeparam> /// <typeparam name="TArg">The type of argument passed to the <paramref name="transformer"/>.</typeparam> /// <param name="location"> /// The variable or field to be changed, which may be accessed by multiple threads. /// </param> /// <param name="transformer"> /// A function that mutates the value. This function should be side-effect free, /// as it may run multiple times when races occur with other threads.</param> /// <param name="transformerArgument">The argument to pass to <paramref name="transformer"/>.</param> /// <returns> /// <c>true</c> if the location's value is changed by applying the result of the /// <paramref name="transformer"/> function; /// <c>false</c> if the location's value remained the same because the last /// invocation of <paramref name="transformer"/> returned the existing value. /// </returns> public static bool Update<T, TArg>(ref T location, Func<T, TArg, T> transformer, TArg transformerArgument) where T : class { Requires.NotNull(transformer, "transformer"); bool successful; T oldValue = Volatile.Read(ref location); do { T newValue = transformer(oldValue, transformerArgument); if (ReferenceEquals(oldValue, newValue)) { // No change was actually required. return false; } T interlockedResult = Interlocked.CompareExchange(ref location, newValue, oldValue); successful = ReferenceEquals(oldValue, interlockedResult); oldValue = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); return true; } #region ImmutableArray<T> members /// <summary> /// Assigns a field or variable containing an immutable array to the specified value and returns the previous value. /// </summary> /// <typeparam name="T">The type of element stored by the array.</typeparam> /// <param name="location">The field or local variable to change.</param> /// <param name="value">The new value to assign.</param> /// <returns>The prior value at the specified <paramref name="location"/>.</returns> public static ImmutableArray<T> InterlockedExchange<T>(ref ImmutableArray<T> location, ImmutableArray<T> value) { return new ImmutableArray<T>(Interlocked.Exchange(ref location.array, value.array)); } /// <summary> /// Assigns a field or variable containing an immutable array to the specified value /// if it is currently equal to another specified value. Returns the previous value. /// </summary> /// <typeparam name="T">The type of element stored by the array.</typeparam> /// <param name="location">The field or local variable to change.</param> /// <param name="value">The new value to assign.</param> /// <param name="comparand">The value to check equality for before assigning.</param> /// <returns>The prior value at the specified <paramref name="location"/>.</returns> public static ImmutableArray<T> InterlockedCompareExchange<T>(ref ImmutableArray<T> location, ImmutableArray<T> value, ImmutableArray<T> comparand) { return new ImmutableArray<T>(Interlocked.CompareExchange(ref location.array, value.array, comparand.array)); } /// <summary> /// Assigns a field or variable containing an immutable array to the specified value /// if it is has not yet been initialized. /// </summary> /// <typeparam name="T">The type of element stored by the array.</typeparam> /// <param name="location">The field or local variable to change.</param> /// <param name="value">The new value to assign.</param> /// <returns>True if the field was assigned the specified value; <c>false</c> if it was previously initialized.</returns> public static bool InterlockedInitialize<T>(ref ImmutableArray<T> location, ImmutableArray<T> value) { return InterlockedCompareExchange(ref location, value, default(ImmutableArray<T>)).IsDefault; } #endregion #region ImmutableDictionary<TKey, TValue> members /// <summary> /// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist. /// </summary> /// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam> /// <typeparam name="TArg">The type of argument supplied to the value factory.</typeparam> /// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param> /// <param name="key">The key for the value to retrieve or add.</param> /// <param name="valueFactory">The function to execute to obtain the value to insert into the dictionary if the key is not found.</param> /// <param name="factoryArgument">The argument to pass to the value factory.</param> /// <returns>The value obtained from the dictionary or <paramref name="valueFactory"/> if it was not present.</returns> public static TValue GetOrAdd<TKey, TValue, TArg>(ref ImmutableDictionary<TKey, TValue> location, TKey key, Func<TKey, TArg, TValue> valueFactory, TArg factoryArgument) { Requires.NotNull(valueFactory, "valueFactory"); var map = Volatile.Read(ref location); Requires.NotNull(map, "location"); TValue value; if (map.TryGetValue(key, out value)) { return value; } value = valueFactory(key, factoryArgument); return GetOrAdd(ref location, key, value); } /// <summary> /// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist. /// </summary> /// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam> /// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param> /// <param name="key">The key for the value to retrieve or add.</param> /// <param name="valueFactory"> /// The function to execute to obtain the value to insert into the dictionary if the key is not found. /// This delegate will not be invoked more than once. /// </param> /// <returns>The value obtained from the dictionary or <paramref name="valueFactory"/> if it was not present.</returns> public static TValue GetOrAdd<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, Func<TKey, TValue> valueFactory) { Requires.NotNull(valueFactory, "valueFactory"); var map = Volatile.Read(ref location); Requires.NotNull(map, "location"); TValue value; if (map.TryGetValue(key, out value)) { return value; } value = valueFactory(key); return GetOrAdd(ref location, key, value); } /// <summary> /// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist. /// </summary> /// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam> /// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param> /// <param name="key">The key for the value to retrieve or add.</param> /// <param name="value">The value to add to the dictionary if one is not already present.</param> /// <returns>The value obtained from the dictionary or <paramref name="value"/> if it was not present.</returns> public static TValue GetOrAdd<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue value) { var priorCollection = Volatile.Read(ref location); bool successful; do { Requires.NotNull(priorCollection, "location"); TValue oldValue; if (priorCollection.TryGetValue(key, out oldValue)) { return oldValue; } var updatedCollection = priorCollection.Add(key, value); var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection); successful = Object.ReferenceEquals(priorCollection, interlockedResult); priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); // We won the race-condition and have updated the collection. // Return the value that is in the collection (as of the Interlocked operation). return value; } /// <summary> /// Obtains the value from a dictionary after having added it or updated an existing entry. /// </summary> /// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam> /// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param> /// <param name="key">The key for the value to add or update.</param> /// <param name="addValueFactory">The function that receives the key and returns a new value to add to the dictionary when no value previously exists.</param> /// <param name="updateValueFactory">The function that receives the key and prior value and returns the new value with which to update the dictionary.</param> /// <returns>The added or updated value.</returns> public static TValue AddOrUpdate<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory) { Requires.NotNull(addValueFactory, "addValueFactory"); Requires.NotNull(updateValueFactory, "updateValueFactory"); TValue newValue; var priorCollection = Volatile.Read(ref location); bool successful; do { Requires.NotNull(priorCollection, "location"); TValue oldValue; if (priorCollection.TryGetValue(key, out oldValue)) { newValue = updateValueFactory(key, oldValue); } else { newValue = addValueFactory(key); } var updatedCollection = priorCollection.SetItem(key, newValue); var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection); successful = Object.ReferenceEquals(priorCollection, interlockedResult); priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); // We won the race-condition and have updated the collection. // Return the value that is in the collection (as of the Interlocked operation). return newValue; } /// <summary> /// Obtains the value from a dictionary after having added it or updated an existing entry. /// </summary> /// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam> /// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param> /// <param name="key">The key for the value to add or update.</param> /// <param name="addValue">The value to use if no previous value exists.</param> /// <param name="updateValueFactory">The function that receives the key and prior value and returns the new value with which to update the dictionary.</param> /// <returns>The added or updated value.</returns> public static TValue AddOrUpdate<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory) { Requires.NotNull(updateValueFactory, "updateValueFactory"); TValue newValue; var priorCollection = Volatile.Read(ref location); bool successful; do { Requires.NotNull(priorCollection, "location"); TValue oldValue; if (priorCollection.TryGetValue(key, out oldValue)) { newValue = updateValueFactory(key, oldValue); } else { newValue = addValue; } var updatedCollection = priorCollection.SetItem(key, newValue); var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection); successful = Object.ReferenceEquals(priorCollection, interlockedResult); priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); // We won the race-condition and have updated the collection. // Return the value that is in the collection (as of the Interlocked operation). return newValue; } /// <summary> /// Adds the specified key and value to the dictionary if no colliding key already exists in the dictionary. /// </summary> /// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam> /// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param> /// <param name="key">The key to add, if is not already defined in the dictionary.</param> /// <param name="value">The value to add.</param> /// <returns><c>true</c> if the key was not previously set in the dictionary and the value was set; <c>false</c> otherwise.</returns> public static bool TryAdd<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue value) { var priorCollection = Volatile.Read(ref location); bool successful; do { Requires.NotNull(priorCollection, "location"); if (priorCollection.ContainsKey(key)) { return false; } var updatedCollection = priorCollection.Add(key, value); var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection); successful = Object.ReferenceEquals(priorCollection, interlockedResult); priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); return true; } /// <summary> /// Sets the specified key to the given value if the key already is set to a specific value. /// </summary> /// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam> /// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param> /// <param name="key">The key to update.</param> /// <param name="newValue">The new value to set.</param> /// <param name="comparisonValue">The value that must already be set in the dictionary in order for the update to succeed.</param> /// <returns><c>true</c> if the key and comparison value were present in the dictionary and the update was made; <c>false</c> otherwise.</returns> public static bool TryUpdate<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, TValue newValue, TValue comparisonValue) { var valueComparer = EqualityComparer<TValue>.Default; var priorCollection = Volatile.Read(ref location); bool successful; do { Requires.NotNull(priorCollection, "location"); TValue priorValue; if (!priorCollection.TryGetValue(key, out priorValue) || !valueComparer.Equals(priorValue, comparisonValue)) { // The key isn't in the dictionary, or its current value doesn't match what the caller expected. return false; } var updatedCollection = priorCollection.SetItem(key, newValue); var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection); successful = Object.ReferenceEquals(priorCollection, interlockedResult); priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); return true; } /// <summary> /// Removes an entry from the dictionary with the specified key if it is defined and returns its value. /// </summary> /// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam> /// <param name="location">The variable or field to atomically update if the specified <paramref name="key"/> is not in the dictionary.</param> /// <param name="key">The key to remove.</param> /// <param name="value">Receives the value from the pre-existing entry, if one exists.</param> /// <returns><c>true</c> if the key was found and removed; <c>false</c> otherwise.</returns> public static bool TryRemove<TKey, TValue>(ref ImmutableDictionary<TKey, TValue> location, TKey key, out TValue value) { var priorCollection = Volatile.Read(ref location); bool successful; do { Requires.NotNull(priorCollection, "location"); if (!priorCollection.TryGetValue(key, out value)) { return false; } var updatedCollection = priorCollection.Remove(key); var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection); successful = Object.ReferenceEquals(priorCollection, interlockedResult); priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); return true; } #endregion #region ImmutableStack<T> members /// <summary> /// Pushes a new element onto a stack. /// </summary> /// <typeparam name="T">The type of elements stored in the stack.</typeparam> /// <param name="location">The variable or field to atomically update.</param> /// <param name="value">The value popped from the stack, if it was non-empty.</param> /// <returns><c>true</c> if an element was removed from the stack; <c>false</c> otherwise.</returns> public static bool TryPop<T>(ref ImmutableStack<T> location, out T value) { var priorCollection = Volatile.Read(ref location); bool successful; do { Requires.NotNull(priorCollection, "location"); if (priorCollection.IsEmpty) { value = default(T); return false; } var updatedCollection = priorCollection.Pop(out value); var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection); successful = Object.ReferenceEquals(priorCollection, interlockedResult); priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); return true; } /// <summary> /// Pushes a new element onto a stack. /// </summary> /// <typeparam name="T">The type of elements stored in the stack.</typeparam> /// <param name="location">The variable or field to atomically update.</param> /// <param name="value">The value to push.</param> public static void Push<T>(ref ImmutableStack<T> location, T value) { var priorCollection = Volatile.Read(ref location); bool successful; do { Requires.NotNull(priorCollection, "location"); var updatedCollection = priorCollection.Push(value); var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection); successful = Object.ReferenceEquals(priorCollection, interlockedResult); priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); } #endregion #region ImmutableQueue<T> members /// <summary> /// Atomically removes the element at the head of a queue and returns it to the caller, if the queue is not empty. /// </summary> /// <typeparam name="T">The type of element stored in the queue.</typeparam> /// <param name="location">The variable or field to atomically update.</param> /// <param name="value">Receives the value from the head of the queue, if the queue is non-empty.</param> /// <returns><c>true</c> if the queue was not empty and the head element was removed; <c>false</c> otherwise.</returns> public static bool TryDequeue<T>(ref ImmutableQueue<T> location, out T value) { var priorCollection = Volatile.Read(ref location); bool successful; do { Requires.NotNull(priorCollection, "location"); if (priorCollection.IsEmpty) { value = default(T); return false; } var updatedCollection = priorCollection.Dequeue(out value); var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection); successful = Object.ReferenceEquals(priorCollection, interlockedResult); priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); return true; } /// <summary> /// Atomically enqueues an element to the tail of a queue. /// </summary> /// <typeparam name="T">The type of element stored in the queue.</typeparam> /// <param name="location">The variable or field to atomically update.</param> /// <param name="value">The value to enqueue.</param> public static void Enqueue<T>(ref ImmutableQueue<T> location, T value) { var priorCollection = Volatile.Read(ref location); bool successful; do { Requires.NotNull(priorCollection, "location"); var updatedCollection = priorCollection.Enqueue(value); var interlockedResult = Interlocked.CompareExchange(ref location, updatedCollection, priorCollection); successful = Object.ReferenceEquals(priorCollection, interlockedResult); priorCollection = interlockedResult; // we already have a volatile read that we can reuse for the next loop } while (!successful); } #endregion } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Xml; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnostics.Windows; using BenchmarkDotNet.Jobs; using Microsoft.CodeAnalysis.CSharp.Syntax; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web.PublishedCache.XmlPublishedCache; namespace Umbraco.Tests.Benchmarks { [Config(typeof(Config))] public class XmlPublishedContentInitBenchmarks { private class Config : ManualConfig { public Config() { Add(new MemoryDiagnoser()); //The 'quick and dirty' settings, so it runs a little quicker // see benchmarkdotnet FAQ Add(Job.Default .WithLaunchCount(1) // benchmark process will be launched only once .WithIterationTime(100) // 100ms per iteration .WithWarmupCount(3) // 3 warmup iteration .WithTargetCount(3)); // 3 target iteration } } public XmlPublishedContentInitBenchmarks() { _xml10 = Build(10); _xml100 = Build(100); _xml1000 = Build(1000); _xml10000 = Build(10000); } private readonly string[] _intAttributes = { "id", "parentID", "nodeType", "level", "writerID", "creatorID", "template", "sortOrder", "isDoc", "isDraft" }; private readonly string[] _strAttributes = { "nodeName", "urlName", "writerName", "creatorName", "path" }; private readonly string[] _dateAttributes = { "createDate", "updateDate" }; private readonly string[] _guidAttributes = { "key", "version" }; private XmlDocument Build(int children) { var xml = new XmlDocument(); var root = Build(xml, "Home", 10); for (int i = 0; i < children; i++) { var child = Build(xml, "child" + i, 10); root.AppendChild(child); } xml.AppendChild(root); return xml; } private XmlElement Build(XmlDocument xml, string name, int propertyCount) { var random = new Random(); var content = xml.CreateElement(name); foreach (var p in _intAttributes) { var a = xml.CreateAttribute(p); a.Value = random.Next(1, 9).ToInvariantString(); content.Attributes.Append(a); } foreach (var p in _strAttributes) { var a = xml.CreateAttribute(p); a.Value = Guid.NewGuid().ToString(); content.Attributes.Append(a); } foreach (var p in _guidAttributes) { var a = xml.CreateAttribute(p); a.Value = Guid.NewGuid().ToString(); content.Attributes.Append(a); } foreach (var p in _dateAttributes) { var a = xml.CreateAttribute(p); a.Value = DateTime.Now.ToString("o"); content.Attributes.Append(a); } for (int i = 0; i < propertyCount; i++) { var prop = xml.CreateElement("prop" + i); var cdata = xml.CreateCDataSection(string.Join("", Enumerable.Range(0, 10).Select(x => Guid.NewGuid().ToString()))); prop.AppendChild(cdata); content.AppendChild(prop); } return content; } private readonly XmlDocument _xml10; private readonly XmlDocument _xml100; private readonly XmlDocument _xml1000; private readonly XmlDocument _xml10000; //out props int id, nodeType, level, writerId, creatorId, template, sortOrder; Guid key, version; string name, urlName, writerName, creatorName, docTypeAlias, path; bool isDraft; DateTime createDate, updateDate; PublishedContentType publishedContentType; Dictionary<string, IPublishedProperty> properties; [Benchmark(Baseline = true, OperationsPerInvoke = 10)] public void Original_10_Children() { OriginalInitializeNode(_xml10.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties); } [Benchmark(OperationsPerInvoke = 10)] public void Original_100_Children() { OriginalInitializeNode(_xml100.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties); } [Benchmark(OperationsPerInvoke = 10)] public void Original_1000_Children() { OriginalInitializeNode(_xml1000.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties); } [Benchmark(OperationsPerInvoke = 10)] public void Original_10000_Children() { OriginalInitializeNode(_xml10000.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties); } [Benchmark(OperationsPerInvoke = 10)] public void Enhanced_10_Children() { XmlPublishedContent.InitializeNode(_xml10.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties, GetPublishedContentType); } [Benchmark(OperationsPerInvoke = 10)] public void Enhanced_100_Children() { XmlPublishedContent.InitializeNode(_xml100.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties, GetPublishedContentType); } [Benchmark(OperationsPerInvoke = 10)] public void Enhanced_1000_Children() { XmlPublishedContent.InitializeNode(_xml1000.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties, GetPublishedContentType); } [Benchmark(OperationsPerInvoke = 10)] public void Enhanced_10000_Children() { XmlPublishedContent.InitializeNode(_xml10000.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties, GetPublishedContentType); } internal static void OriginalInitializeNode(XmlNode xmlNode, bool legacy, bool isPreviewing, out int id, out Guid key, out int template, out int sortOrder, out string name, out string writerName, out string urlName, out string creatorName, out int creatorId, out int writerId, out string docTypeAlias, out int docTypeId, out string path, out Guid version, out DateTime createDate, out DateTime updateDate, out int level, out bool isDraft, out PublishedContentType contentType, out Dictionary<string, IPublishedProperty> properties) { //initialize the out params with defaults: writerName = null; docTypeAlias = null; id = template = sortOrder = template = creatorId = writerId = docTypeId = level = default(int); key = version = default(Guid); name = writerName = urlName = creatorName = docTypeAlias = path = null; createDate = updateDate = default(DateTime); isDraft = false; contentType = null; properties = null; //return if this is null if (xmlNode == null) { return; } if (xmlNode.Attributes != null) { id = int.Parse(xmlNode.Attributes.GetNamedItem("id").Value); if (xmlNode.Attributes.GetNamedItem("key") != null) // because, migration key = Guid.Parse(xmlNode.Attributes.GetNamedItem("key").Value); if (xmlNode.Attributes.GetNamedItem("template") != null) template = int.Parse(xmlNode.Attributes.GetNamedItem("template").Value); if (xmlNode.Attributes.GetNamedItem("sortOrder") != null) sortOrder = int.Parse(xmlNode.Attributes.GetNamedItem("sortOrder").Value); if (xmlNode.Attributes.GetNamedItem("nodeName") != null) name = xmlNode.Attributes.GetNamedItem("nodeName").Value; if (xmlNode.Attributes.GetNamedItem("writerName") != null) writerName = xmlNode.Attributes.GetNamedItem("writerName").Value; if (xmlNode.Attributes.GetNamedItem("urlName") != null) urlName = xmlNode.Attributes.GetNamedItem("urlName").Value; // Creatorname is new in 2.1, so published xml might not have it! try { creatorName = xmlNode.Attributes.GetNamedItem("creatorName").Value; } catch { creatorName = writerName; } //Added the actual userID, as a user cannot be looked up via full name only... if (xmlNode.Attributes.GetNamedItem("creatorID") != null) creatorId = int.Parse(xmlNode.Attributes.GetNamedItem("creatorID").Value); if (xmlNode.Attributes.GetNamedItem("writerID") != null) writerId = int.Parse(xmlNode.Attributes.GetNamedItem("writerID").Value); if (legacy) { if (xmlNode.Attributes.GetNamedItem("nodeTypeAlias") != null) docTypeAlias = xmlNode.Attributes.GetNamedItem("nodeTypeAlias").Value; } else { docTypeAlias = xmlNode.Name; } if (xmlNode.Attributes.GetNamedItem("nodeType") != null) docTypeId = int.Parse(xmlNode.Attributes.GetNamedItem("nodeType").Value); if (xmlNode.Attributes.GetNamedItem("path") != null) path = xmlNode.Attributes.GetNamedItem("path").Value; if (xmlNode.Attributes.GetNamedItem("version") != null) version = new Guid(xmlNode.Attributes.GetNamedItem("version").Value); if (xmlNode.Attributes.GetNamedItem("createDate") != null) createDate = DateTime.Parse(xmlNode.Attributes.GetNamedItem("createDate").Value); if (xmlNode.Attributes.GetNamedItem("updateDate") != null) updateDate = DateTime.Parse(xmlNode.Attributes.GetNamedItem("updateDate").Value); if (xmlNode.Attributes.GetNamedItem("level") != null) level = int.Parse(xmlNode.Attributes.GetNamedItem("level").Value); isDraft = (xmlNode.Attributes.GetNamedItem("isDraft") != null); } // load data var dataXPath = legacy ? "data" : "* [not(@isDoc)]"; var nodes = xmlNode.SelectNodes(dataXPath); contentType = GetPublishedContentType(PublishedItemType.Content, docTypeAlias); var propertyNodes = new Dictionary<string, XmlNode>(); if (nodes != null) foreach (XmlNode n in nodes) { var attrs = n.Attributes; if (attrs == null) continue; var alias = legacy ? attrs.GetNamedItem("alias").Value : n.Name; propertyNodes[alias.ToLowerInvariant()] = n; } properties = contentType.PropertyTypes.Select(p => { XmlNode n; return propertyNodes.TryGetValue(p.PropertyTypeAlias.ToLowerInvariant(), out n) ? new XmlPublishedProperty(p, isPreviewing, n) : new XmlPublishedProperty(p, isPreviewing); }).Cast<IPublishedProperty>().ToDictionary( x => x.PropertyTypeAlias, x => x, StringComparer.OrdinalIgnoreCase); } private static PublishedContentType GetPublishedContentType(PublishedItemType type, string alias) { return new PublishedContentType(alias, new string[] {}, new List<PublishedPropertyType>(Enumerable.Range(0, 10).Select(x => new PublishedPropertyType("prop" + x, 0, "test", initConverters:false)))); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using Windows.UI.ApplicationSettings; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using SDKTemplate; using Windows.Security.Credentials; using Windows.Security.Authentication.Web.Core; using System; using Windows.Storage; using System.Threading.Tasks; using Windows.UI.Popups; using Windows.Security.Authentication.Web.Provider; namespace Accounts { public sealed partial class SingleMicrosoftAccountScenario : Page { private MainPage rootPage; // To obtain Microsoft account tokens, you must register your application online // Then, you must associate the app with the store. const string MicrosoftAccountProviderId = "https://login.microsoft.com"; const string ConsumerAuthority = "consumers"; const string AccountScopeRequested = "service::wl.basic::DELEGATION"; const string AccountClientId = "none"; const string StoredAccountKey = "accountid"; public SingleMicrosoftAccountScenario() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; // The AccountCommandsRequested event triggers before the Accounts settings pane is displayed AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += OnAccountCommandsRequested; IdentityChecker.SampleIdentityConfigurationCorrect(NotRegisteredWarning); } protected override void OnNavigatedFrom(NavigationEventArgs e) { AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested; } private void Button_ShowAccountSettings(object sender, RoutedEventArgs e) { ((Button)sender).IsEnabled = false; rootPage.NotifyUser("Launching AccountSettingsPane", NotifyType.StatusMessage); AccountsSettingsPane.Show(); ((Button)sender).IsEnabled = true; } private async void Button_Reset(object sender, RoutedEventArgs e) { ((Button)sender).IsEnabled = false; rootPage.NotifyUser("Resetting...", NotifyType.StatusMessage); await LogoffAndRemoveAccount(); ((Button)sender).IsEnabled = true; } // This event handler is called when the Account settings pane is to be launched. private async void OnAccountCommandsRequested( AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs e) { // In order to make async calls within this callback, the deferral object is needed AccountsSettingsPaneEventDeferral deferral = e.GetDeferral(); // This scenario only lets the user have one account at a time. // If there already is an account, we do not include a provider in the list // This will prevent the add account button from showing up. bool isPresent = ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountKey); if (isPresent) { await AddWebAccount(e); } else { await AddWebAccountProvider(e); } AddLinksAndDescription(e); deferral.Complete(); } private async Task AddWebAccountProvider(AccountsSettingsPaneCommandsRequestedEventArgs e) { // FindAccountProviderAsync returns the WebAccountProvider of an installed plugin // The Provider and Authority specifies the specific plugin // This scenario only supports Microsoft accounts. // The Microsoft account provider is always present in Windows 10 devices, as is the Azure AD plugin. // If a non-installed plugin or incorect identity is specified, FindAccountProviderAsync will return null WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority); WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked); e.WebAccountProviderCommands.Add(providerCommand); } private async Task AddWebAccount(AccountsSettingsPaneCommandsRequestedEventArgs e) { WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority); String accountID = (String)ApplicationData.Current.LocalSettings.Values[StoredAccountKey]; WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID); if (account == null) { // The account has most likely been deleted in Windows settings // Unless there would be significant data loss, you should just delete the account // If there would be significant data loss, prompt the user to either re-add the account, or to remove it ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); } WebAccountCommand command = new WebAccountCommand(account, WebAccountInvoked, SupportedWebAccountActions.Remove); e.WebAccountCommands.Add(command); } private void AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs e) { e.HeaderText = "Describe what adding an account to your application will do for the user"; // You can add links such as privacy policy, help, general account settings e.Commands.Add(new SettingsCommand("privacypolicy", "Privacy policy", PrivacyPolicyInvoked)); e.Commands.Add(new SettingsCommand("otherlink", "Other link", OtherLinkInvoked)); } private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command) { // ClientID is ignored by MSA await RequestTokenAndSaveAccount(command.WebAccountProvider, AccountScopeRequested, AccountClientId); } private async void WebAccountInvoked(WebAccountCommand command, WebAccountInvokedArgs args) { if (args.Action == WebAccountAction.Remove) { rootPage.NotifyUser("Removing account", NotifyType.StatusMessage); await LogoffAndRemoveAccount(); } } private void PrivacyPolicyInvoked(IUICommand command) { rootPage.NotifyUser("Privacy policy clicked by user", NotifyType.StatusMessage); } private void OtherLinkInvoked(IUICommand command) { rootPage.NotifyUser("Other link pressed by user", NotifyType.StatusMessage); } private async Task RequestTokenAndSaveAccount(WebAccountProvider Provider, String Scope, String ClientID) { try { WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID); rootPage.NotifyUser("Requesting Web Token", NotifyType.StatusMessage); // If the user selected a specific account, RequestTokenAsync will return a token for that account. // The user may be prompted for credentials or to authorize using that account with your app // If the user selected a provider, the user will be prompted for credentials to login to a new account WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); // If a token was successfully returned, then store the WebAccount Id into local app data // This Id can be used to retrieve the account whenever needed. To later get a token with that account // First retrieve the account with FindAccountAsync, and include that webaccount // as a parameter to RequestTokenAsync or RequestTokenSilentlyAsync if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); ApplicationData.Current.LocalSettings.Values[StoredAccountKey] = webTokenRequestResult.ResponseData[0].WebAccount.Id; } OutputTokenResult(webTokenRequestResult); } catch (Exception ex) { rootPage.NotifyUser("Web Token request failed: " + ex.Message, NotifyType.ErrorMessage); } } private void OutputTokenResult(WebTokenRequestResult result) { if (result.ResponseStatus == WebTokenRequestStatus.Success) { rootPage.NotifyUser("Web Token request successful for user: " + result.ResponseData[0].WebAccount.UserName, NotifyType.StatusMessage); SignInButton.Content = "Account"; } else { rootPage.NotifyUser("Web Token request error: " + result.ResponseError, NotifyType.StatusMessage); } } private async Task LogoffAndRemoveAccount() { if (ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountKey)) { WebAccountProvider providertoDelete = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority); WebAccount accountToDelete = await WebAuthenticationCoreManager.FindAccountAsync(providertoDelete, (string)ApplicationData.Current.LocalSettings.Values[StoredAccountKey]); if(accountToDelete != null) { await accountToDelete.SignOutAsync(); } ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); SignInButton.Content = "Sign in"; } } } }
// 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.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ExpressRouteCircuitsOperations. /// </summary> public static partial class ExpressRouteCircuitsOperationsExtensions { /// <summary> /// Deletes the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> public static void Delete(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName) { operations.DeleteAsync(resourceGroupName, circuitName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets information about the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of express route circuit. /// </param> public static ExpressRouteCircuit Get(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName) { return operations.GetAsync(resourceGroupName, circuitName).GetAwaiter().GetResult(); } /// <summary> /// Gets information about the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of express route circuit. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuit> GetAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates an express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update express route circuit /// operation. /// </param> public static ExpressRouteCircuit CreateOrUpdate(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, ExpressRouteCircuit parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, circuitName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update express route circuit /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuit> CreateOrUpdateAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the currently advertised ARP table associated with the express route /// circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> public static ExpressRouteCircuitsArpTableListResult ListArpTable(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath) { return operations.ListArpTableAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult(); } /// <summary> /// Gets the currently advertised ARP table associated with the express route /// circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitsArpTableListResult> ListArpTableAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListArpTableWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the currently advertised routes table associated with the express /// route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> public static ExpressRouteCircuitsRoutesTableListResult ListRoutesTable(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath) { return operations.ListRoutesTableAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult(); } /// <summary> /// Gets the currently advertised routes table associated with the express /// route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitsRoutesTableListResult> ListRoutesTableAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListRoutesTableWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the currently advertised routes table summary associated with the /// express route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> public static ExpressRouteCircuitsRoutesTableSummaryListResult ListRoutesTableSummary(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath) { return operations.ListRoutesTableSummaryAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult(); } /// <summary> /// Gets the currently advertised routes table summary associated with the /// express route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitsRoutesTableSummaryListResult> ListRoutesTableSummaryAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListRoutesTableSummaryWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the stats from an express route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> public static ExpressRouteCircuitStats GetStats(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName) { return operations.GetStatsAsync(resourceGroupName, circuitName).GetAwaiter().GetResult(); } /// <summary> /// Gets all the stats from an express route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitStats> GetStatsAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetStatsWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all stats from an express route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> public static ExpressRouteCircuitStats GetPeeringStats(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName) { return operations.GetPeeringStatsAsync(resourceGroupName, circuitName, peeringName).GetAwaiter().GetResult(); } /// <summary> /// Gets all stats from an express route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitStats> GetPeeringStatsAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPeeringStatsWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the express route circuits in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<ExpressRouteCircuit> List(this IExpressRouteCircuitsOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets all the express route circuits in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ExpressRouteCircuit>> ListAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the express route circuits in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<ExpressRouteCircuit> ListAll(this IExpressRouteCircuitsOperations operations) { return operations.ListAllAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all the express route circuits in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ExpressRouteCircuit>> ListAllAsync(this IExpressRouteCircuitsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> public static void BeginDelete(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName) { operations.BeginDeleteAsync(resourceGroupName, circuitName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates an express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update express route circuit /// operation. /// </param> public static ExpressRouteCircuit BeginCreateOrUpdate(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, ExpressRouteCircuit parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, circuitName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update express route circuit /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuit> BeginCreateOrUpdateAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the currently advertised ARP table associated with the express route /// circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> public static ExpressRouteCircuitsArpTableListResult BeginListArpTable(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath) { return operations.BeginListArpTableAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult(); } /// <summary> /// Gets the currently advertised ARP table associated with the express route /// circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitsArpTableListResult> BeginListArpTableAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginListArpTableWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the currently advertised routes table associated with the express /// route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> public static ExpressRouteCircuitsRoutesTableListResult BeginListRoutesTable(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath) { return operations.BeginListRoutesTableAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult(); } /// <summary> /// Gets the currently advertised routes table associated with the express /// route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitsRoutesTableListResult> BeginListRoutesTableAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginListRoutesTableWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the currently advertised routes table summary associated with the /// express route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> public static ExpressRouteCircuitsRoutesTableSummaryListResult BeginListRoutesTableSummary(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath) { return operations.BeginListRoutesTableSummaryAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult(); } /// <summary> /// Gets the currently advertised routes table summary associated with the /// express route circuit in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitsRoutesTableSummaryListResult> BeginListRoutesTableSummaryAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginListRoutesTableSummaryWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the express route circuits in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ExpressRouteCircuit> ListNext(this IExpressRouteCircuitsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the express route circuits in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ExpressRouteCircuit>> ListNextAsync(this IExpressRouteCircuitsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the express route circuits in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ExpressRouteCircuit> ListAllNext(this IExpressRouteCircuitsOperations operations, string nextPageLink) { return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the express route circuits in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ExpressRouteCircuit>> ListAllNextAsync(this IExpressRouteCircuitsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// // server.cs: Web Server that uses ASP.NET hosting // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (C) 2002,2003 Ximian, Inc (http://www.ximian.com) // (C) Copyright 2004-2005 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using Mono.Security.Authenticode; using MSX = Mono.Security.X509; using Mono.Security.X509.Extensions; namespace Mono.WebServer.XSP { public class SecurityConfiguration { bool valid; RSA key; X509Certificate x509; string password; public SecurityConfiguration () { } // properties public bool AcceptClientCertificates { get; set; } public string CertificateFile { get; set; } public bool Enabled { get; set; } public bool RequireClientCertificates { get; set; } public string Password { get { throw new CryptographicException ("Password is write-only."); } set { password = value; } } public string Pkcs12File { get; set; } public RSA KeyPair { get { if (!valid) CheckSecurityContextValidity (); return key; } } public string PvkFile { get; set; } public X509Certificate ServerCertificate { get { if (!valid) CheckSecurityContextValidity (); return x509; } } // methods public void CheckSecurityContextValidity () { if (Enabled) { // give priority to pkcs12 (for conflicting options) LoadPkcs12File (Pkcs12File, password); LoadCertificate (CertificateFile); LoadPrivateKeyFile (PvkFile, password); } valid = true; } public override string ToString () { if (!Enabled) return "(non-secure)"; var sb = new StringBuilder ("("); if (RequireClientCertificates) sb.Append (" with mandatory client certificates"); sb.Append (")"); return sb.ToString (); } // private stuff void LoadCertificate (string filename) { if ((filename == null) || (x509 != null)) return; try { x509 = X509Certificate.CreateFromCertFile (filename); } catch (Exception e) { string message = String.Format ("Unable to load X.509 certicate file '{0}'.", filename); throw new CryptographicException (message, e); } } void LoadPrivateKeyFile (string filename, string password) { if ((filename == null) || (key != null)) return; try { key = password == null ? PrivateKey.CreateFromFile (filename).RSA : PrivateKey.CreateFromFile (filename, password).RSA; } catch (CryptographicException ce) { string message = String.Format ("Invalid private key password or private key file '{0}' is corrupt.", filename); throw new CryptographicException (message, ce); } catch (Exception e) { string message = String.Format ("Unable to load private key '{0}'.", filename); throw new CryptographicException (message, e); } } void LoadPkcs12File (string filename, string password) { if ((filename == null) || (key != null)) return; try { MSX.PKCS12 pfx = password == null ? MSX.PKCS12.LoadFromFile (filename) : MSX.PKCS12.LoadFromFile (filename, password); // a PKCS12 file may contain many certificates and keys so we must find // the best one (i.e. not the first one) // test for only one certificate / keypair if (Simple (pfx)) return; // next, we look for a certificate with the server authentication EKU (oid // 1.3.6.1.5.5.7.3.1) and, if found, try to find a key associated with it if (ExtendedKeyUsage (pfx)) return; // next, we look for a certificate with the KU matching the use of a private // key matching SSL usage and, if found, try to find a key associated with it if (KeyUsage (pfx)) return; // next, we look for the old netscape extension if (NetscapeCertType (pfx)) return; // finally we iterate all keys (not certificates) to find a certificate with the // same public key if (BruteForce (pfx)) return; // we don't merit to use SSL ;-) throw new Exception ("Couldn't find an appropriate certificate and private key to use for SSL."); } catch (CryptographicException ce) { string message = String.Format ("Invalid private key password or private key file '{0}' is corrupt.", filename); throw new CryptographicException (message, ce); } catch (Exception e) { string message = String.Format ("Unable to load private key '{0}'.", filename); throw new CryptographicException (message, e); } } bool Simple (MSX.PKCS12 pfx) { int ncerts = pfx.Certificates.Count; if (ncerts == 0) throw new Exception ("No certificates are present in the PKCS#12 file."); int nkeys = pfx.Keys.Count; if (nkeys == 0) throw new Exception ("No keypair is present in the PKCS#12 file."); if (ncerts == 1) { MSX.X509Certificate cert = pfx.Certificates [0]; // only one certificate, find matching key if (nkeys == 1) { // only one key key = (pfx.Keys [0] as RSA); } else { // many keys (strange case) key = GetKeyMatchingCertificate (pfx, cert); } // complete ? if ((key != null) && (cert != null)) { x509 = new X509Certificate (cert.RawData); return true; } } return false; } bool ExtendedKeyUsage (MSX.PKCS12 pfx) { foreach (MSX.X509Certificate cert in pfx.Certificates) { MSX.X509Extension xtn = cert.Extensions ["2.5.29.37"]; if (xtn == null) continue; var eku = new ExtendedKeyUsageExtension (xtn); if (!eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.1")) continue; key = GetKeyMatchingCertificate (pfx, cert); if (key == null) continue; x509 = new X509Certificate (cert.RawData); break; } // complete ? return ((x509 != null) && (key != null)); } bool KeyUsage (MSX.PKCS12 pfx) { foreach (MSX.X509Certificate cert in pfx.Certificates) { MSX.X509Extension xtn = cert.Extensions ["2.5.29.15"]; if (xtn == null) continue; var ku = new KeyUsageExtension (xtn); if (!ku.Support (KeyUsages.digitalSignature) && !ku.Support (KeyUsages.keyEncipherment)) continue; key = GetKeyMatchingCertificate (pfx, cert); if (key == null) continue; x509 = new X509Certificate (cert.RawData); break; } // complete ? return ((x509 != null) && (key != null)); } bool NetscapeCertType (MSX.PKCS12 pfx) { foreach (MSX.X509Certificate cert in pfx.Certificates) { MSX.X509Extension xtn = cert.Extensions ["2.16.840.1.113730.1.1"]; if (xtn == null) continue; var ct = new NetscapeCertTypeExtension (xtn); if (!ct.Support (NetscapeCertTypeExtension.CertTypes.SslServer)) continue; key = GetKeyMatchingCertificate (pfx, cert); if (key == null) continue; x509 = new X509Certificate (cert.RawData); break; } // complete ? return ((x509 != null) && (key != null)); } bool BruteForce (MSX.PKCS12 pfx) { foreach (object o in pfx.Keys) { key = (o as RSA); if (key == null) continue; string s = key.ToXmlString (false); foreach (MSX.X509Certificate cert in pfx.Certificates) { if (s == cert.RSA.ToXmlString (false)) x509 = new X509Certificate (cert.RawData); } // complete ? if ((x509 != null) && (key != null)) return true; } return false; } static RSA GetKeyMatchingCertificate (MSX.PKCS12 pfx, MSX.X509Certificate cert) { IDictionary attributes = pfx.GetAttributes (cert); return (pfx.GetAsymmetricAlgorithm (attributes) as RSA); } } }
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ namespace TestCases.SS.UserModel { using System; using NUnit.Framework; using NPOI.SS; using NPOI.SS.UserModel; using NPOI.SS.Util; using TestCases.SS; using NPOI.HSSF.Record.CF; using NPOI.HSSF.Util; /** * @author Dmitriy Kumshayev * @author Yegor Kozlov */ [TestFixture] public class BaseTestConditionalFormatting { private ITestDataProvider _testDataProvider; public BaseTestConditionalFormatting() { _testDataProvider = TestCases.HSSF.HSSFITestDataProvider.Instance; } public BaseTestConditionalFormatting(ITestDataProvider TestDataProvider) { _testDataProvider = TestDataProvider; } [Test] public void TestBasic() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); ISheetConditionalFormatting sheetCF = sh.SheetConditionalFormatting; Assert.AreEqual(0, sheetCF.NumConditionalFormattings); try { Assert.IsNull(sheetCF.GetConditionalFormattingAt(0)); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Specified CF index 0 is outside the allowable range")); } try { sheetCF.RemoveConditionalFormatting(0); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Specified CF index 0 is outside the allowable range")); } IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule("1"); IConditionalFormattingRule rule2 = sheetCF.CreateConditionalFormattingRule("2"); IConditionalFormattingRule rule3 = sheetCF.CreateConditionalFormattingRule("3"); IConditionalFormattingRule rule4 = sheetCF.CreateConditionalFormattingRule("4"); try { sheetCF.AddConditionalFormatting(null, rule1); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("regions must not be null")); } try { sheetCF.AddConditionalFormatting( new CellRangeAddress[] { CellRangeAddress.ValueOf("A1:A3") }, (IConditionalFormattingRule)null); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("cfRules must not be null")); } try { sheetCF.AddConditionalFormatting( new CellRangeAddress[] { CellRangeAddress.ValueOf("A1:A3") }, new IConditionalFormattingRule[0]); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("cfRules must not be empty")); } try { sheetCF.AddConditionalFormatting( new CellRangeAddress[] { CellRangeAddress.ValueOf("A1:A3") }, new IConditionalFormattingRule[] { rule1, rule2, rule3, rule4 }); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Number of rules must not exceed 3")); } } /** * Test format conditions based on a bool formula */ [Test] public void TestBooleanFormulaConditions() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); ISheetConditionalFormatting sheetCF = sh.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule("SUM(A1:A5)>10"); Assert.AreEqual(ConditionType.Formula, rule1.ConditionType); Assert.AreEqual("SUM(A1:A5)>10", rule1.Formula1); int formatIndex1 = sheetCF.AddConditionalFormatting( new CellRangeAddress[]{ CellRangeAddress.ValueOf("B1"), CellRangeAddress.ValueOf("C3"), }, rule1); Assert.AreEqual(0, formatIndex1); Assert.AreEqual(1, sheetCF.NumConditionalFormattings); CellRangeAddress[] ranges1 = sheetCF.GetConditionalFormattingAt(formatIndex1).GetFormattingRanges(); Assert.AreEqual(2, ranges1.Length); Assert.AreEqual("B1", ranges1[0].FormatAsString()); Assert.AreEqual("C3", ranges1[1].FormatAsString()); // adjacent Address are merged int formatIndex2 = sheetCF.AddConditionalFormatting( new CellRangeAddress[]{ CellRangeAddress.ValueOf("B1"), CellRangeAddress.ValueOf("B2"), CellRangeAddress.ValueOf("B3"), }, rule1); Assert.AreEqual(1, formatIndex2); Assert.AreEqual(2, sheetCF.NumConditionalFormattings); CellRangeAddress[] ranges2 = sheetCF.GetConditionalFormattingAt(formatIndex2).GetFormattingRanges(); Assert.AreEqual(1, ranges2.Length); Assert.AreEqual("B1:B3", ranges2[0].FormatAsString()); } [Test] public void TestSingleFormulaConditions() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); ISheetConditionalFormatting sheetCF = sh.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Equal, "SUM(A1:A5)+10"); Assert.AreEqual(ConditionType.CellValueIs, rule1.ConditionType); Assert.AreEqual("SUM(A1:A5)+10", rule1.Formula1); Assert.AreEqual(ComparisonOperator.Equal, rule1.ComparisonOperation); IConditionalFormattingRule rule2 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.NotEqual, "15"); Assert.AreEqual(ConditionType.CellValueIs, rule2.ConditionType); Assert.AreEqual("15", rule2.Formula1); Assert.AreEqual(ComparisonOperator.NotEqual, rule2.ComparisonOperation); IConditionalFormattingRule rule3 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.NotEqual, "15"); Assert.AreEqual(ConditionType.CellValueIs, rule3.ConditionType); Assert.AreEqual("15", rule3.Formula1); Assert.AreEqual(ComparisonOperator.NotEqual, rule3.ComparisonOperation); IConditionalFormattingRule rule4 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.GreaterThan, "0"); Assert.AreEqual(ConditionType.CellValueIs, rule4.ConditionType); Assert.AreEqual("0", rule4.Formula1); Assert.AreEqual(ComparisonOperator.GreaterThan, rule4.ComparisonOperation); IConditionalFormattingRule rule5 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.LessThan, "0"); Assert.AreEqual(ConditionType.CellValueIs, rule5.ConditionType); Assert.AreEqual("0", rule5.Formula1); Assert.AreEqual(ComparisonOperator.LessThan, rule5.ComparisonOperation); IConditionalFormattingRule rule6 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.GreaterThanOrEqual, "0"); Assert.AreEqual(ConditionType.CellValueIs, rule6.ConditionType); Assert.AreEqual("0", rule6.Formula1); Assert.AreEqual(ComparisonOperator.GreaterThanOrEqual, rule6.ComparisonOperation); IConditionalFormattingRule rule7 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.LessThanOrEqual, "0"); Assert.AreEqual(ConditionType.CellValueIs, rule7.ConditionType); Assert.AreEqual("0", rule7.Formula1); Assert.AreEqual(ComparisonOperator.LessThanOrEqual, rule7.ComparisonOperation); IConditionalFormattingRule rule8 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Between, "0", "5"); Assert.AreEqual(ConditionType.CellValueIs, rule8.ConditionType); Assert.AreEqual("0", rule8.Formula1); Assert.AreEqual("5", rule8.Formula2); Assert.AreEqual(ComparisonOperator.Between, rule8.ComparisonOperation); IConditionalFormattingRule rule9 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.NotBetween, "0", "5"); Assert.AreEqual(ConditionType.CellValueIs, rule9.ConditionType); Assert.AreEqual("0", rule9.Formula1); Assert.AreEqual("5", rule9.Formula2); Assert.AreEqual(ComparisonOperator.NotBetween, rule9.ComparisonOperation); } [Test] public void TestCopy() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet1 = wb.CreateSheet(); ISheet sheet2 = wb.CreateSheet(); ISheetConditionalFormatting sheet1CF = sheet1.SheetConditionalFormatting; ISheetConditionalFormatting sheet2CF = sheet2.SheetConditionalFormatting; Assert.AreEqual(0, sheet1CF.NumConditionalFormattings); Assert.AreEqual(0, sheet2CF.NumConditionalFormattings); IConditionalFormattingRule rule1 = sheet1CF.CreateConditionalFormattingRule( ComparisonOperator.Equal, "SUM(A1:A5)+10"); IConditionalFormattingRule rule2 = sheet1CF.CreateConditionalFormattingRule( ComparisonOperator.NotEqual, "15"); // adjacent Address are merged int formatIndex = sheet1CF.AddConditionalFormatting( new CellRangeAddress[]{ CellRangeAddress.ValueOf("A1:A5"), CellRangeAddress.ValueOf("C1:C5") }, rule1, rule2); Assert.AreEqual(0, formatIndex); Assert.AreEqual(1, sheet1CF.NumConditionalFormattings); Assert.AreEqual(0, sheet2CF.NumConditionalFormattings); sheet2CF.AddConditionalFormatting(sheet1CF.GetConditionalFormattingAt(formatIndex)); Assert.AreEqual(1, sheet2CF.NumConditionalFormattings); IConditionalFormatting sheet2cf = sheet2CF.GetConditionalFormattingAt(0); Assert.AreEqual(2, sheet2cf.NumberOfRules); Assert.AreEqual("SUM(A1:A5)+10", sheet2cf.GetRule(0).Formula1); Assert.AreEqual(ComparisonOperator.Equal, sheet2cf.GetRule(0).ComparisonOperation); Assert.AreEqual(ConditionType.CellValueIs, sheet2cf.GetRule(0).ConditionType); Assert.AreEqual("15", sheet2cf.GetRule(1).Formula1); Assert.AreEqual(ComparisonOperator.NotEqual, sheet2cf.GetRule(1).ComparisonOperation); Assert.AreEqual(ConditionType.CellValueIs, sheet2cf.GetRule(1).ConditionType); } [Test] public void TestRemove() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet1 = wb.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet1.SheetConditionalFormatting; Assert.AreEqual(0, sheetCF.NumConditionalFormattings); IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Equal, "SUM(A1:A5)"); // adjacent Address are merged int formatIndex = sheetCF.AddConditionalFormatting( new CellRangeAddress[]{ CellRangeAddress.ValueOf("A1:A5") }, rule1); Assert.AreEqual(0, formatIndex); Assert.AreEqual(1, sheetCF.NumConditionalFormattings); sheetCF.RemoveConditionalFormatting(0); Assert.AreEqual(0, sheetCF.NumConditionalFormattings); try { Assert.IsNull(sheetCF.GetConditionalFormattingAt(0)); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Specified CF index 0 is outside the allowable range")); } formatIndex = sheetCF.AddConditionalFormatting( new CellRangeAddress[]{ CellRangeAddress.ValueOf("A1:A5") }, rule1); Assert.AreEqual(0, formatIndex); Assert.AreEqual(1, sheetCF.NumConditionalFormattings); sheetCF.RemoveConditionalFormatting(0); Assert.AreEqual(0, sheetCF.NumConditionalFormattings); try { Assert.IsNull(sheetCF.GetConditionalFormattingAt(0)); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Specified CF index 0 is outside the allowable range")); } } [Test] public void TestCreateCF() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); String formula = "7"; ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(formula); IFontFormatting fontFmt = rule1.CreateFontFormatting(); fontFmt.SetFontStyle(true, false); IBorderFormatting bordFmt = rule1.CreateBorderFormatting(); bordFmt.BorderBottom = (/*setter*/BorderStyle.Thin); bordFmt.BorderTop = (/*setter*/BorderStyle.Thick); bordFmt.BorderLeft = (/*setter*/BorderStyle.Dashed); bordFmt.BorderRight = (/*setter*/BorderStyle.Dotted); IPatternFormatting patternFmt = rule1.CreatePatternFormatting(); patternFmt.FillBackgroundColor = (/*setter*/HSSFColor.Yellow.Index); IConditionalFormattingRule rule2 = sheetCF.CreateConditionalFormattingRule(ComparisonOperator.Between, "1", "2"); IConditionalFormattingRule[] cfRules = { rule1, rule2 }; short col = 1; CellRangeAddress[] regions = { new CellRangeAddress(0, 65535, col, col) }; sheetCF.AddConditionalFormatting(regions, cfRules); sheetCF.AddConditionalFormatting(regions, cfRules); // Verification Assert.AreEqual(2, sheetCF.NumConditionalFormattings); sheetCF.RemoveConditionalFormatting(1); Assert.AreEqual(1, sheetCF.NumConditionalFormattings); IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.IsNotNull(cf); regions = cf.GetFormattingRanges(); Assert.IsNotNull(regions); Assert.AreEqual(1, regions.Length); CellRangeAddress r = regions[0]; Assert.AreEqual(1, r.FirstColumn); Assert.AreEqual(1, r.LastColumn); Assert.AreEqual(0, r.FirstRow); Assert.AreEqual(65535, r.LastRow); Assert.AreEqual(2, cf.NumberOfRules); rule1 = cf.GetRule(0); Assert.AreEqual("7", rule1.Formula1); Assert.IsNull(rule1.Formula2); IFontFormatting r1fp = rule1.GetFontFormatting(); Assert.IsNotNull(r1fp); Assert.IsTrue(r1fp.IsItalic); Assert.IsFalse(r1fp.IsBold); IBorderFormatting r1bf = rule1.GetBorderFormatting(); Assert.IsNotNull(r1bf); Assert.AreEqual(BorderStyle.Thin, r1bf.BorderBottom); Assert.AreEqual(BorderStyle.Thick, r1bf.BorderTop); Assert.AreEqual(BorderStyle.Dashed, r1bf.BorderLeft); Assert.AreEqual(BorderStyle.Dotted, r1bf.BorderRight); IPatternFormatting r1pf = rule1.GetPatternFormatting(); Assert.IsNotNull(r1pf); // Assert.AreEqual(HSSFColor.Yellow.index,r1pf.FillBackgroundColor); rule2 = cf.GetRule(1); Assert.AreEqual("2", rule2.Formula2); Assert.AreEqual("1", rule2.Formula1); } [Test] public void TestClone() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); String formula = "7"; ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(formula); IFontFormatting fontFmt = rule1.CreateFontFormatting(); fontFmt.SetFontStyle(true, false); IPatternFormatting patternFmt = rule1.CreatePatternFormatting(); patternFmt.FillBackgroundColor = (/*setter*/HSSFColor.Yellow.Index); IConditionalFormattingRule rule2 = sheetCF.CreateConditionalFormattingRule(ComparisonOperator.Between, "1", "2"); IConditionalFormattingRule[] cfRules = { rule1, rule2 }; short col = 1; CellRangeAddress[] regions = { new CellRangeAddress(0, 65535, col, col) }; sheetCF.AddConditionalFormatting(regions, cfRules); try { wb.CloneSheet(0); } catch (Exception e) { if (e.Message.IndexOf("needs to define a clone method") > 0) { Assert.Fail("Indentified bug 45682"); } throw e; } Assert.AreEqual(2, wb.NumberOfSheets); } [Test] public void TestShiftRows() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Between, "SUM(A10:A15)", "1+SUM(B16:B30)"); IFontFormatting fontFmt = rule1.CreateFontFormatting(); fontFmt.SetFontStyle(true, false); IPatternFormatting patternFmt = rule1.CreatePatternFormatting(); patternFmt.FillBackgroundColor = (/*setter*/HSSFColor.Yellow.Index); IConditionalFormattingRule rule2 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Between, "SUM(A10:A15)", "1+SUM(B16:B30)"); IBorderFormatting borderFmt = rule2.CreateBorderFormatting(); borderFmt.BorderDiagonal= BorderStyle.Medium; CellRangeAddress[] regions = { new CellRangeAddress(2, 4, 0, 0), // A3:A5 }; sheetCF.AddConditionalFormatting(regions, rule1); sheetCF.AddConditionalFormatting(regions, rule2); // This row-shift should destroy the CF region sheet.ShiftRows(10, 20, -9); Assert.AreEqual(0, sheetCF.NumConditionalFormattings); // re-add the CF sheetCF.AddConditionalFormatting(regions, rule1); sheetCF.AddConditionalFormatting(regions, rule2); // This row shift should only affect the formulas sheet.ShiftRows(14, 17, 8); IConditionalFormatting cf1 = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual("SUM(A10:A23)", cf1.GetRule(0).Formula1); Assert.AreEqual("1+SUM(B24:B30)", cf1.GetRule(0).Formula2); IConditionalFormatting cf2 = sheetCF.GetConditionalFormattingAt(1); Assert.AreEqual("SUM(A10:A23)", cf2.GetRule(0).Formula1); Assert.AreEqual("1+SUM(B24:B30)", cf2.GetRule(0).Formula2); sheet.ShiftRows(0, 8, 21); cf1 = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual("SUM(A10:A21)", cf1.GetRule(0).Formula1); Assert.AreEqual("1+SUM(#REF!)", cf1.GetRule(0).Formula2); cf2 = sheetCF.GetConditionalFormattingAt(1); Assert.AreEqual("SUM(A10:A21)", cf2.GetRule(0).Formula1); Assert.AreEqual("1+SUM(#REF!)", cf2.GetRule(0).Formula2); } // public void TestRead(string sampleFile) { IWorkbook wb = _testDataProvider.OpenSampleWorkbook(sampleFile); ISheet sh = wb.GetSheet("CF"); ISheetConditionalFormatting sheetCF = sh.SheetConditionalFormatting; Assert.AreEqual(3, sheetCF.NumConditionalFormattings); IConditionalFormatting cf1 = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual(2, cf1.NumberOfRules); CellRangeAddress[] regions1 = cf1.GetFormattingRanges(); Assert.AreEqual(1, regions1.Length); Assert.AreEqual("A1:A8", regions1[0].FormatAsString()); // CF1 has two rules: values less than -3 are bold-italic red, values greater than 3 are green IConditionalFormattingRule rule1 = cf1.GetRule(0); Assert.AreEqual(ConditionType.CellValueIs, rule1.ConditionType); Assert.AreEqual(ComparisonOperator.GreaterThan, rule1.ComparisonOperation); Assert.AreEqual("3", rule1.Formula1); Assert.IsNull(rule1.Formula2); // Fills and borders are not Set Assert.IsNull(rule1.GetPatternFormatting()); Assert.IsNull(rule1.GetBorderFormatting()); IFontFormatting fmt1 = rule1.GetFontFormatting(); // Assert.AreEqual(HSSFColor.GREEN.index, fmt1.FontColorIndex); Assert.IsTrue(fmt1.IsBold); Assert.IsFalse(fmt1.IsItalic); IConditionalFormattingRule rule2 = cf1.GetRule(1); Assert.AreEqual(ConditionType.CellValueIs, rule2.ConditionType); Assert.AreEqual(ComparisonOperator.LessThan, rule2.ComparisonOperation); Assert.AreEqual("-3", rule2.Formula1); Assert.IsNull(rule2.Formula2); Assert.IsNull(rule2.GetPatternFormatting()); Assert.IsNull(rule2.GetBorderFormatting()); IFontFormatting fmt2 = rule2.GetFontFormatting(); // Assert.AreEqual(HSSFColor.Red.index, fmt2.FontColorIndex); Assert.IsTrue(fmt2.IsBold); Assert.IsTrue(fmt2.IsItalic); IConditionalFormatting cf2 = sheetCF.GetConditionalFormattingAt(1); Assert.AreEqual(1, cf2.NumberOfRules); CellRangeAddress[] regions2 = cf2.GetFormattingRanges(); Assert.AreEqual(1, regions2.Length); Assert.AreEqual("B9", regions2[0].FormatAsString()); IConditionalFormattingRule rule3 = cf2.GetRule(0); Assert.AreEqual(ConditionType.Formula, rule3.ConditionType); Assert.AreEqual(ComparisonOperator.NoComparison, rule3.ComparisonOperation); Assert.AreEqual("$A$8>5", rule3.Formula1); Assert.IsNull(rule3.Formula2); IFontFormatting fmt3 = rule3.GetFontFormatting(); // Assert.AreEqual(HSSFColor.Red.index, fmt3.FontColorIndex); Assert.IsTrue(fmt3.IsBold); Assert.IsTrue(fmt3.IsItalic); IPatternFormatting fmt4 = rule3.GetPatternFormatting(); // Assert.AreEqual(HSSFColor.LIGHT_CORNFLOWER_BLUE.index, fmt4.FillBackgroundColor); // Assert.AreEqual(HSSFColor.Automatic.index, fmt4.FillForegroundColor); Assert.AreEqual((short)FillPattern.NoFill, fmt4.FillPattern); // borders are not Set Assert.IsNull(rule3.GetBorderFormatting()); IConditionalFormatting cf3 = sheetCF.GetConditionalFormattingAt(2); CellRangeAddress[] regions3 = cf3.GetFormattingRanges(); Assert.AreEqual(1, regions3.Length); Assert.AreEqual("B1:B7", regions3[0].FormatAsString()); Assert.AreEqual(2, cf3.NumberOfRules); IConditionalFormattingRule rule4 = cf3.GetRule(0); Assert.AreEqual(ConditionType.CellValueIs, rule4.ConditionType); Assert.AreEqual(ComparisonOperator.LessThanOrEqual, rule4.ComparisonOperation); Assert.AreEqual("\"AAA\"", rule4.Formula1); Assert.IsNull(rule4.Formula2); IConditionalFormattingRule rule5 = cf3.GetRule(1); Assert.AreEqual(ConditionType.CellValueIs, rule5.ConditionType); Assert.AreEqual(ComparisonOperator.Between, rule5.ComparisonOperation); Assert.AreEqual("\"A\"", rule5.Formula1); Assert.AreEqual("\"AAA\"", rule5.Formula2); } [Test] public void TestCreateFontFormatting() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(ComparisonOperator.Equal, "7"); IFontFormatting fontFmt = rule1.CreateFontFormatting(); Assert.IsFalse(fontFmt.IsItalic); Assert.IsFalse(fontFmt.IsBold); fontFmt.SetFontStyle(true, true); Assert.IsTrue(fontFmt.IsItalic); Assert.IsTrue(fontFmt.IsBold); Assert.AreEqual(-1, fontFmt.FontHeight); // not modified fontFmt.FontHeight = (/*setter*/200); Assert.AreEqual(200, fontFmt.FontHeight); fontFmt.FontHeight = (/*setter*/100); Assert.AreEqual(100, fontFmt.FontHeight); Assert.AreEqual(FontSuperScript.None, fontFmt.EscapementType); fontFmt.EscapementType = (/*setter*/FontSuperScript.Sub); Assert.AreEqual(FontSuperScript.Sub, fontFmt.EscapementType); fontFmt.EscapementType = (/*setter*/FontSuperScript.None); Assert.AreEqual(FontSuperScript.None, fontFmt.EscapementType); fontFmt.EscapementType = (/*setter*/FontSuperScript.Super); Assert.AreEqual(FontSuperScript.Super, fontFmt.EscapementType); Assert.AreEqual(FontUnderlineType.None, fontFmt.UnderlineType); fontFmt.UnderlineType = (/*setter*/FontUnderlineType.Single); Assert.AreEqual(FontUnderlineType.Single, fontFmt.UnderlineType); fontFmt.UnderlineType = (/*setter*/FontUnderlineType.None); Assert.AreEqual(FontUnderlineType.None, fontFmt.UnderlineType); fontFmt.UnderlineType = (/*setter*/FontUnderlineType.Double); Assert.AreEqual(FontUnderlineType.Double, fontFmt.UnderlineType); Assert.AreEqual(-1, fontFmt.FontColorIndex); fontFmt.FontColorIndex = (/*setter*/HSSFColor.Red.Index); Assert.AreEqual(HSSFColor.Red.Index, fontFmt.FontColorIndex); fontFmt.FontColorIndex = (/*setter*/HSSFColor.Automatic.Index); Assert.AreEqual(HSSFColor.Automatic.Index, fontFmt.FontColorIndex); fontFmt.FontColorIndex = (/*setter*/HSSFColor.Blue.Index); Assert.AreEqual(HSSFColor.Blue.Index, fontFmt.FontColorIndex); IConditionalFormattingRule[] cfRules = { rule1 }; CellRangeAddress[] regions = { CellRangeAddress.ValueOf("A1:A5") }; sheetCF.AddConditionalFormatting(regions, cfRules); // Verification IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.IsNotNull(cf); Assert.AreEqual(1, cf.NumberOfRules); IFontFormatting r1fp = cf.GetRule(0).GetFontFormatting(); Assert.IsNotNull(r1fp); Assert.IsTrue(r1fp.IsItalic); Assert.IsTrue(r1fp.IsBold); Assert.AreEqual(FontSuperScript.Super, r1fp.EscapementType); Assert.AreEqual(FontUnderlineType.Double, r1fp.UnderlineType); Assert.AreEqual(HSSFColor.Blue.Index, r1fp.FontColorIndex); } [Test] public void TestCreateBorderFormatting() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(ComparisonOperator.Equal, "7"); IBorderFormatting borderFmt = rule1.CreateBorderFormatting(); Assert.AreEqual(BorderStyle.None, borderFmt.BorderBottom); borderFmt.BorderBottom = (/*setter*/BorderStyle.Dotted); Assert.AreEqual(BorderStyle.Dotted, borderFmt.BorderBottom); borderFmt.BorderBottom = (/*setter*/BorderStyle.None); Assert.AreEqual(BorderStyle.None, borderFmt.BorderBottom); borderFmt.BorderBottom = (/*setter*/BorderStyle.Thick); Assert.AreEqual(BorderStyle.Thick, borderFmt.BorderBottom); Assert.AreEqual(BorderStyle.None, borderFmt.BorderTop); borderFmt.BorderTop = (/*setter*/BorderStyle.Dotted); Assert.AreEqual(BorderStyle.Dotted, borderFmt.BorderTop); borderFmt.BorderTop = (/*setter*/BorderStyle.None); Assert.AreEqual(BorderStyle.None, borderFmt.BorderTop); borderFmt.BorderTop = (/*setter*/BorderStyle.Thick); Assert.AreEqual(BorderStyle.Thick, borderFmt.BorderTop); Assert.AreEqual(BorderStyle.None, borderFmt.BorderLeft); borderFmt.BorderLeft = (/*setter*/BorderStyle.Dotted); Assert.AreEqual(BorderStyle.Dotted, borderFmt.BorderLeft); borderFmt.BorderLeft = (/*setter*/BorderStyle.None); Assert.AreEqual(BorderStyle.None, borderFmt.BorderLeft); borderFmt.BorderLeft = (/*setter*/BorderStyle.Thin); Assert.AreEqual(BorderStyle.Thin, borderFmt.BorderLeft); Assert.AreEqual(BorderStyle.None, borderFmt.BorderRight); borderFmt.BorderRight = (/*setter*/BorderStyle.Dotted); Assert.AreEqual(BorderStyle.Dotted, borderFmt.BorderRight); borderFmt.BorderRight = (/*setter*/BorderStyle.None); Assert.AreEqual(BorderStyle.None, borderFmt.BorderRight); borderFmt.BorderRight = (/*setter*/BorderStyle.Hair); Assert.AreEqual(BorderStyle.Hair, borderFmt.BorderRight); IConditionalFormattingRule[] cfRules = { rule1 }; CellRangeAddress[] regions = { CellRangeAddress.ValueOf("A1:A5") }; sheetCF.AddConditionalFormatting(regions, cfRules); // Verification IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.IsNotNull(cf); Assert.AreEqual(1, cf.NumberOfRules); IBorderFormatting r1fp = cf.GetRule(0).GetBorderFormatting(); Assert.IsNotNull(r1fp); Assert.AreEqual(BorderStyle.Thick, r1fp.BorderBottom); Assert.AreEqual(BorderStyle.Thick, r1fp.BorderTop); Assert.AreEqual(BorderStyle.Thin, r1fp.BorderLeft); Assert.AreEqual(BorderStyle.Hair, r1fp.BorderRight); } [Test] public void TestBug55380() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); CellRangeAddress[] ranges = new CellRangeAddress[] { CellRangeAddress.ValueOf("C9:D30"), CellRangeAddress.ValueOf("C7:C31") }; IConditionalFormattingRule rule = sheet.SheetConditionalFormatting.CreateConditionalFormattingRule("$A$1>0"); sheet.SheetConditionalFormatting.AddConditionalFormatting(ranges, rule); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcmv = Google.Cloud.Monitoring.V3; namespace Google.Cloud.Monitoring.V3 { public partial class ListNotificationChannelDescriptorsRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gagr::ProjectName ProjectName { get => string.IsNullOrEmpty(Name) ? null : gagr::ProjectName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gagr::OrganizationName OrganizationName { get => string.IsNullOrEmpty(Name) ? null : gagr::OrganizationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::FolderName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gagr::FolderName FolderName { get => string.IsNullOrEmpty(Name) ? null : gagr::FolderName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gagr::ProjectName.TryParse(Name, out gagr::ProjectName project)) { return project; } if (gagr::OrganizationName.TryParse(Name, out gagr::OrganizationName organization)) { return organization; } if (gagr::FolderName.TryParse(Name, out gagr::FolderName folder)) { return folder; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } public partial class GetNotificationChannelDescriptorRequest { /// <summary> /// <see cref="gcmv::NotificationChannelDescriptorName"/>-typed view over the <see cref="Name"/> resource name /// property. /// </summary> public gcmv::NotificationChannelDescriptorName NotificationChannelDescriptorName { get => string.IsNullOrEmpty(Name) ? null : gcmv::NotificationChannelDescriptorName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gcmv::NotificationChannelDescriptorName.TryParse(Name, out gcmv::NotificationChannelDescriptorName notificationChannelDescriptor)) { return notificationChannelDescriptor; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } public partial class CreateNotificationChannelRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gagr::ProjectName ProjectName { get => string.IsNullOrEmpty(Name) ? null : gagr::ProjectName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gagr::OrganizationName OrganizationName { get => string.IsNullOrEmpty(Name) ? null : gagr::OrganizationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::FolderName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gagr::FolderName FolderName { get => string.IsNullOrEmpty(Name) ? null : gagr::FolderName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gagr::ProjectName.TryParse(Name, out gagr::ProjectName project)) { return project; } if (gagr::OrganizationName.TryParse(Name, out gagr::OrganizationName organization)) { return organization; } if (gagr::FolderName.TryParse(Name, out gagr::FolderName folder)) { return folder; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } public partial class ListNotificationChannelsRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gagr::ProjectName ProjectName { get => string.IsNullOrEmpty(Name) ? null : gagr::ProjectName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gagr::OrganizationName OrganizationName { get => string.IsNullOrEmpty(Name) ? null : gagr::OrganizationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::FolderName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gagr::FolderName FolderName { get => string.IsNullOrEmpty(Name) ? null : gagr::FolderName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gagr::ProjectName.TryParse(Name, out gagr::ProjectName project)) { return project; } if (gagr::OrganizationName.TryParse(Name, out gagr::OrganizationName organization)) { return organization; } if (gagr::FolderName.TryParse(Name, out gagr::FolderName folder)) { return folder; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } public partial class GetNotificationChannelRequest { /// <summary> /// <see cref="gcmv::NotificationChannelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::NotificationChannelName NotificationChannelName { get => string.IsNullOrEmpty(Name) ? null : gcmv::NotificationChannelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gcmv::NotificationChannelName.TryParse(Name, out gcmv::NotificationChannelName notificationChannel)) { return notificationChannel; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } public partial class DeleteNotificationChannelRequest { /// <summary> /// <see cref="gcmv::NotificationChannelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::NotificationChannelName NotificationChannelName { get => string.IsNullOrEmpty(Name) ? null : gcmv::NotificationChannelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gcmv::NotificationChannelName.TryParse(Name, out gcmv::NotificationChannelName notificationChannel)) { return notificationChannel; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } public partial class SendNotificationChannelVerificationCodeRequest { /// <summary> /// <see cref="gcmv::NotificationChannelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::NotificationChannelName NotificationChannelName { get => string.IsNullOrEmpty(Name) ? null : gcmv::NotificationChannelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gcmv::NotificationChannelName.TryParse(Name, out gcmv::NotificationChannelName notificationChannel)) { return notificationChannel; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } public partial class GetNotificationChannelVerificationCodeRequest { /// <summary> /// <see cref="gcmv::NotificationChannelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::NotificationChannelName NotificationChannelName { get => string.IsNullOrEmpty(Name) ? null : gcmv::NotificationChannelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gcmv::NotificationChannelName.TryParse(Name, out gcmv::NotificationChannelName notificationChannel)) { return notificationChannel; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } public partial class VerifyNotificationChannelRequest { /// <summary> /// <see cref="gcmv::NotificationChannelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::NotificationChannelName NotificationChannelName { get => string.IsNullOrEmpty(Name) ? null : gcmv::NotificationChannelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gcmv::NotificationChannelName.TryParse(Name, out gcmv::NotificationChannelName notificationChannel)) { return notificationChannel; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.ServiceModel.Description; #if PRIVATE_RTLIB using Microsoft.Xml.Schema; using XmlNS = Microsoft.Xml; #else using System.Xml.Schema; using XmlNS = System.Xml; #endif using WsdlNS = System.Web.Services.Description; namespace Microsoft.Tools.ServiceModel.Svcutil.Metadata { public class MetadataDocumentSaver { private const string defaultPolicyFileName = "policy"; private const string defaultMetadataFileName = "metadata"; internal const bool DefaultOverwrite = false; internal const MetadataFileNamingConvention DefaultNamingConvention = MetadataFileNamingConvention.Namespace; private MetadataFileNameManager FileNameMgr { get; set; } private List<MetadataFileInfo> MetadataFiles { get; set; } private string DirectoryPath { get; set; } private MetadataFileNamingConvention NamingConvention { get; set; } private List<UnresolvedUri> UnresolvedReferences { get; set; } private MetadataDocumentSaver(string directoryPath, IEnumerable<MetadataSection> documents, MetadataFileNamingConvention namingConvention) { this.DirectoryPath = directoryPath ?? throw new ArgumentNullException(nameof(directoryPath)); this.MetadataFiles = new List<MetadataFileInfo>(); this.NamingConvention = namingConvention; this.FileNameMgr = new MetadataFileNameManager(); this.UnresolvedReferences = new List<UnresolvedUri>(); AddMetadataFiles(documents); } public static async Task<SaveResult> SaveMetadataAsync(string directoryPath, IEnumerable<MetadataSection> documents, CancellationToken cancellationToken) { return await SaveMetadataAsync(directoryPath, documents, DefaultNamingConvention, DefaultOverwrite, cancellationToken).ConfigureAwait(false); } public static async Task<SaveResult> SaveMetadataAsync(string directoryPath, IEnumerable<MetadataSection> documents, MetadataFileNamingConvention namingConvention, bool overwrite, CancellationToken cancellationToken) { var metadataDocumentSaver = new MetadataDocumentSaver(directoryPath, documents, namingConvention); var mainWsdl = await AsyncHelper.RunAsync(() => metadataDocumentSaver.SaveMetadata(overwrite), cancellationToken).ConfigureAwait(false); return new SaveResult { WsdlFilePath = mainWsdl?.FilePath, MetadataFiles = metadataDocumentSaver.MetadataFiles.Select(mf => mf.FilePath), DocumentSaveErrors = metadataDocumentSaver.UnresolvedReferences.Distinct().OrderBy(ur => ur.Uri).Select(ur => string.Format(CultureInfo.CurrentCulture, MetadataResources.ErrUnableToResolveSchemaReferenceFormat, ur.Uri)) }; } private MetadataFileInfo SaveMetadata(bool overwrite) { if (!overwrite) { var fileInfo = this.MetadataFiles.FirstOrDefault(fi => File.Exists(fi.FilePath)); if (fileInfo != null) { throw new IOException(string.Format(CultureInfo.CurrentCulture, MetadataResources.ErrFileAlreadyExistsFormat, fileInfo.FilePath)); } } foreach (var mfi in this.MetadataFiles) { using (XmlNS.XmlWriter xWriter = CreateXmlFile(mfi.FilePath)) { if (mfi.Write != null) { mfi.Write(xWriter); xWriter.Flush(); } } } return GetMainWsdl(); } private void AddMetadataFiles(IEnumerable<MetadataSection> documents) { if (documents == null) { throw new ArgumentNullException(nameof(documents)); } // prepopulate schema/wsdl includes/imports so references can be resolved/updated when resolving document paths. foreach (var doc in documents) { if (!AddUnresolvedSchemaRefs(doc.Metadata as XmlNS.Schema.XmlSchema)) { AddUnresolvedWsdlRefs(doc.Metadata as WsdlNS.ServiceDescription); } } // compute document paths. foreach (var doc in documents) { if (AddWsdl(doc.Metadata as WsdlNS.ServiceDescription) == null) { if (AddSchema(doc.Metadata as XmlNS.Schema.XmlSchema) == null) { if (AddXmlDocument(doc.Metadata as XmlNS.XmlElement, doc.Dialect) == null) { #if DEBUG string typeName = doc.Metadata.GetType().ToString(); Debug.Fail("Unknown metadata found: " + typeName); #endif } } } } for (int idx = UnresolvedReferences.Count - 1; idx >= 0; idx--) { var unresolvedRef = UnresolvedReferences[idx]; if (unresolvedRef.Namespace != null) { // remove namespace-only schema references as they are still valid UnresolvedReferences.RemoveAt(idx); } else { // remove schema references for which multiple files are resolved (wildcards). var location = unresolvedRef.WsdlImport != null ? unresolvedRef.WsdlImport.Location : unresolvedRef.SchemaExternal?.SchemaLocation; if (MetadataFileNameManager.TryCreateUri(location, out Uri locationUri) && MetadataFileNameManager.TryResolveFiles(locationUri.LocalPath, out var files)) { var missingRefs = files.Where(file => !this.MetadataFiles.Any(metaFile => MetadataFileNameManager.UriEqual(file.FullName, metaFile.SourceUri))); if (missingRefs.Count() == 0) { var updatedLocation = Path.Combine(this.DirectoryPath, Path.GetFileName(location)); if (unresolvedRef.WsdlImport != null) { unresolvedRef.WsdlImport.Location = updatedLocation; } else { unresolvedRef.SchemaExternal.SchemaLocation = updatedLocation; } UnresolvedReferences.Remove(unresolvedRef); } } } } } private bool AddUnresolvedWsdlRefs(WsdlNS.ServiceDescription wsdl) { if (wsdl != null) { foreach (WsdlNS.Import import in wsdl.Imports) { if (!string.IsNullOrEmpty(import.Location) && !this.UnresolvedReferences.Any(r => r.WsdlImport == import)) { import.Location = MetadataFileNameManager.GetComposedUri(wsdl.RetrievalUrl, import.Location); UnresolvedReferences.Add(new UnresolvedUri { WsdlImport = import, Wsdl = wsdl }); } } foreach (XmlNS.Schema.XmlSchema schema in wsdl.Types.Schemas) { AddUnresolvedSchemaRefs(schema); } return true; } return false; } private bool AddUnresolvedSchemaRefs(XmlNS.Schema.XmlSchema schema) { if (schema != null) { foreach (XmlNS.Schema.XmlSchemaExternal schemaExternal in schema.Includes) { if (!this.UnresolvedReferences.Any(r => r.SchemaExternal == schemaExternal)) { if (!string.IsNullOrEmpty(schemaExternal.SchemaLocation)) { schemaExternal.SchemaLocation = MetadataFileNameManager.GetComposedUri(schema.SourceUri, schemaExternal.SchemaLocation); UnresolvedReferences.Add(new UnresolvedUri { Schema = schema, SchemaExternal = schemaExternal }); } else if (schemaExternal.Schema == null) { // the MetadataExchangeClient when using MEX protocol downloads wsdl-embedded schemas separately, // need to gather namespace-only imports (which are valid w/o any schema) to be able to connect // the docs if it is the case. var schemaImport = schemaExternal as XmlNS.Schema.XmlSchemaImport; if (schemaImport != null && !string.IsNullOrEmpty(schemaImport.Namespace)) { UnresolvedReferences.Add(new UnresolvedUri { Schema = schema, SchemaExternal = schemaExternal, Namespace = schemaImport.Namespace }); } } } } return true; } return false; } private MetadataFileInfo AddWsdl(WsdlNS.ServiceDescription wsdl) { MetadataFileInfo metadataFileInfo = null; if (wsdl != null && !this.MetadataFiles.Any(mi => mi.Metadata == wsdl)) { var sourceUrl = wsdl.RetrievalUrl; var filePath = AddFilePath(wsdl.RetrievalUrl, wsdl.TargetNamespace, ".wsdl"); wsdl.RetrievalUrl = Path.GetFileName(filePath); metadataFileInfo = new WsdlFileInfo(wsdl, filePath, sourceUrl, wsdl.Write); this.MetadataFiles.Add(metadataFileInfo); var unresolvedRefs = UnresolvedReferences.Where(u => MetadataFileNameManager.UriEqual(u.WsdlImport?.Location, sourceUrl)).ToList(); foreach (var unresolvedRef in unresolvedRefs) { unresolvedRef.WsdlImport.Location = wsdl.RetrievalUrl; UnresolvedReferences.Remove(unresolvedRef); } } return metadataFileInfo; } private MetadataFileInfo AddSchema(XmlSchema schema) { MetadataFileInfo metadataFileInfo = null; if (schema != null && !this.MetadataFiles.Any(mi => mi.Metadata == schema) /*&& schema.Items.Count > 0*/) { var sourceUrl = schema.SourceUri; var filePath = AddFilePath(schema.SourceUri, schema.TargetNamespace, ".xsd"); schema.SourceUri = Path.GetFileName(filePath); metadataFileInfo = new SchemaFileInfo(schema, filePath, sourceUrl, schema.Write); this.MetadataFiles.Add(metadataFileInfo); var unresolvedRefs = UnresolvedReferences.Where(u => (MetadataFileNameManager.UriEqual(u.SchemaExternal?.SchemaLocation, sourceUrl) || (!string.IsNullOrEmpty(u.Namespace) && u.Namespace == schema.TargetNamespace))).ToList(); foreach (var unresolvedRef in unresolvedRefs) { unresolvedRef.SchemaExternal.SchemaLocation = schema.SourceUri; UnresolvedReferences.Remove(unresolvedRef); } } return metadataFileInfo; } private MetadataFileInfo AddXmlDocument(XmlNS.XmlElement document, string dialect) { MetadataFileInfo metadataFileInfo = null; if (document != null && !this.MetadataFiles.Any(mi => mi.Metadata == document)) { var fileName = GetXmlElementFilename(document, dialect); var filePath = FileNameMgr.AddFileName(this.DirectoryPath, fileName, ".xml"); metadataFileInfo = new MetadataFileInfo(document, filePath, null, document.WriteTo); this.MetadataFiles.Add(metadataFileInfo); } return metadataFileInfo; } private WsdlFileInfo GetMainWsdl() { var importedWsdl = new List<string>(); var wsdlFiles = this.MetadataFiles.OfType<WsdlFileInfo>(); // record imported wsld files to be able to identify the core wsdl file. foreach (var wsdl in wsdlFiles.Select(f => f.Wsdl)) { foreach (WsdlNS.Import import in wsdl.Imports) { var filePath = Path.Combine(this.DirectoryPath, import.Location); importedWsdl.Add(filePath); } } var mainWsdlFile = wsdlFiles.Where(w => !importedWsdl.Any(i => MetadataFileNameManager.UriEqual(i, w.FilePath))).FirstOrDefault(); if (mainWsdlFile == null) { // this may be the case of docs with circular dependencies, this is ok as they are not imported multiple times, select the first one (if any). mainWsdlFile = wsdlFiles.FirstOrDefault(); } return mainWsdlFile; } private string AddFilePath(string location, string targetNamespace, string extension) { Uri.TryCreate(location, UriKind.Absolute, out Uri uri); string filePath = this.NamingConvention == MetadataFileNamingConvention.Namespace || uri == null ? this.FileNameMgr.AddFromNamespace(this.DirectoryPath, targetNamespace, extension) : this.FileNameMgr.AddFileName(this.DirectoryPath, Path.GetFileName(uri.LocalPath), extension); return filePath; } private XmlNS.XmlWriter CreateXmlFile(string filePath) { var dirPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } var xmlWriterSettings = new XmlNS.XmlWriterSettings() { Indent = true, CheckCharacters = false }; return XmlNS.XmlWriter.Create(filePath, xmlWriterSettings); } private static string GetXmlElementFilename(XmlNS.XmlElement doc, string dialect) { string filename; if (dialect == MetadataSection.PolicyDialect) { filename = GetPolicyFilename(doc); } else { filename = defaultMetadataFileName; } return filename; } private static string GetPolicyFilename(XmlNS.XmlElement policyElement) { string id = null; if (policyElement.NamespaceURI == MetadataConstants.WSPolicy.NamespaceUri && policyElement.LocalName == MetadataConstants.WSPolicy.Elements.Policy) { id = policyElement.GetAttribute(MetadataConstants.Wsu.Attributes.Id, MetadataConstants.Wsu.NamespaceUri); if (id == null) { id = policyElement.GetAttribute(MetadataConstants.Xml.Attributes.Id, MetadataConstants.Xml.NamespaceUri); } if (!string.IsNullOrEmpty(id)) { return string.Format(CultureInfo.InvariantCulture, "{0}", id); } } return defaultPolicyFileName; } #region Nested types public class SaveResult { public string WsdlFilePath { get; internal set; } public IEnumerable<string> MetadataFiles { get; internal set; } public IEnumerable<string> DocumentSaveErrors { get; internal set; } } private class UnresolvedUri { public XmlNS.Schema.XmlSchema Schema; public XmlNS.Schema.XmlSchemaExternal SchemaExternal; public WsdlNS.ServiceDescription Wsdl; public WsdlNS.Import WsdlImport; public string Namespace; public string Uri { get { if (SchemaExternal != null) { return SchemaExternal.SchemaLocation; } if (WsdlImport != null) { return WsdlImport.Location; } return null; } } public override string ToString() { return string.IsNullOrEmpty(this.Uri) ? base.ToString() : this.Uri; } public override bool Equals(object obj) { UnresolvedUri other = obj as UnresolvedUri; return other != null && MetadataFileNameManager.UriEqual(this.Uri, other.Uri); } public override int GetHashCode() { return this.ToString().GetHashCode(); } } #endregion } }
using DragonSpark.Extensions; using DragonSpark.TypeSystem; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Core; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Core.Objects; using System.Data.Entity.Core.Objects.DataClasses; using System.Diagnostics; using System.Linq; using System.Reflection; namespace DragonSpark.Windows.Entity { public static class ObjectContextExtensions { readonly static List<ObjectContext> InitializedContexts = new List<ObjectContext>(); /// <summary> /// Initializeds the specified target. /// </summary> /// <typeparam name="TContext">The type of the t context.</typeparam> /// <param name="target">The target.</param> /// <returns>TContext.</returns> public static TContext Initialized<TContext>( this TContext target ) where TContext : ObjectContext { if ( !InitializedContexts.Contains( target ) ) { target.MetadataWorkspace.LoadFromAssembly( target.GetType().Assembly ); InitializedContexts.Add( target ); } return target; } /// <summary> /// Creates the query text. /// </summary> /// <typeparam name="TEntity">The type of the t entity.</typeparam> /// <param name="target">The target.</param> /// <param name="where">The where.</param> /// <returns>System.String.</returns> public static string CreateQueryText<TEntity>( this ObjectContext target, string where ) where TEntity : EntityObject { var result = target.CreateQueryText( typeof(TEntity), where ); return result; } /// <summary> /// Creates the query text. /// </summary> /// <param name="target">The target.</param> /// <param name="entityType">Type of the entity.</param> /// <param name="where">The where.</param> /// <returns>System.String.</returns> public static string CreateQueryText( this ObjectContext target, Type entityType, string where ) { var result = string.Format( "SELECT VALUE entity FROM {0}.{1} AS entity WHERE {2}", target.DefaultContainerName, target.DetermineEntitySet( entityType ).Name, where ); return result; } /// <summary> /// Finds the specified target. /// </summary> /// <typeparam name="TItem">The type of the t item.</typeparam> /// <param name="target">The target.</param> /// <param name="key">The key.</param> /// <returns>TItem.</returns> public static TItem Find<TItem>( this ObjectContext target, object[] key ) where TItem : class { var entityKey = MetadataHelper.CreateKey<TItem>( target, key ); object entity; var result = target.TryGetObjectByKey( entityKey, out entity ) ? (TItem)entity : null; return result; } /// <summary> /// Determines the entity set. /// </summary> /// <typeparam name="TEntity">The type of the t entity.</typeparam> /// <param name="context">The context.</param> /// <returns>EntitySet.</returns> public static EntitySet DetermineEntitySet<TEntity>( this ObjectContext context ) { var result = context.DetermineEntitySet( typeof(TEntity) ); return result; } /// <summary> /// Determines the entity set. /// </summary> /// <param name="context">The context.</param> /// <param name="entityType">Type of the entity.</param> /// <returns>EntitySet.</returns> public static EntitySet DetermineEntitySet( this ObjectContext context, Type entityType ) { var objects = (ObjectItemCollection)context.MetadataWorkspace.GetItemCollection(DataSpace.OSpace); var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace); var result = container.BaseEntitySets.OfType<EntitySet>().FirstOrDefault(x => !x.Name.Contains( "_" ) && objects.GetClrType( context.MetadataWorkspace.GetObjectSpaceType( x.ElementType ) ).IsAssignableFrom( entityType )); return result; } /// <summary> /// Adds the or attach. /// </summary> /// <param name="target">The target.</param> /// <param name="entity">The entity.</param> public static void AddOrAttach( this ObjectContext target, object entity ) { object existing; var key = MetadataHelper.ExtractKey( target, entity ); if ( target.TryGetObjectByKey( key, out existing ) ) { var entityWithKey = entity.To<IEntityWithKey>(); entityWithKey.EntityKey = key; target.Detach( existing ); target.Attach( entityWithKey ); } else { target.Add( entity ); } } /// <summary> /// Adds the specified target. /// </summary> /// <param name="target">The target.</param> /// <param name="entity">The entity.</param> public static void Add( this ObjectContext target, object entity ) { var entitySet = target.DetermineEntitySet( entity.GetType() ); target.AddObject( entitySet.Name, entity ); } /// <summary> /// Gets the query. /// </summary> /// <param name="target">The target.</param> /// <param name="entityType">Type of the entity.</param> /// <returns>IQueryable.</returns> public static IQueryable GetQuery( this ObjectContext target, Type entityType ) { var entitySet = target.DetermineEntitySet( entityType ); var query = target.GetType().GetProperty( entitySet.Name ).GetValue( target, null ); var result = query.GetType().GetMethod( "OfType" ).MakeGenericMethod( entityType ).Invoke( query, null ).As<IQueryable>(); return result; } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="TEntity">The type of the t entity.</typeparam> /// <param name="target">The target.</param> /// <returns>ObjectQuery&lt;TEntity&gt;.</returns> public static ObjectQuery<TEntity> GetQuery<TEntity>( this ObjectContext target ) { var entitySet = target.DetermineEntitySet<TEntity>(); var query = target.GetType().GetProperty( entitySet.Name ).GetValue( target, null ); var result = query.GetType().GetMethod( "OfType" ).MakeGenericMethod( typeof(TEntity) ).Invoke( query, null ).As<ObjectQuery<TEntity>>(); return result; } /// <summary> /// Deletes the object ensured. /// </summary> /// <param name="target">The target.</param> /// <param name="entity">The entity.</param> public static void DeleteObjectEnsured( this ObjectContext target, object entity ) { // HACK: Ensure all ends are loaded: var query = from property in entity.GetType().GetRuntimeProperties() where typeof(IRelatedEnd).IsAssignableFrom( property.PropertyType ) let end = property.GetValue( entity, null ) as IRelatedEnd where end != null && !end.IsLoaded select end; foreach ( var end in query ) { end.Load(); } target.DeleteObject( entity ); } public static bool IsPropertyChanged( this ObjectContext context, object instance, string propertyName ) { var entry = GetObjectStateEntry( context, instance ); if ( entry != null ) { var edmMember = GetEdmMember( context, entry, propertyName ); switch ( edmMember.BuiltInTypeKind ) { case BuiltInTypeKind.NavigationProperty: { var navigationProperty = edmMember as NavigationProperty; var sourceRelatedEnd = entry.RelationshipManager.GetRelatedEnd( navigationProperty.RelationshipType.FullName, navigationProperty.ToEndMember.Name ); const EntityState state = EntityState.Added | EntityState.Deleted; var relationshipGroups = GetRelationshipsByRelatedEnd( context, entry, state ); return relationshipGroups.Select( relationshipGroup => relationshipGroup.Key ).Any( targetRelatedEnd => Check( targetRelatedEnd, sourceRelatedEnd ) ); } case BuiltInTypeKind.EdmProperty: { ObjectStateEntry containerStateEntry; return context.IsScalarPropertyModified( propertyName, entry, out containerStateEntry ); } } throw new InvalidOperationException( "Property type not supported" ); } return false; } static ObjectStateEntry GetObjectStateEntry( ObjectContext context, object instance ) { ObjectStateEntry result; return context.ObjectStateManager.TryGetObjectStateEntry( instance, out result ) || TryGetObjectStateEntry( context, instance, ref result ) ? result : null; } static bool TryGetObjectStateEntry( ObjectContext context, object instance, ref ObjectStateEntry result ) { object item; return context.TryGetObjectByKey( context.ExtractKey( instance ), out item ) && context.ObjectStateManager.TryGetObjectStateEntry( item, out result ); } static bool Check( IRelatedEnd targetRelatedEnd, object sourceRelatedEnd ) { var isEntityReference = targetRelatedEnd.IsEntityReference(); var same = targetRelatedEnd == sourceRelatedEnd; var result = isEntityReference && same; return result; } public static EntityState GetEntityState( this ObjectContext context, EntityKey key ) { var entry = context.ObjectStateManager.GetObjectStateEntry( key ); return entry.State; } public static string GetFullEntitySetName( this EntityKey key ) { return key.EntityContainerName + "." + key.EntitySetName; } public static IEntityWithKey GetEntityByKey( this ObjectContext context, EntityKey key ) { return (IEntityWithKey)context.ObjectStateManager.GetObjectStateEntry( key ).Entity; } // // ObjectStateEntry // public static IExtendedDataRecord UsableValues( this ObjectStateEntry entry ) { switch ( entry.State ) { case EntityState.Added: case EntityState.Detached: case EntityState.Unchanged: case EntityState.Modified: return entry.CurrentValues; case EntityState.Deleted: return (IExtendedDataRecord)entry.OriginalValues; default: throw new InvalidOperationException( "This entity state should not exist." ); } } public static EdmType EdmType( this ObjectStateEntry entry ) { return entry.UsableValues().DataRecordInfo.RecordType.EdmType; } public static bool IsManyToMany( this AssociationType associationType ) { foreach ( RelationshipEndMember endMember in associationType.RelationshipEndMembers ) { if ( endMember.RelationshipMultiplicity != RelationshipMultiplicity.Many ) { return false; } } return true; } // // RelationshipEntry // public static bool IsRelationshipForKey( this ObjectStateEntry entry, EntityKey key ) { if ( entry.IsRelationship == false ) { return false; } return ( (EntityKey)entry.UsableValues()[ 0 ] == key ) || ( (EntityKey)entry.UsableValues()[ 1 ] == key ); } public static EntityKey OtherEndKey( this ObjectStateEntry relationshipEntry, EntityKey thisEndKey ) { Debug.Assert( relationshipEntry.IsRelationship ); Debug.Assert( thisEndKey != null ); if ( (EntityKey)relationshipEntry.UsableValues()[ 0 ] == thisEndKey ) { return (EntityKey)relationshipEntry.UsableValues()[ 1 ]; } else if ( (EntityKey)relationshipEntry.UsableValues()[ 1 ] == thisEndKey ) { return (EntityKey)relationshipEntry.UsableValues()[ 0 ]; } else { throw new InvalidOperationException( "Neither end of the relationship contains the passed in key." ); } } public static string OtherEndRole( this ObjectStateEntry relationshipEntry, EntityKey thisEndKey ) { Debug.Assert( relationshipEntry != null ); Debug.Assert( relationshipEntry.IsRelationship ); Debug.Assert( thisEndKey != null ); if ( (EntityKey)relationshipEntry.UsableValues()[ 0 ] == thisEndKey ) { return relationshipEntry.UsableValues().DataRecordInfo.FieldMetadata[ 1 ].FieldType.Name; } else if ( (EntityKey)relationshipEntry.UsableValues()[ 1 ] == thisEndKey ) { return relationshipEntry.UsableValues().DataRecordInfo.FieldMetadata[ 0 ].FieldType.Name; } else { throw new InvalidOperationException( "Neither end of the relationship contains the passed in key." ); } } // // IRelatedEnd methods // public static bool IsEntityReference( this IRelatedEnd relatedEnd ) { Type relationshipType = relatedEnd.GetType(); return ( relationshipType.GetGenericTypeDefinition() == typeof( EntityReference<> ) ); } public static EntityKey GetEntityKey( this IRelatedEnd relatedEnd ) { Debug.Assert( relatedEnd.IsEntityReference() ); Type relationshipType = relatedEnd.GetType(); PropertyInfo pi = relationshipType.GetProperty( "EntityKey" ); return (EntityKey)pi.GetValue( relatedEnd, null ); } public static void SetEntityKey( this IRelatedEnd relatedEnd, EntityKey key ) { Debug.Assert( relatedEnd.IsEntityReference() ); Type relationshipType = relatedEnd.GetType(); PropertyInfo pi = relationshipType.GetProperty( "EntityKey" ); pi.SetValue( relatedEnd, key, null ); } public static bool Contains( this IRelatedEnd relatedEnd, EntityKey key ) { foreach ( object relatedObject in relatedEnd ) { Debug.Assert( relatedObject is IEntityWithKey ); if ( ( (IEntityWithKey)relatedObject ).EntityKey == key ) { return true; } } return false; } // // queries over the context // public static IEnumerable<IEntityWithKey> GetEntities( this ObjectContext context, EntityState state ) { return from e in context.ObjectStateManager.GetObjectStateEntries( state ) where e.IsRelationship == false && e.Entity != null select (IEntityWithKey)e.Entity; } public static IEnumerable<ObjectStateEntry> GetRelationships( this ObjectContext context, EntityState state ) { return from e in context.ObjectStateManager.GetObjectStateEntries( state ) where e.IsRelationship select e; } public static IEnumerable<ObjectStateEntry> GetUnchangedManyToManyRelationships( this ObjectContext context ) { return context.GetRelationships( EntityState.Unchanged ) .Where( e => ( (AssociationType)e.EdmType() ).IsManyToMany() ); } public static IEnumerable<ObjectStateEntry> GetRelationshipsForKey( this ObjectContext context, EntityKey key, EntityState state ) { return context.GetRelationships( state ).Where( e => e.IsRelationshipForKey( key ) ); } public static IEnumerable<IGrouping<IRelatedEnd, ObjectStateEntry>> GetRelationshipsByRelatedEnd( this ObjectContext context, ObjectStateEntry entry, EntityState state ) { return from e in context.GetRelationshipsForKey( entry.EntityKey, state ) group e by ( entry.RelationshipManager .GetRelatedEnd( ( (AssociationType)( e.EdmType() ) ).Name, e.OtherEndRole( entry.EntityKey ) ) ); } // // original values // // Extension method for the ObjectContext which will create an object instance that is essentially equivalent // to the original object that was added or attached to the context before any changes were performed. // NOTE: This object will have no relationships--just the original value properties. public static object CreateOriginalValuesObject( this ObjectContext context, object source ) { // Get the state entry of the source object // NOTE: For now we require the object to implement IEntityWithKey. // This is something we should be able to relax later. Debug.Assert( source is IEntityWithKey ); EntityKey sourceKey = ( (IEntityWithKey)source ).EntityKey; // This method will throw if the key is null or an entry isn't found to match it. We // could throw nicer exceptions, but this will catch the important invalid cases. ObjectStateEntry sourceStateEntry = context.ObjectStateManager.GetObjectStateEntry( sourceKey ); // Return null for added entities & throw an exception for detached ones. In other cases we can // always make a new object with the original values. switch ( sourceStateEntry.State ) { case EntityState.Added: return null; case EntityState.Detached: throw new InvalidOperationException( "Can't get original values when detached." ); } // Create target object and add it to the context so that we can easily set properties using // the StateEntry. Since objects in the added state use temp keys, we know this won't // conflict with anything already in the context. object target = Activator.CreateInstance( source.GetType() ); string fullEntitySetName = sourceKey.EntityContainerName + "." + sourceKey.EntitySetName; context.AddObject( fullEntitySetName, target ); EntityKey targetKey = context.CreateEntityKey( fullEntitySetName, target ); ObjectStateEntry targetStateEntry = context.ObjectStateManager.GetObjectStateEntry( targetKey ); // Copy original values from the sourceStateEntry to the targetStateEntry. This will // cause the corresponding properties on the object to be set. for ( int i = 0; i < sourceStateEntry.OriginalValues.FieldCount; i++ ) { targetStateEntry.CurrentValues.SetValue( i, sourceStateEntry.OriginalValues[ i ] ); } // Detach the object we just created since we only attached it temporarily in order to use // the stateEntry. context.Detach( target ); // Set the EntityKey property on the object (if it implements IEntityWithKey). IEntityWithKey targetWithKey = target as IEntityWithKey; if ( targetWithKey != null ) { targetWithKey.EntityKey = sourceKey; } return target; } private static bool IsScalarPropertyModified(this ObjectContext context, string scalarPropertyName, ObjectStateEntry entityContainer, out ObjectStateEntry containerStateEntry) { containerStateEntry = context.ObjectStateManager.GetObjectStateEntry( entityContainer.EntityKey ); var modifiedProperties = containerStateEntry.GetModifiedProperties(); var changedProperty = modifiedProperties.FirstOrDefault( element => ( element == scalarPropertyName ) ); var isModified = ( null != changedProperty ); if ( isModified ) { var originalValue = containerStateEntry.OriginalValues[changedProperty]; var currentValue = containerStateEntry.CurrentValues[changedProperty]; //sometimes property can be treated as changed even though you set the same value it had before isModified = !Equals( originalValue, currentValue ); } return isModified; } static EdmMember GetEdmMember( this ObjectContext context, ObjectStateEntry entry, string propertyName ) { var entityType = context.MetadataWorkspace.GetEntityMetadata( entry.Entity.GetType() ); var edmMembers = entityType.MetadataProperties.First( p => p.Name == "Members" ).Value as IEnumerable<EdmMember> ?? Items<EdmMember>.Default; var edmMember = edmMembers.FirstOrDefault( item => item.Name == propertyName ); if ( edmMember == null ) { throw new ArgumentException( $"Cannot find property metadata: property '{propertyName}' in '{entityType.Name}' entity object" ); } return edmMember; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ConvertScalarToVector128UInt32UInt32() { var test = new ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt32UInt32(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt32UInt32 { private struct TestStruct { public UInt32 _fld; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld = TestLibrary.Generator.GetUInt32(); return testStruct; } public void RunStructFldScenario(ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt32UInt32 testClass) { var result = Sse2.ConvertScalarToVector128UInt32(_fld); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32 _data; private static UInt32 _clsVar; private UInt32 _fld; private ScalarSimdUnaryOpTest__DataTable<UInt32> _dataTable; static ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt32UInt32() { _clsVar = TestLibrary.Generator.GetUInt32(); } public ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt32UInt32() { Succeeded = true; _fld = TestLibrary.Generator.GetUInt32(); _data = TestLibrary.Generator.GetUInt32(); _dataTable = new ScalarSimdUnaryOpTest__DataTable<UInt32>(new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ConvertScalarToVector128UInt32( Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_data, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertScalarToVector128UInt32), new Type[] { typeof(UInt32) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_data, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ConvertScalarToVector128UInt32( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data = Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data)); var result = Sse2.ConvertScalarToVector128UInt32(data); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(data, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt32UInt32(); var result = Sse2.ConvertScalarToVector128UInt32(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ConvertScalarToVector128UInt32(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ConvertScalarToVector128UInt32(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(UInt32 firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(firstOp, outArray, method); } private void ValidateResult(UInt32 firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (false) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ConvertScalarToVector128UInt32)}<UInt32>(UInt32): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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. *******************************************************************************/ //package com.handmark.pulltorefresh.library.internal; //import android.annotation.SuppressLint; //import android.content.Context; //import android.content.res.ColorStateList; //import android.content.res.TypedArray; //import android.graphics.Typeface; //import android.graphics.drawable.AnimationDrawable; //import android.graphics.drawable.Drawable; //import android.text.TextUtils; //import android.util.TypedValue; //import android.view.Gravity; //import android.view.LayoutInflater; //import android.view.View; //import android.view.ViewGroup; //import android.view.animation.Interpolator; //import android.view.animation.LinearInterpolator; //import android.widget.FrameLayout; //import android.widget.ImageView; //import android.widget.ProgressBar; //import android.widget.TextView; //import com.handmark.pulltorefresh.library.ILoadingLayout; //import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; //import com.handmark.pulltorefresh.library.PullToRefreshBase.Orientation; //import com.handmark.pulltorefresh.library.R; using Android.Content; using Android.Content.Res; using Android.Graphics; using Android.Graphics.Drawables; using Android.Runtime; using Android.Text; using Android.Util; using Android.Views; using Android.Views.Animations; using Android.Widget; using Mode = Com.Handmark.PullToRefresh.Library.PtrMode; namespace Com.Handmark.PullToRefresh.Library.Internal { //@SuppressLint("ViewConstructor") public abstract class LoadingLayout : FrameLayout, ILoadingLayout { const string LOG_TAG = "PullToRefresh-LoadingLayout"; protected static readonly IInterpolator ANIMATION_INTERPOLATOR = new LinearInterpolator(); private FrameLayout mInnerLayout; protected readonly ImageView mHeaderImage; protected readonly ProgressBar mHeaderProgress; private bool mUseIntrinsicAnimation; private readonly TextView mHeaderText; private readonly TextView mSubHeaderText; protected readonly Mode mMode; protected readonly PtrOrientation mScrollDirection; private string mPullLabel; private string mRefreshingLabel; private string mReleaseLabel; public LoadingLayout(Context context, Mode mode, PtrOrientation scrollDirection, TypedArray attrs) : base(context) { //base(context); mMode = mode; mScrollDirection = scrollDirection; switch (scrollDirection) { case PtrOrientation.HORIZONTAL: LayoutInflater.From(context).Inflate(Resource.Layout.pull_to_refresh_header_horizontal, this); break; case PtrOrientation.VERTICAL: default: LayoutInflater.From(context).Inflate(Resource.Layout.pull_to_refresh_header_vertical, this); break; } mInnerLayout = (FrameLayout)FindViewById(Resource.Id.fl_inner); mHeaderText = (TextView)mInnerLayout.FindViewById(Resource.Id.pull_to_refresh_text); mHeaderProgress = (ProgressBar)mInnerLayout.FindViewById(Resource.Id.pull_to_refresh_progress); mSubHeaderText = (TextView)mInnerLayout.FindViewById(Resource.Id.pull_to_refresh_sub_text); mHeaderImage = (ImageView)mInnerLayout.FindViewById(Resource.Id.pull_to_refresh_image); FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)mInnerLayout.LayoutParameters; switch (mode) { case Mode.PULL_FROM_END: lp.Gravity = scrollDirection == PtrOrientation.VERTICAL ? GravityFlags.Top : GravityFlags.Left; // Load in labels mPullLabel = context.GetString(Resource.String.pull_to_refresh_from_bottom_pull_label); mRefreshingLabel = context.GetString(Resource.String.pull_to_refresh_from_bottom_refreshing_label); mReleaseLabel = context.GetString(Resource.String.pull_to_refresh_from_bottom_release_label); break; case Mode.PULL_FROM_START: default: lp.Gravity = scrollDirection == PtrOrientation.VERTICAL ? GravityFlags.Bottom : GravityFlags.Right; // Load in labels mPullLabel = context.GetString(Resource.String.pull_to_refresh_pull_label); mRefreshingLabel = context.GetString(Resource.String.pull_to_refresh_refreshing_label); mReleaseLabel = context.GetString(Resource.String.pull_to_refresh_release_label); break; } if (attrs.HasValue(Resource.Styleable.PullToRefresh_ptrHeaderBackground)) { Drawable background = attrs.GetDrawable(Resource.Styleable.PullToRefresh_ptrHeaderBackground); if (null != background) { ViewCompat.setBackground(this, background); } } if (attrs.HasValue(Resource.Styleable.PullToRefresh_ptrHeaderTextAppearance)) { TypedValue styleID = new TypedValue(); attrs.GetValue(Resource.Styleable.PullToRefresh_ptrHeaderTextAppearance, styleID); setTextAppearance(styleID.Data); } if (attrs.HasValue(Resource.Styleable.PullToRefresh_ptrSubHeaderTextAppearance)) { TypedValue styleID = new TypedValue(); attrs.GetValue(Resource.Styleable.PullToRefresh_ptrSubHeaderTextAppearance, styleID); setSubTextAppearance(styleID.Data); } // Text Color attrs need to be set after TextAppearance attrs if (attrs.HasValue(Resource.Styleable.PullToRefresh_ptrHeaderTextColor)) { ColorStateList colors = attrs.GetColorStateList(Resource.Styleable.PullToRefresh_ptrHeaderTextColor); if (null != colors) { setTextColor(colors); } } if (attrs.HasValue(Resource.Styleable.PullToRefresh_ptrHeaderSubTextColor)) { ColorStateList colors = attrs.GetColorStateList(Resource.Styleable.PullToRefresh_ptrHeaderSubTextColor); if (null != colors) { setSubTextColor(colors); } } // Try and get defined drawable from Attrs Drawable imageDrawable = null; if (attrs.HasValue(Resource.Styleable.PullToRefresh_ptrDrawable)) { imageDrawable = attrs.GetDrawable(Resource.Styleable.PullToRefresh_ptrDrawable); } // Check Specific Drawable from Attrs, these overrite the generic // drawable attr above switch (mode) { case Mode.PULL_FROM_START: default: if (attrs.HasValue(Resource.Styleable.PullToRefresh_ptrDrawableStart)) { imageDrawable = attrs.GetDrawable(Resource.Styleable.PullToRefresh_ptrDrawableStart); } else if (attrs.HasValue(Resource.Styleable.PullToRefresh_ptrDrawableTop)) { Utils.warnDeprecation("ptrDrawableTop", "ptrDrawableStart"); imageDrawable = attrs.GetDrawable(Resource.Styleable.PullToRefresh_ptrDrawableTop); } break; case Mode.PULL_FROM_END: if (attrs.HasValue(Resource.Styleable.PullToRefresh_ptrDrawableEnd)) { imageDrawable = attrs.GetDrawable(Resource.Styleable.PullToRefresh_ptrDrawableEnd); } else if (attrs.HasValue(Resource.Styleable.PullToRefresh_ptrDrawableBottom)) { Utils.warnDeprecation("ptrDrawableBottom", "ptrDrawableEnd"); imageDrawable = attrs.GetDrawable(Resource.Styleable.PullToRefresh_ptrDrawableBottom); } break; } // If we don't have a user defined drawable, load the default if (null == imageDrawable) { imageDrawable = context.Resources.GetDrawable(getDefaultDrawableResId()); } // Set Drawable, and save width/height setLoadingDrawable(imageDrawable); reset(); } public void setHeight(int height) { ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams)this.LayoutParameters; lp.Height = height; RequestLayout(); } public void setWidth(int width) { ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams)this.LayoutParameters; lp.Width = width; RequestLayout(); } public int getContentSize() { switch (mScrollDirection) { case PtrOrientation.HORIZONTAL: return mInnerLayout.Width; case PtrOrientation.VERTICAL: default: return mInnerLayout.Height; } } public void hideAllViews() { if (ViewStates.Visible == mHeaderText.Visibility) { mHeaderText.Visibility = ViewStates.Invisible; } if (ViewStates.Visible == mHeaderProgress.Visibility) { mHeaderProgress.Visibility = ViewStates.Invisible; } if (ViewStates.Visible == mHeaderImage.Visibility) { mHeaderImage.Visibility = ViewStates.Invisible; } if (ViewStates.Visible == mSubHeaderText.Visibility) { mSubHeaderText.Visibility = ViewStates.Invisible; } } public void onPull(float scaleOfLayout) { if (!mUseIntrinsicAnimation) { onPullImpl(scaleOfLayout); } } public void pullToRefresh() { if (null != mHeaderText) { mHeaderText.Text = mPullLabel; } // Now call the callback pullToRefreshImpl(); } public void refreshing() { if (null != mHeaderText) { mHeaderText.Text = mRefreshingLabel; } if (mUseIntrinsicAnimation) { ((AnimationDrawable)mHeaderImage.Drawable).Start(); } else { // Now call the callback refreshingImpl(); } if (null != mSubHeaderText) { mSubHeaderText.Visibility = ViewStates.Gone; } } public void releaseToRefresh() { if (null != mHeaderText) { mHeaderText.Text = mReleaseLabel; } // Now call the callback releaseToRefreshImpl(); } public void reset() { if (null != mHeaderText) { mHeaderText.Text = mPullLabel; } mHeaderImage.Visibility = ViewStates.Visible; if (mUseIntrinsicAnimation) { ((AnimationDrawable)mHeaderImage.Drawable).Stop(); } else { // Now call the callback resetImpl(); } if (null != mSubHeaderText) { if (TextUtils.IsEmpty(mSubHeaderText.Text)) { mSubHeaderText.Visibility = ViewStates.Gone; } else { mSubHeaderText.Visibility = ViewStates.Visible; } } } //@Override public void setLastUpdatedLabel(string label) { setSubHeaderText(label); } public void setLoadingDrawable(Drawable imageDrawable) { // Set Drawable mHeaderImage.SetImageDrawable(imageDrawable); mUseIntrinsicAnimation = (imageDrawable is AnimationDrawable); // Now call the callback onLoadingDrawableSet(imageDrawable); } public void setPullLabel(string pullLabel) { mPullLabel = pullLabel; } public void setRefreshingLabel(string refreshingLabel) { mRefreshingLabel = refreshingLabel; } public void setReleaseLabel(string releaseLabel) { mReleaseLabel = releaseLabel; } //@Override public void setTextTypeface(Typeface tf) { mHeaderText.Typeface = tf; } public void showInvisibleViews() { if (ViewStates.Invisible == mHeaderText.Visibility) { mHeaderText.Visibility = ViewStates.Visible; } if (ViewStates.Invisible == mHeaderProgress.Visibility) { mHeaderProgress.Visibility = ViewStates.Visible; } if (ViewStates.Invisible == mHeaderImage.Visibility) { mHeaderImage.Visibility = ViewStates.Visible; } if (ViewStates.Invisible == mSubHeaderText.Visibility) { mSubHeaderText.Visibility = ViewStates.Visible; } } /** * Callbacks for derivative Layouts */ protected abstract int getDefaultDrawableResId(); protected abstract void onLoadingDrawableSet(Drawable imageDrawable); protected abstract void onPullImpl(float scaleOfLayout); protected abstract void pullToRefreshImpl(); protected abstract void refreshingImpl(); protected abstract void releaseToRefreshImpl(); protected abstract void resetImpl(); private void setSubHeaderText(string label) { if (null != mSubHeaderText) { if (TextUtils.IsEmpty(label)) { mSubHeaderText.Visibility = ViewStates.Gone; } else { mSubHeaderText.Text = label; // Only set it to Visible if we're GONE, otherwise VISIBLE will // be set soon if (ViewStates.Gone == mSubHeaderText.Visibility) { mSubHeaderText.Visibility = ViewStates.Visible; } } } } private void setSubTextAppearance(int value) { if (null != mSubHeaderText) { mSubHeaderText.SetTextAppearance(this.Context, value); } } private void setSubTextColor(ColorStateList color) { if (null != mSubHeaderText) { mSubHeaderText.SetTextColor(color); } } private void setTextAppearance(int value) { if (null != mHeaderText) { mHeaderText.SetTextAppearance(this.Context, value); } if (null != mSubHeaderText) { mSubHeaderText.SetTextAppearance(this.Context, value); } } private void setTextColor(ColorStateList color) { if (null != mHeaderText) { mHeaderText.SetTextColor(color); } if (null != mSubHeaderText) { mSubHeaderText.SetTextColor(color); } } } }
// 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.Linq; using System.Text; using Microsoft.Cci.Comparers; using Microsoft.Cci.Extensions; using Microsoft.Cci.Writers.Syntax; namespace Microsoft.Cci.Writers.CSharp { public partial class CSDeclarationWriter { // writeInline => [ , , ] vs []\n[]\n public void WriteAttributes(IEnumerable<ISecurityAttribute> securityAttributes, bool writeInline = false, string prefix = "") { if (!securityAttributes.SelectMany(s => s.Attributes).Any(IncludeAttribute)) return; securityAttributes = securityAttributes.OrderBy(s => s.Action.ToString()); bool first = true; WriteSymbol("["); foreach (ISecurityAttribute securityAttribute in securityAttributes) { foreach (ICustomAttribute attribute in securityAttribute.Attributes) { if (!first) { if (writeInline) { WriteSymbol(",", addSpace: true); } else { WriteSymbol("]"); _writer.WriteLine(); WriteSymbol("["); } } WriteAttribute(attribute, prefix, securityAttribute.Action); first = false; } } WriteSymbol("]"); if (!writeInline) _writer.WriteLine(); } private static FakeCustomAttribute s_methodImpl = new FakeCustomAttribute("System.Runtime.CompilerServices", "MethodImpl"); private static FakeCustomAttribute s_dllImport = new FakeCustomAttribute("System.Runtime.InteropServices", "DllImport"); private void WriteMethodPseudoCustomAttributes(IMethodDefinition method) { // Decided not to put more information (parameters) here as that would have introduced a lot of noise. if (method.IsPlatformInvoke) { if (IncludeAttribute(s_dllImport)) { string typeName = _forCompilation ? s_dllImport.FullTypeName : s_dllImport.TypeName; WriteFakeAttribute(typeName, writeInline: true, parameters: "\"" + method.PlatformInvokeData.ImportModule.Name.Value + "\""); } } var ops = CreateMethodImplOptions(method); if (ops != default(System.Runtime.CompilerServices.MethodImplOptions)) { if (IncludeAttribute(s_methodImpl)) { string typeName = _forCompilation ? s_methodImpl.FullTypeName : s_methodImpl.TypeName; string enumValue = _forCompilation ? string.Join("|", ops.ToString().Split('|').Select(x => "System.Runtime.CompilerServices.MethodImplOptions." + x)) : ops.ToString(); WriteFakeAttribute(typeName, writeInline: true, parameters: enumValue); } } } private System.Runtime.CompilerServices.MethodImplOptions CreateMethodImplOptions(IMethodDefinition method) { // Some options are not exposed in portable contracts. PortingHelpers.cs exposes the missing constants. System.Runtime.CompilerServices.MethodImplOptions options = default(System.Runtime.CompilerServices.MethodImplOptions); if (method.IsUnmanaged) options |= System.Runtime.CompilerServices.MethodImplOptionsEx.Unmanaged; if (method.IsForwardReference) options |= System.Runtime.CompilerServices.MethodImplOptionsEx.ForwardRef; if (method.PreserveSignature) options |= System.Runtime.CompilerServices.MethodImplOptions.PreserveSig; if (method.IsRuntimeInternal) options |= System.Runtime.CompilerServices.MethodImplOptionsEx.InternalCall; if (method.IsSynchronized) options |= System.Runtime.CompilerServices.MethodImplOptionsEx.Synchronized; if (method.IsNeverInlined) options |= System.Runtime.CompilerServices.MethodImplOptions.NoInlining; if (method.IsAggressivelyInlined) options |= System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining; if (method.IsNeverOptimized) options |= System.Runtime.CompilerServices.MethodImplOptions.NoOptimization; return options; } public void WriteAttributes(IEnumerable<ICustomAttribute> attributes, bool writeInline = false, string prefix = null) { attributes = attributes.Where(IncludeAttribute); if (!attributes.Any()) return; attributes = attributes.OrderBy(a => a, new AttributeComparer(_filter, _forCompilation)); bool first = true; WriteSymbol("["); foreach (ICustomAttribute attribute in attributes) { if (!first) { if (writeInline) { WriteSymbol(",", addSpace: true); } else { WriteSymbol("]"); _writer.WriteLine(); WriteSymbol("["); } } WriteAttribute(attribute, prefix); first = false; } WriteSymbol("]"); if (!writeInline) _writer.WriteLine(); } public void WriteAttribute(ICustomAttribute attribute, string prefix = null, SecurityAction action = SecurityAction.ActionNil) { if (!string.IsNullOrEmpty(prefix)) { Write(prefix); WriteSymbol(":"); } WriteTypeName(attribute.Constructor.ContainingType, noSpace: true); // Should we strip Attribute from name? if (attribute.NumberOfNamedArguments > 0 || attribute.Arguments.Any() || action != SecurityAction.ActionNil) { WriteSymbol("("); bool first = true; if (action != SecurityAction.ActionNil) { Write("System.Security.Permissions.SecurityAction." + action.ToString()); first = false; } foreach (IMetadataExpression arg in attribute.Arguments) { if (!first) WriteSymbol(",", true); WriteMetadataExpression(arg); first = false; } foreach (IMetadataNamedArgument namedArg in attribute.NamedArguments) { if (!first) WriteSymbol(",", true); WriteIdentifier(namedArg.ArgumentName); WriteSymbol("="); WriteMetadataExpression(namedArg.ArgumentValue); first = false; } WriteSymbol(")"); } } private void WriteFakeAttribute(string typeName, params string[] parameters) { WriteFakeAttribute(typeName, false, parameters); } private void WriteFakeAttribute(string typeName, bool writeInline, params string[] parameters) { // These fake attributes are really only useful for the compilers if (!_forCompilation && !_includeFakeAttributes) return; if (_forCompilationIncludeGlobalprefix) typeName = "global::" + typeName; WriteSymbol("["); _writer.WriteTypeName(typeName); if (parameters.Length > 0) { WriteSymbol("("); _writer.WriteList(parameters, p => { if (_forCompilationIncludeGlobalprefix) p = "global::" + p; Write(p); }); WriteSymbol(")"); } WriteSymbol("]"); if (!writeInline) _writer.WriteLine(); } private void WriteMetadataExpression(IMetadataExpression expression) { IMetadataConstant constant = expression as IMetadataConstant; if (constant != null) { WriteMetadataConstant(constant); return; } IMetadataCreateArray array = expression as IMetadataCreateArray; if (array != null) { WriteMetadataArray(array); return; } IMetadataTypeOf type = expression as IMetadataTypeOf; if (type != null) { WriteKeyword("typeof", noSpace: true); WriteSymbol("("); WriteTypeName(type.TypeToGet, noSpace: true); WriteSymbol(")"); return; } throw new NotSupportedException("IMetadataExpression type not supported"); } private void WriteMetadataConstant(IMetadataConstant constant, ITypeReference constantType = null) { object value = constant.Value; ITypeReference type = (constantType == null ? constant.Type : constantType); if (value == null) { if (type.IsValueType) { // Write default(T) for value types WriteDefaultOf(type); } else { WriteKeyword("null", noSpace: true); } } else if (type.ResolvedType.IsEnum) { //TODO: Do a better job translating the Enum value. WriteSymbol("("); WriteTypeName(type, noSpace: true); WriteSymbol(")"); WriteSymbol("("); // Wrap value in parens to avoid issues with negative values Write(value.ToString()); WriteSymbol(")"); } else if (value is string) { Write(QuoteString((string)value)); } else if (value is char) { Write(String.Format("'{0}'", EscapeChar((char)value, false))); } else if (value is double) { double val = (double)value; if (double.IsNegativeInfinity(val)) Write("-1.0 / 0.0"); else if (double.IsPositiveInfinity(val)) Write("1.0 / 0.0"); else if (double.IsNaN(val)) Write("0.0 / 0.0"); else Write(((double)value).ToString("R", CultureInfo.InvariantCulture)); } else if (value is float) { float val = (float)value; if (float.IsNegativeInfinity(val)) Write("-1.0f / 0.0f"); else if (float.IsPositiveInfinity(val)) Write("1.0f / 0.0f"); else if (float.IsNaN(val)) Write("0.0f / 0.0f"); else Write(((float)value).ToString("R", CultureInfo.InvariantCulture) + "f"); } else if (value is bool) { if ((bool)value) WriteKeyword("true", noSpace: true); else WriteKeyword("false", noSpace: true); } else if (value is int) { // int is the default and most used constant value so lets // special case int to avoid a bunch of useless casts. Write(value.ToString()); } else { // Explicitly cast the value so that we avoid any signed/unsigned resolution issues WriteSymbol("("); WriteTypeName(type, noSpace: true); WriteSymbol(")"); Write(value.ToString()); } // Might need to add support for other types... } private void WriteMetadataArray(IMetadataCreateArray array) { bool first = true; WriteKeyword("new"); WriteTypeName(array.Type, noSpace: true); WriteSymbol("{", addSpace: true); foreach (IMetadataExpression expr in array.Initializers) { if (first) { first = false; } else { WriteSymbol(",", true); } WriteMetadataExpression(expr); } WriteSymbol("}"); } private static string QuoteString(string str) { StringBuilder sb = new StringBuilder(str.Length + 4); sb.Append("\""); foreach (char ch in str) { sb.Append(EscapeChar(ch, true)); } sb.Append("\""); return sb.ToString(); } private static string EscapeChar(char c, bool inString) { switch (c) { case '\r': return @"\r"; case '\n': return @"\n"; case '\f': return @"\f"; case '\t': return @"\t"; case '\v': return @"\v"; case '\0': return @"\0"; case '\a': return @"\a"; case '\b': return @"\b"; case '\\': return @"\\"; case '\'': return inString ? "'" : @"\'"; case '"': return inString ? "\\\"" : "\""; } var cat = CharUnicodeInfo.GetUnicodeCategory(c); if (cat == UnicodeCategory.Control || cat == UnicodeCategory.LineSeparator || cat == UnicodeCategory.Format || cat == UnicodeCategory.Surrogate || cat == UnicodeCategory.PrivateUse || cat == UnicodeCategory.OtherNotAssigned) return String.Format("\\u{0:X4}", (int)c); return c.ToString(); } private static bool ExcludeSpecialAttribute(ICustomAttribute c) { string typeName = c.FullName(); switch (typeName) { case "System.Runtime.CompilerServices.FixedBufferAttribute": return true; case "System.ParamArrayAttribute": return true; case "System.Reflection.DefaultMemberAttribute": return true; case "System.Reflection.AssemblyKeyFileAttribute": return true; case "System.Reflection.AssemblyDelaySignAttribute": return true; case "System.Runtime.CompilerServices.ExtensionAttribute": return true; case "System.Runtime.CompilerServices.DynamicAttribute": return true; } return false; } private static bool IsDynamic(IEnumerable<ICustomAttribute> attributes) { foreach (var attribute in attributes) { if (attribute.Type.AreEquivalent("System.Runtime.CompilerServices.DynamicAttribute")) return true; } return false; } private bool IncludeAttribute(ICustomAttribute attribute) { if (ExcludeSpecialAttribute(attribute)) return false; return _filter.Include(attribute); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; using System.Xml.Serialization; using Apache.Geode.Client.Tests; namespace Apache.Geode.Client.FwkLib { using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; public class PutTask<TKey, TVal> : ClientTask { #region Private members private IRegion<TKey, TVal> m_region; private int m_MaxKeys; private List<IDictionary<TKey, TVal>> m_maps; private Int32 m_update; private Int32 m_cnt; private bool m_isCreate; #endregion public PutTask(IRegion<TKey, TVal> region, int keyCnt, List<IDictionary<TKey, TVal>> maps, bool isCreate) : base() { m_region = region; m_MaxKeys = keyCnt; m_maps = maps; m_update = 0; m_cnt = 0; m_isCreate = isCreate; } public override void DoTask(int iters, object data) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("PutTask::DoTask:"); Int32 localcnt = m_cnt; Interlocked.Increment(ref m_cnt); int offset = Util.Rand(m_MaxKeys); int count = offset; while (Running && (iters-- != 0)) { int idx = count % m_MaxKeys; TKey key = default(TKey); try { key = (TKey)(object)("AAAAAA" + localcnt + idx.ToString("D10")); DeltaTestImpl oldVal = (m_maps[localcnt])[key] as DeltaTestImpl; if (oldVal == null) { Util.Log(Util.LogLevel.Error, "oldDelta Cannot be null"); } DeltaTestImpl obj = new DeltaTestImpl(oldVal); obj.SetIntVar(oldVal.GetIntVar() + 1); m_region[key] = (TVal)(object)obj; Interlocked.Increment(ref m_update); Util.BBSet("ToDeltaBB", key.ToString(), oldVal.GetToDeltaCounter()); bool removeKey = (m_maps[localcnt]).Remove(key); if (removeKey) { (m_maps[localcnt]).Add(key, (TVal)(object)obj); } } catch (Exception ex) { Util.Log(Util.LogLevel.Error, "Exception while putting key[{0}] for region {1} in iteration " + "{2}: {3}", key, m_region.Name, (count - offset), ex); throw; } count++; //if ((count % 1000) == 0) //{ // Util.Log("PutsTask::DoTask: Intermediate: Ran for 1000 iterations."); //} } //Util.Log("PutsTask::DoTask: Ran for {0} iterations.", count); Interlocked.Add(ref m_iters, count - offset); } public void dumpToBB() { Int32 localcnt = m_cnt; Int32 size = m_maps.Count; Int32 count = 0; Int32 i = 0; while (i < size) { count += m_maps[i].Count; foreach (KeyValuePair<TKey, TVal> item in m_maps[i]) { TKey key = (TKey)(object)item.Key; DeltaTestImpl value = item.Value as DeltaTestImpl; ; Util.BBSet("ToDeltaBB", key.ToString(), value.GetToDeltaCounter()); } i++; } Util.BBSet("MapCount", "size", count); Util.BBSet("DeltaBB", "UPDATECOUNT", m_update); } } public class CreateTask<TKey, TVal> : ClientTask { #region Private members private IRegion<TKey, TVal> m_region; private int m_MaxKeys; private List<IDictionary<TKey, TVal>> m_maps; private Int32 m_create; private Int32 m_cnt; #endregion public CreateTask(IRegion<TKey, TVal> region, int keyCnt, List<IDictionary<TKey, TVal>> maps) : base() { m_region = region; m_MaxKeys = keyCnt; m_maps = maps; m_create = 0; m_cnt = 0; } public override void DoTask(int iters, object data) { Int32 localcnt = m_cnt; Interlocked.Increment(ref m_cnt); IDictionary<TKey, TVal> hmoc = new Dictionary<TKey, TVal>(); lock (m_maps) { m_maps.Add(hmoc); } int offset = Util.Rand(m_MaxKeys); int count = offset; Util.Log("CreateTask::DoTask: starting {0} iterations.", iters); while (Running && (iters-- != 0)) { int idx = count % m_MaxKeys; TKey key = default(TKey); try { key = (TKey)(object)("AAAAAA" + localcnt + idx.ToString("D10")); TVal obj = (TVal)(object)(new DeltaTestImpl(0, "delta")); m_region.Add(key, obj); Interlocked.Increment(ref m_create); (m_maps[localcnt]).Add(key, obj); } catch (Exception ex) { Util.Log(Util.LogLevel.Error, "Exception while creating key[{0}] for region {1} in iteration " + "{2}: {3}", key, m_region.Name, (count - offset), ex); throw; } count++; } Interlocked.Add(ref m_iters, count - offset); } public void dumpToBB() { Util.BBSet("DeltaBB", "CREATECOUNT", m_create); Util.BBSet("DeltaBB", "DESTROYCOUNT", 0); } } public class EntryTask<TKey, TVal> : ClientTask { #region Private members private IRegion<TKey, TVal> m_region; private int m_MaxKeys; private List<IDictionary<TKey, TVal>> m_maps; private Int32 m_create; private Int32 m_update; private Int32 m_destroy; private Int32 m_invalidate; private Int32 m_cnt; bool m_isDestroy; private object CLASS_LOCK = new object(); #endregion public EntryTask(IRegion<TKey, TVal> region, int keyCnt, List<IDictionary<TKey, TVal>> maps) : base() { m_region = region; m_MaxKeys = keyCnt; m_maps = maps; m_create = 0; m_update = 0; m_destroy = 0; m_invalidate = 0; m_cnt = 0; m_isDestroy = true; } DeltaTestImpl getLatestDelta(TKey key, Int32 localcnt, bool isCreate) { DeltaTestImpl oldValue = (m_maps[localcnt])[key] as DeltaTestImpl; if (oldValue == null) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("oldDelta cannot be null"); } DeltaTestImpl obj = new DeltaTestImpl(oldValue.GetIntVar() + 1, "delta"); if (!isCreate) { obj.SetIntVar(oldValue.GetIntVar() + 1); } return obj; } public override void DoTask(int iters, object data) { Int32 localcnt = m_cnt; Interlocked.Increment(ref m_cnt); IDictionary<TKey, TVal> hmoc = new Dictionary<TKey, TVal>(); lock (m_maps) { m_maps.Add(hmoc); } int offset = Util.Rand(m_MaxKeys); int count = offset; TKey key = default(TKey); Util.Log("EntryTask::DoTask: starting {0} iterations.", iters); while (Running && (iters-- != 0)) { int idx = count % m_MaxKeys; key = (TKey)(object)("AAAAAA" + localcnt + idx.ToString("D10")); string opcode = FwkTest<TKey, TVal>.CurrentTest.GetStringValue("entryOps"); if (opcode == null) opcode = "no-opcode"; if (opcode == "put") { lock (CLASS_LOCK) { DeltaTestImpl newValue = null; if (m_region.ContainsKey(key)) { DeltaTestImpl oldValue = m_region[key] as DeltaTestImpl; if (oldValue == null) { newValue = getLatestDelta(key, localcnt, false); m_region[key] = (TVal)(object)newValue; } else { newValue = new DeltaTestImpl(oldValue); newValue.SetIntVar(oldValue.GetIntVar() + 1); m_region[key] = (TVal)(object)newValue; } Interlocked.Increment(ref m_update); //Util.BBSet("ToDeltaBB", key.ToString(), newValue.GetToDeltaCounter()); } else { newValue = getLatestDelta(key, localcnt, true); m_region.Add(key, (TVal)(object)newValue); Interlocked.Increment(ref m_create); } //(m_maps[localcnt]).Add(key, newValue); m_maps[localcnt][key] = (TVal)(object)newValue; } } else if (opcode == "destroy") { DeltaTestImpl oldValue = null; if (m_region.ContainsKey(key)) { if ((oldValue = m_region[key] as DeltaTestImpl) == null) { if (m_isDestroy) { m_region.Remove(key); (m_maps[localcnt]).Remove(key); } } else { m_maps[localcnt][key] = (TVal)(object)oldValue; m_region.Remove(key); //(m_maps[localcnt]).Remove(key); } Interlocked.Increment(ref m_destroy); } } else if (opcode == "invalidate") { DeltaTestImpl oldValue = null; if (m_region.ContainsKey(key)) { if ((oldValue = m_region[key] as DeltaTestImpl) != null) { m_maps[localcnt].Add(key, (TVal)(object)oldValue); m_region.Invalidate(key); Interlocked.Increment(ref m_invalidate); m_maps[localcnt].Add(key, default(TVal)); } } } } Interlocked.Add(ref m_iters, count - offset); } public void dumpToBB() { Int32 localcnt = m_cnt; Int32 size = m_maps.Count; Int32 count = 0; Int32 i = 0; while(i < size) { count += m_maps[i].Count; foreach (KeyValuePair<TKey, TVal> item in m_maps[i]) { TKey key = (TKey)(object)item.Key; DeltaTestImpl value = item.Value as DeltaTestImpl; Util.BBSet("ToDeltaBB", key.ToString(), value.GetToDeltaCounter()); } i++; } Util.BBSet("MapCount", "size", count); Int32 createCnt = (Int32)Util.BBGet("DeltaBB", "CREATECOUNT"); Util.BBSet("DeltaBB", "CREATECOUNT", createCnt + m_create); Util.BBSet("DeltaBB", "UPDATECOUNT", m_update); Util.BBSet("DeltaBB", "DESTROYCOUNT", m_destroy); } } public class DeltaTest<TKey, TVal> : FwkTest<TKey, TVal> { protected TKey[] m_keysA; protected int m_maxKeys; protected int m_keyIndexBegin; protected TVal[] m_cValues; protected int m_maxValues; protected const string ClientCount = "clientCount"; protected const string TimedInterval = "timedInterval"; protected const string DistinctKeys = "distinctKeys"; protected const string NumThreads = "numThreads"; protected const string ValueSizes = "valueSizes"; protected const string OpsSecond = "opsSecond"; protected const string KeyType = "keyType"; protected const string KeySize = "keySize"; protected const string KeyIndexBegin = "keyIndexBegin"; protected const string RegisterKeys = "registerKeys"; protected const string RegisterRegex = "registerRegex"; protected const string UnregisterRegex = "unregisterRegex"; protected const string ExpectedCount = "expectedCount"; protected const string InterestPercent = "interestPercent"; protected const string KeyStart = "keyStart"; protected const string KeyEnd = "keyEnd"; protected char m_keyType = 'i'; protected static List<IDictionary<TKey, TVal>> mapList = new List<IDictionary<TKey, TVal>>(); private static bool isObjectRegistered = false; protected void ClearKeys() { if (m_keysA != null) { for (int i = 0; i < m_keysA.Length; i++) { if (m_keysA[i] != null) { //m_keysA[i].Dispose(); m_keysA[i] = default(TKey); } } m_keysA = null; m_maxKeys = 0; } } protected int InitKeys(bool useDefault) { string typ = GetStringValue(KeyType); // int is only value to use char newType = (typ == null || typ.Length == 0) ? 's' : typ[0]; int low = GetUIntValue(KeyIndexBegin); low = (low > 0) ? low : 0; int numKeys = GetUIntValue(DistinctKeys); // check distinct keys first if (numKeys <= 0) { if (useDefault) { numKeys = 5000; } else { //FwkSevere("Failed to initialize keys with numKeys: {0}", numKeys); return numKeys; } } int high = numKeys + low; FwkInfo("InitKeys:: numKeys: {0}; low: {1}", numKeys, low); if ((newType == m_keyType) && (numKeys == m_maxKeys) && (m_keyIndexBegin == low)) { return numKeys; } ClearKeys(); m_maxKeys = numKeys; m_keyIndexBegin = low; m_keyType = newType; if (m_keyType == 'i') { InitIntKeys(low, high); } else { int keySize = GetUIntValue(KeySize); keySize = (keySize > 0) ? keySize : 10; string keyBase = new string('A', keySize); InitStrKeys(low, high, keyBase); } for (int j = 0; j < numKeys; j++) { int randIndx = Util.Rand(numKeys); if (randIndx != j) { TKey tmp = m_keysA[j]; m_keysA[j] = m_keysA[randIndx]; m_keysA[randIndx] = tmp; } } return m_maxKeys; } protected int InitKeys() { return InitKeys(true); } protected void InitStrKeys(int low, int high, string keyBase) { m_keysA = (TKey[])(object)new String[m_maxKeys]; FwkInfo("m_maxKeys: {0}; low: {1}; high: {2}", m_maxKeys, low, high); for (int i = low; i < high; i++) { m_keysA[i - low] = (TKey)(object)(keyBase + i.ToString("D10")); } } protected void InitIntKeys(int low, int high) { m_keysA = (TKey[])(object)new Int32[m_maxKeys]; FwkInfo("m_maxKeys: {0}; low: {1}; high: {2}", m_maxKeys, low, high); for (int i = low; i < high; i++) { m_keysA[i - low] = (TKey)(object)i; } } protected IRegion<TKey,TVal> GetRegion() { return GetRegion(null); } protected IRegion<TKey, TVal> GetRegion(string regionName) { IRegion<TKey, TVal> region; if (regionName == null) { region = GetRootRegion(); if (region == null) { IRegion<TKey, TVal>[] rootRegions = CacheHelper<TKey, TVal>.DCache.RootRegions<TKey, TVal>(); if (rootRegions != null && rootRegions.Length > 0) { region = rootRegions[Util.Rand(rootRegions.Length)]; } } } else { region = CacheHelper<TKey, TVal>.GetRegion(regionName); } return region; } public DeltaTest() { //FwkInfo("In DeltaTest()"); } public static ICacheListener<TKey, TVal> CreateDeltaValidationCacheListener() { return new DeltaClientValidationListener<TKey, TVal>(); } public virtual void DoCreateRegion() { FwkInfo("In DoCreateRegion()"); try { if (!isObjectRegistered) { CacheHelper<TKey, TVal>.DCache.TypeRegistry.RegisterType(DeltaTestImpl.CreateDeserializable, 0x1E); CacheHelper<TKey, TVal>.DCache.TypeRegistry.RegisterType(TestObject1.CreateDeserializable, 0x1F); isObjectRegistered = true; } IRegion<TKey, TVal> region = CreateRootRegion(); if (region == null) { FwkException("DoCreateRegion() could not create region."); } FwkInfo("DoCreateRegion() Created region '{0}'", region.Name); } catch (Exception ex) { FwkException("DoCreateRegion() Caught Exception: {0}", ex); } FwkInfo("DoCreateRegion() complete."); } public virtual void DoCreatePool() { FwkInfo("In DoCreatePool()"); try { CreatePool(); } catch (Exception ex) { FwkException("DoCreatePool() Caught Exception: {0}", ex); } FwkInfo("DoCreatePool() complete."); } public void DoRegisterAllKeys() { FwkInfo("In DoRegisterAllKeys()"); try { IRegion<TKey, TVal> region = GetRegion(); FwkInfo("DoRegisterAllKeys() region name is {0}", region.Name); bool isDurable = GetBoolValue("isDurableReg"); ResetKey("getInitialValues"); bool isGetInitialValues = GetBoolValue("getInitialValues"); region.GetSubscriptionService().RegisterAllKeys(isDurable, isGetInitialValues); } catch (Exception ex) { FwkException("DoRegisterAllKeys() Caught Exception: {0}", ex); } FwkInfo("DoRegisterAllKeys() complete."); } public void DoPuts() { FwkInfo("In DoPuts()"); try { IRegion<TKey, TVal> region = GetRegion(); int numClients = GetUIntValue(ClientCount); string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes); int timedInterval = GetTimeValue(TimedInterval) * 1000; if (timedInterval <= 0) { timedInterval = 5000; } int maxTime = 10 * timedInterval; // Loop over key set sizes ResetKey(DistinctKeys); int numKeys; while ((numKeys = InitKeys(false)) > 0) { // keys loop // Loop over value sizes ResetKey(NumThreads); int numThreads; while ((numThreads = GetUIntValue(NumThreads)) > 0) { PutTask<TKey, TVal> puts = new PutTask<TKey, TVal>(region, numKeys / numThreads, mapList, true); FwkInfo("Running timed task "); try { RunTask(puts, numThreads, -1, timedInterval, maxTime, null); } catch (ClientTimeoutException) { FwkException("In DoPuts() Timed run timed out."); } puts.dumpToBB(); Thread.Sleep(3000); // Put a marker of inactivity in the stats } Thread.Sleep(3000); // Put a marker of inactivity in the stats } // keys loop } catch (Exception ex) { FwkException("DoPuts() Caught Exception: {0}", ex); } Thread.Sleep(3000); // Put a marker of inactivity in the stats FwkInfo("DoPuts() complete."); } public void DoPopulateRegion() { FwkInfo("In DoPopulateRegion()"); try { IRegion<TKey, TVal> region = GetRegion(); ResetKey(DistinctKeys); int numKeys = InitKeys(); ResetKey(NumThreads); int numThreads = GetUIntValue(NumThreads); CreateTask<TKey, TVal> creates = new CreateTask<TKey, TVal>(region, (numKeys / numThreads), mapList); FwkInfo("Populating region."); RunTask(creates, numThreads, (numKeys / numThreads), -1, -1, null); creates.dumpToBB(); } catch (Exception ex) { FwkException("DoPopulateRegion() Caught Exception: {0}", ex); } FwkInfo("DoPopulateRegion() complete."); } public void DoEntryOperation() { FwkInfo("In DoEntryOperation"); try { IRegion<TKey, TVal> region = GetRegion(); int numClients = GetUIntValue(ClientCount); string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes); int timedInterval = GetTimeValue(TimedInterval) * 1000; { timedInterval = 5000; } int maxTime = 10 * timedInterval; // Loop over key set sizes ResetKey(DistinctKeys); int numKeys = GetUIntValue(DistinctKeys); ResetKey(NumThreads); int numThreads; while ((numThreads = GetUIntValue(NumThreads)) > 0) { EntryTask<TKey, TVal> entrytask = new EntryTask<TKey, TVal>(region, numKeys / numThreads, mapList); FwkInfo("Running timed task "); try { RunTask(entrytask, numThreads, -1, timedInterval, maxTime, null); } catch (ClientTimeoutException) { FwkException("In DoPuts() Timed run timed out."); } Thread.Sleep(3000); entrytask.dumpToBB(); } } catch (Exception ex) { FwkException("DoEntryOperation() Caught Exception: {0}", ex); } FwkInfo("DoEntryOperation() complete."); } public void DoCloseCache() { FwkInfo("DoCloseCache() Closing cache and disconnecting from" + " distributed system."); CacheHelper<TKey, TVal>.Close(); } public void DoValidateDeltaTest() { FwkInfo("DoValidateDeltaTest() called."); try { IRegion<TKey, TVal> region = GetRegion(); region.GetLocalView().DestroyRegion(); TKey key = default(TKey); Int32 expectedAfterCreateEvent = (Int32)Util.BBGet("DeltaBB", "CREATECOUNT"); Int32 expectedAfterUpdateEvent = (Int32)Util.BBGet("DeltaBB", "UPDATECOUNT"); Int32 expectedAfterDestroyEvent = (Int32)Util.BBGet("DeltaBB", "DESTROYCOUNT"); long eventAfterCreate = (long)Util.BBGet("DeltaBB", "AFTER_CREATE_COUNT_" + Util.ClientId + "_" + region.Name); long eventAfterUpdate = (long)Util.BBGet("DeltaBB", "AFTER_UPDATE_COUNT_" + Util.ClientId + "_" + region.Name); long eventAfterDestroy = (long)Util.BBGet("DeltaBB", "AFTER_DESTROY_COUNT_" + Util.ClientId + "_" + region.Name); FwkInfo("DoValidateDeltaTest() -- eventAfterCreate {0} ,eventAfterUpdate {1} ,eventAfterDestroy {2}", eventAfterCreate, eventAfterUpdate, eventAfterDestroy); FwkInfo("DoValidateDeltaTest() -- expectedAfterCreateEvent {0} ,expectedAfterUpdateEvent {1}, expectedAfterDestroyEvent {2} ", expectedAfterCreateEvent, expectedAfterUpdateEvent, expectedAfterDestroyEvent); if (expectedAfterCreateEvent == eventAfterCreate && expectedAfterUpdateEvent == eventAfterUpdate && expectedAfterDestroyEvent == eventAfterDestroy) { DeltaClientValidationListener<TKey, TVal> cs = (region.Attributes.CacheListener) as DeltaClientValidationListener<TKey, TVal>; IDictionary<TKey, Int64> map = cs.getMap(); Int32 mapCount = map.Count; Int32 toDeltaMapCount = (Int32)Util.BBGet("MapCount", "size"); if (mapCount == toDeltaMapCount) { foreach (KeyValuePair<TKey, Int64> item in map) { key = (TKey)(object)item.Key; Int64 value = item.Value; long fromDeltaCount = (long)value; long toDeltaCount = (long)Util.BBGet("ToDeltaBB", key.ToString()); if (toDeltaCount == fromDeltaCount) { FwkInfo("DoValidateDeltaTest() Delta Count Validation success with fromDeltaCount: {0} = toDeltaCount: {1}", fromDeltaCount, toDeltaCount); } } FwkInfo("DoValidateDeltaTest() Validation success."); } else { FwkException("Validation Failed() as fromDeltaMapCount: {0} is not equal to toDeltaMapCount: {1}",mapCount,toDeltaMapCount); } } else { FwkException("Validation Failed()for Region: {0} Expected were expectedAfterCreateEvent {1} expectedAfterUpdateEvent {2} expectedAfterDestroyEvent {3} eventAfterCreate {4}, eventAfterUpdate {5} ", region.Name, expectedAfterCreateEvent, expectedAfterUpdateEvent,expectedAfterDestroyEvent, eventAfterCreate, eventAfterUpdate ,eventAfterDestroy); } } catch (Exception ex) { FwkException("DoValidateDeltaTest() Caught Exception: {0}", ex); FwkInfo("DoValidateDeltaTest() complete."); } } } }//DeltaTest end
namespace System.Workflow.ComponentModel { #region Imports using System; using System.Drawing; using System.CodeDom; using System.Collections; using System.Reflection; using System.Collections.Generic; using System.ComponentModel; using System.Drawing.Design; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Workflow.ComponentModel.Design; using System.Workflow.ComponentModel.Compiler; #endregion [SRDescription(SR.FaultHandlerActivityDescription)] [ToolboxItem(typeof(ActivityToolboxItem))] [ToolboxBitmap(typeof(FaultHandlerActivity), "Resources.Exception.png")] [SRCategory(SR.Standard)] [Designer(typeof(FaultHandlerActivityDesigner), typeof(IDesigner))] [ActivityValidator(typeof(FaultHandlerActivityValidator))] [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class FaultHandlerActivity : CompositeActivity, IActivityEventListener<ActivityExecutionStatusChangedEventArgs>, ITypeFilterProvider, IDynamicPropertyTypeProvider { public static readonly DependencyProperty FaultTypeProperty = DependencyProperty.Register("FaultType", typeof(Type), typeof(FaultHandlerActivity), new PropertyMetadata(DependencyPropertyOptions.Metadata)); internal static readonly DependencyProperty FaultProperty = DependencyProperty.Register("Fault", typeof(Exception), typeof(FaultHandlerActivity)); public FaultHandlerActivity() { } public FaultHandlerActivity(string name) : base(name) { } [Editor(typeof(TypeBrowserEditor), typeof(UITypeEditor))] [SRDescription(SR.ExceptionTypeDescr)] [MergableProperty(false)] public Type FaultType { get { return (Type)base.GetValue(FaultTypeProperty); } set { base.SetValue(FaultTypeProperty, value); } } [SRDescription(SR.FaultDescription)] [MergableProperty(false)] [ReadOnly(true)] public Exception Fault { get { return base.GetValue(FaultProperty) as Exception; } } internal void SetException(Exception e) { this.SetValue(FaultProperty, e); } protected internal override void Initialize(IServiceProvider provider) { if (this.Parent == null) throw new InvalidOperationException(SR.GetString(SR.Error_MustHaveParent)); base.Initialize(provider); } protected internal override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { return SequenceHelper.Execute(this, executionContext); } protected internal override ActivityExecutionStatus Cancel(ActivityExecutionContext executionContext) { return SequenceHelper.Cancel(this, executionContext); } void IActivityEventListener<ActivityExecutionStatusChangedEventArgs>.OnEvent(Object sender, ActivityExecutionStatusChangedEventArgs e) { SequenceHelper.OnEvent(this, sender, e); } protected internal override void OnActivityChangeRemove(ActivityExecutionContext executionContext, Activity removedActivity) { SequenceHelper.OnActivityChangeRemove(this, executionContext, removedActivity); } protected internal override void OnWorkflowChangesCompleted(ActivityExecutionContext executionContext) { SequenceHelper.OnWorkflowChangesCompleted(this, executionContext); } #region ITypeFilterProvider Members bool ITypeFilterProvider.CanFilterType(Type type, bool throwOnError) { bool isAssignable = TypeProvider.IsAssignable(typeof(Exception), type); if (throwOnError && !isAssignable) throw new Exception(SR.GetString(SR.Error_ExceptionTypeNotException, type, "Type")); return isAssignable; } string ITypeFilterProvider.FilterDescription { get { return SR.GetString(SR.FilterDescription_FaultHandlerActivity); } } #endregion #region IDynamicPropertyTypeProvider Members Type IDynamicPropertyTypeProvider.GetPropertyType(IServiceProvider serviceProvider, string propertyName) { if (propertyName == null) throw new ArgumentNullException("propertyName"); Type returnType = null; if (string.Equals(propertyName, "Fault", StringComparison.Ordinal)) { returnType = this.FaultType; if (returnType == null) returnType = typeof(Exception); } return returnType; } AccessTypes IDynamicPropertyTypeProvider.GetAccessType(IServiceProvider serviceProvider, string propertyName) { if (propertyName == null) throw new ArgumentNullException("propertyName"); if (propertyName.Equals("Fault", StringComparison.Ordinal)) return AccessTypes.Write; else return AccessTypes.Read; } #endregion } internal sealed class FaultHandlerActivityValidator : CompositeActivityValidator { public override ValidationErrorCollection Validate(ValidationManager manager, object obj) { ValidationErrorCollection validationErrors = base.Validate(manager, obj); FaultHandlerActivity exceptionHandler = obj as FaultHandlerActivity; if (exceptionHandler == null) throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(FaultHandlerActivity).FullName), "obj"); // check parent must be exception handler if (!(exceptionHandler.Parent is FaultHandlersActivity)) validationErrors.Add(new ValidationError(SR.GetString(SR.Error_FaultHandlerActivityParentNotFaultHandlersActivity), ErrorNumbers.Error_FaultHandlerActivityParentNotFaultHandlersActivity)); // validate exception property ITypeProvider typeProvider = manager.GetService(typeof(ITypeProvider)) as ITypeProvider; if (typeProvider == null) throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName)); // Validate the required Type property ValidationError error = null; if (exceptionHandler.FaultType == null) { error = new ValidationError(SR.GetString(SR.Error_TypePropertyInvalid, "FaultType"), ErrorNumbers.Error_PropertyNotSet); error.PropertyName = "FaultType"; validationErrors.Add(error); } else if (!TypeProvider.IsAssignable(typeof(Exception), exceptionHandler.FaultType)) { error = new ValidationError(SR.GetString(SR.Error_TypeTypeMismatch, new object[] { "FaultType", typeof(Exception).FullName }), ErrorNumbers.Error_TypeTypeMismatch); error.PropertyName = "FaultType"; validationErrors.Add(error); } // Generate a warning for unrechable code, if the catch type is all and this is not the last exception handler. /*if (exceptionHandler.FaultType == typeof(System.Exception) && exceptionHandler.Parent is FaultHandlersActivity && ((FaultHandlersActivity)exceptionHandler.Parent).Activities.IndexOf(exceptionHandler) != ((FaultHandlersActivity)exceptionHandler.Parent).Activities.Count - 1) { error = new ValidationError(SR.GetString(SR.Error_FaultHandlerActivityAllMustBeLast), ErrorNumbers.Error_FaultHandlerActivityAllMustBeLast, true); error.PropertyName = "FaultType"; validationErrors.Add(error); }*/ if (exceptionHandler.EnabledActivities.Count == 0) validationErrors.Add(new ValidationError(SR.GetString(SR.Warning_EmptyBehaviourActivity, typeof(FaultHandlerActivity).FullName, exceptionHandler.QualifiedName), ErrorNumbers.Warning_EmptyBehaviourActivity, true)); // fault handler can not contain fault handlers, compensation handler and cancellation handler if (((ISupportAlternateFlow)exceptionHandler).AlternateFlowActivities.Count > 0) validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ModelingConstructsCanNotContainModelingConstructs), ErrorNumbers.Error_ModelingConstructsCanNotContainModelingConstructs)); return validationErrors; } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Media; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Notifications; using Umbraco.Cms.Core.Services; using Umbraco.Extensions; namespace Umbraco.Cms.Core.PropertyEditors { /// <summary> /// Represents an image cropper property editor. /// </summary> [DataEditor( Constants.PropertyEditors.Aliases.ImageCropper, "Image Cropper", "imagecropper", ValueType = ValueTypes.Json, HideLabel = false, Group = Constants.PropertyEditors.Groups.Media, Icon = "icon-crop")] public class ImageCropperPropertyEditor : DataEditor, IMediaUrlGenerator, INotificationHandler<ContentCopiedNotification>, INotificationHandler<ContentDeletedNotification>, INotificationHandler<MediaDeletedNotification>, INotificationHandler<MediaSavingNotification>, INotificationHandler<MemberDeletedNotification> { private readonly MediaFileManager _mediaFileManager; private readonly ContentSettings _contentSettings; private readonly IDataTypeService _dataTypeService; private readonly IIOHelper _ioHelper; private readonly UploadAutoFillProperties _autoFillProperties; private readonly ILogger<ImageCropperPropertyEditor> _logger; private readonly IContentService _contentService; /// <summary> /// Initializes a new instance of the <see cref="ImageCropperPropertyEditor"/> class. /// </summary> public ImageCropperPropertyEditor( IDataValueEditorFactory dataValueEditorFactory, ILoggerFactory loggerFactory, MediaFileManager mediaFileManager, IOptions<ContentSettings> contentSettings, IDataTypeService dataTypeService, IIOHelper ioHelper, UploadAutoFillProperties uploadAutoFillProperties, IContentService contentService) : base(dataValueEditorFactory) { _mediaFileManager = mediaFileManager ?? throw new ArgumentNullException(nameof(mediaFileManager)); _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); _dataTypeService = dataTypeService ?? throw new ArgumentNullException(nameof(dataTypeService)); _ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper)); _autoFillProperties = uploadAutoFillProperties ?? throw new ArgumentNullException(nameof(uploadAutoFillProperties)); _contentService = contentService; _logger = loggerFactory.CreateLogger<ImageCropperPropertyEditor>(); } public bool TryGetMediaPath(string propertyEditorAlias, object value, out string mediaPath) { if (propertyEditorAlias == Alias && GetFileSrcFromPropertyValue(value, out _, false) is var mediaPathValue && !string.IsNullOrWhiteSpace(mediaPathValue)) { mediaPath = mediaPathValue; return true; } mediaPath = null; return false; } /// <summary> /// Creates the corresponding property value editor. /// </summary> /// <returns>The corresponding property value editor.</returns> protected override IDataValueEditor CreateValueEditor() => DataValueEditorFactory.Create<ImageCropperPropertyValueEditor>(Attribute); /// <summary> /// Creates the corresponding preValue editor. /// </summary> /// <returns>The corresponding preValue editor.</returns> protected override IConfigurationEditor CreateConfigurationEditor() => new ImageCropperConfigurationEditor(_ioHelper); /// <summary> /// Gets a value indicating whether a property is an image cropper field. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if the specified property is an image cropper field; otherwise, <c>false</c>. /// </returns> private static bool IsCropperField(IProperty property) => property.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.Aliases.ImageCropper; /// <summary> /// Parses the property value into a json object. /// </summary> /// <param name="value">The property value.</param> /// <param name="writeLog">A value indicating whether to log the error.</param> /// <returns>The json object corresponding to the property value.</returns> /// <remarks>In case of an error, optionally logs the error and returns null.</remarks> private JObject GetJObject(string value, bool writeLog) { if (string.IsNullOrWhiteSpace(value)) return null; try { return JsonConvert.DeserializeObject<JObject>(value); } catch (Exception ex) { if (writeLog) _logger.LogError(ex, "Could not parse image cropper value '{Json}'", value); return null; } } /// <summary> /// The paths to all image cropper property files contained within a collection of content entities /// </summary> /// <param name="entities"></param> private IEnumerable<string> ContainedFilePaths(IEnumerable<IContentBase> entities) => entities .SelectMany(x => x.Properties) .Where(IsCropperField) .SelectMany(GetFilePathsFromPropertyValues) .Distinct(); /// <summary> /// Look through all property values stored against the property and resolve any file paths stored /// </summary> /// <param name="prop"></param> /// <returns></returns> private IEnumerable<string> GetFilePathsFromPropertyValues(IProperty prop) { //parses out the src from a json string foreach (var propertyValue in prop.Values) { //check if the published value contains data and return it var src = GetFileSrcFromPropertyValue(propertyValue.PublishedValue, out var _); if (src != null) yield return _mediaFileManager.FileSystem.GetRelativePath(src); //check if the edited value contains data and return it src = GetFileSrcFromPropertyValue(propertyValue.EditedValue, out var _); if (src != null) yield return _mediaFileManager.FileSystem.GetRelativePath(src); } } /// <summary> /// Returns the "src" property from the json structure if the value is formatted correctly /// </summary> /// <param name="propVal"></param> /// <param name="deserializedValue">The deserialized <see cref="JObject"/> value</param> /// <param name="relative">Should the path returned be the application relative path</param> /// <returns></returns> private string GetFileSrcFromPropertyValue(object propVal, out JObject deserializedValue, bool relative = true) { deserializedValue = null; if (propVal == null || !(propVal is string str)) return null; if (!str.DetectIsJson()) { // Assume the value is a plain string with the file path deserializedValue = new JObject() { { "src", str } }; } else { deserializedValue = GetJObject(str, true); } if (deserializedValue?["src"] == null) return null; var src = deserializedValue["src"].Value<string>(); return relative ? _mediaFileManager.FileSystem.GetRelativePath(src) : src; } /// <summary> /// After a content has been copied, also copy uploaded files. /// </summary> public void Handle(ContentCopiedNotification notification) { // get the image cropper field properties var properties = notification.Original.Properties.Where(IsCropperField); // copy files var isUpdated = false; foreach (var property in properties) { //copy each of the property values (variants, segments) to the destination by using the edited value foreach (var propertyValue in property.Values) { var propVal = property.GetValue(propertyValue.Culture, propertyValue.Segment); var src = GetFileSrcFromPropertyValue(propVal, out var jo); if (src == null) { continue; } var sourcePath = _mediaFileManager.FileSystem.GetRelativePath(src); var copyPath = _mediaFileManager.CopyFile(notification.Copy, property.PropertyType, sourcePath); jo["src"] = _mediaFileManager.FileSystem.GetUrl(copyPath); notification.Copy.SetValue(property.Alias, jo.ToString(), propertyValue.Culture, propertyValue.Segment); isUpdated = true; } } // if updated, re-save the copy with the updated value if (isUpdated) { _contentService.Save(notification.Copy); } } public void Handle(ContentDeletedNotification notification) => DeleteContainedFiles(notification.DeletedEntities); public void Handle(MediaDeletedNotification notification) => DeleteContainedFiles(notification.DeletedEntities); public void Handle(MemberDeletedNotification notification) => DeleteContainedFiles(notification.DeletedEntities); private void DeleteContainedFiles(IEnumerable<IContentBase> deletedEntities) { var filePathsToDelete = ContainedFilePaths(deletedEntities); _mediaFileManager.DeleteMediaFiles(filePathsToDelete); } public void Handle(MediaSavingNotification notification) { foreach (var entity in notification.SavedEntities) { AutoFillProperties(entity); } } /// <summary> /// Auto-fill properties (or clear). /// </summary> private void AutoFillProperties(IContentBase model) { var properties = model.Properties.Where(IsCropperField); foreach (var property in properties) { var autoFillConfig = _contentSettings.GetConfig(property.Alias); if (autoFillConfig == null) continue; foreach (var pvalue in property.Values) { var svalue = property.GetValue(pvalue.Culture, pvalue.Segment) as string; if (string.IsNullOrWhiteSpace(svalue)) { _autoFillProperties.Reset(model, autoFillConfig, pvalue.Culture, pvalue.Segment); } else { var jo = GetJObject(svalue, false); string src; if (jo == null) { // so we have a non-empty string value that cannot be parsed into a json object // see http://issues.umbraco.org/issue/U4-4756 // it can happen when an image is uploaded via the folder browser, in which case // the property value will be the file source eg '/media/23454/hello.jpg' and we // are fixing that anomaly here - does not make any sense at all but... bah... var dt = _dataTypeService.GetDataType(property.PropertyType.DataTypeId); var config = dt?.ConfigurationAs<ImageCropperConfiguration>(); src = svalue; var json = new { src = svalue, crops = config == null ? Array.Empty<ImageCropperConfiguration.Crop>() : config.Crops }; property.SetValue(JsonConvert.SerializeObject(json), pvalue.Culture, pvalue.Segment); } else { src = jo["src"]?.Value<string>(); } if (src == null) _autoFillProperties.Reset(model, autoFillConfig, pvalue.Culture, pvalue.Segment); else _autoFillProperties.Populate(model, autoFillConfig, _mediaFileManager.FileSystem.GetRelativePath(src), pvalue.Culture, pvalue.Segment); } } } } } }