context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace CH13___Ping_Pong
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
// the score
int m_Score1 = 0;
int m_Score2 = 0;
Texture2D m_textureNumbers;
Rectangle[] m_ScoreRect = null;
// the ball
Ball m_ball;
Texture2D m_textureBall;
// the paddles
Paddle m_paddle1;
Paddle m_paddle2;
Texture2D m_texturePaddle;
// constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <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()
{
// use a fixed frame rate of 30 frames per second
IsFixedTimeStep = true;
TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 33);
InitScreen();
InitGameObjects();
base.Initialize();
}
// screen-related init tasks
public void InitScreen()
{
// back buffer
graphics.PreferredBackBufferHeight = SCREEN_HEIGHT;
graphics.PreferredBackBufferWidth = SCREEN_WIDTH;
graphics.PreferMultiSampling = false;
graphics.ApplyChanges();
}
// game-related init tasks
public void InitGameObjects()
{
// create an instance of our ball
m_ball = new Ball();
// set the size of the ball
m_ball.Width = 15.0f;
m_ball.Height = 15.0f;
// create 2 instances of our paddle
m_paddle1 = new Paddle();
m_paddle2 = new Paddle();
// set the size of the paddles
m_paddle1.Width = 15.0f;
m_paddle1.Height = 100.0f;
m_paddle2.Width = 15.0f;
m_paddle2.Height = 100.0f;
// map the digits in the image to actual numbers
m_ScoreRect = new Rectangle[10];
for (int i = 0; i < 10; i++)
{
m_ScoreRect[i] = new Rectangle(
i * 45, // X
0, // Y
45, // Width
75); // Height
}
ResetGame();
}
// initial play state, called when the game is first
// run, and whever a player scores 10 goals
public void ResetGame()
{
// reset scores
m_Score1 = 0;
m_Score2 = 0;
// place the ball at the center of the screen
m_ball.X =
SCREEN_WIDTH / 2 - m_ball.Width / 2;
m_ball.Y =
SCREEN_HEIGHT / 2 - m_ball.Height / 2;
// set a speed and direction for the ball
m_ball.DX = 5.0f;
m_ball.DY = 4.0f;
// place the paddles at either end of the screen
m_paddle1.X = 30;
m_paddle1.Y =
SCREEN_HEIGHT / 2 - m_paddle1.Height / 2;
m_paddle2.X =
SCREEN_WIDTH - 30 - m_paddle2.Width;
m_paddle2.Y =
SCREEN_HEIGHT / 2 - m_paddle1.Height / 2;
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// load images from disk
LoadGameGraphics();
}
// load our textures from disk
protected void LoadGameGraphics()
{
// load the texture for the ball
m_textureBall =
Content.Load<Texture2D>(@"media\ball");
m_ball.Visual = m_textureBall;
// load the texture for the paddles
m_texturePaddle =
Content.Load<Texture2D>(@"media\paddle");
m_paddle1.Visual = m_texturePaddle;
m_paddle2.Visual = m_texturePaddle;
// load the texture for the score
m_textureNumbers =
Content.Load<Texture2D>(@"media\numbers");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <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)
{
// update the ball's location on the screen
MoveBall();
// update the paddles' locations on the screen
MovePaddles();
base.Update(gameTime);
}
// move the ball based on it's current DX and DY
// settings. check for collisions
private void MoveBall()
{
// actually move the ball
m_ball.X += m_ball.DX;
m_ball.Y += m_ball.DY;
// did ball touch top or bottom side?
if (m_ball.Y <= 0 ||
m_ball.Y >= SCREEN_HEIGHT - m_ball.Height)
{
// reverse vertical direction
m_ball.DY *= -1;
}
// did ball touch the left side?
if (m_ball.X <= 0)
{
// at higher speeds, the ball can leave the
// playing field, make sure that doesn't happen
m_ball.X = 0;
// increment player 2's score
m_Score2++;
// reduce speed, reverse direction
m_ball.DX = 5.0f;
}
// did ball touch the right side?
if (m_ball.X >= SCREEN_WIDTH - m_ball.Width)
{
// at higher speeds, the ball can leave the
// playing field, make sure that doesn't happen
m_ball.X = SCREEN_WIDTH - m_ball.Width;
// increment player 1's score
m_Score1++;
// reduce speed, reverse direction
m_ball.DX = -5.0f;
}
// reset game if a player scores 10 goals
if (m_Score1 > 9 || m_Score2 > 9)
{
ResetGame();
}
// did ball hit the paddle from the front?
if (CollisionOccurred())
{
// reverse hoizontal direction
m_ball.DX *= -1;
// increase the speed a little.
m_ball.DX *= 1.15f;
}
}
// check for a collision between the ball and paddles
private bool CollisionOccurred()
{
// assume no collision
bool retval = false;
// heading towards player one
if (m_ball.DX < 0)
{
Rectangle b = m_ball.Rect;
Rectangle p = m_paddle1.Rect;
retval =
b.Left < p.Right &&
b.Right > p.Left &&
b.Top < p.Bottom &&
b.Bottom > p.Top;
}
// heading towards player two
else // m_ball.DX > 0
{
Rectangle b = m_ball.Rect;
Rectangle p = m_paddle2.Rect;
retval =
b.Left < p.Right &&
b.Right > p.Left &&
b.Top < p.Bottom &&
b.Bottom > p.Top;
}
return retval;
}
// how much to move paddle each frame
private const float PADDLE_STRIDE = 10.0f;
// actually move the paddles
private void MovePaddles()
{
// define bounds for the paddles
float MIN_Y = 0.0f;
float MAX_Y = SCREEN_HEIGHT - m_paddle1.Height;
// get player input
GamePadState pad1 =
GamePad.GetState(PlayerIndex.One);
GamePadState pad2 =
GamePad.GetState(PlayerIndex.Two);
KeyboardState keyb =
Keyboard.GetState();
// check the controller, PLAYER ONE
bool PlayerUp =
pad1.DPad.Up == ButtonState.Pressed;
bool PlayerDown =
pad1.DPad.Down == ButtonState.Pressed;
// also check the keyboard, PLAYER ONE
PlayerUp |= keyb.IsKeyDown(Keys.W);
PlayerDown |= keyb.IsKeyDown(Keys.S);
// move the paddle
if (PlayerUp)
{
m_paddle1.Y -= PADDLE_STRIDE;
if (m_paddle1.Y < MIN_Y)
{
m_paddle1.Y = MIN_Y;
}
}
else if (PlayerDown)
{
m_paddle1.Y += PADDLE_STRIDE;
if (m_paddle1.Y > MAX_Y)
{
m_paddle1.Y = MAX_Y;
}
}
// check the controller, PLAYER TWO
PlayerUp =
pad2.DPad.Up == ButtonState.Pressed;
PlayerDown =
pad2.DPad.Down == ButtonState.Pressed;
// also check the keyboard, PLAYER TWO
PlayerUp |= keyb.IsKeyDown(Keys.Up);
PlayerDown |= keyb.IsKeyDown(Keys.Down);
// move the paddle
if (PlayerUp)
{
m_paddle2.Y -= PADDLE_STRIDE;
if (m_paddle2.Y < MIN_Y)
{
m_paddle2.Y = MIN_Y;
}
}
else if (PlayerDown)
{
m_paddle2.Y += PADDLE_STRIDE;
if (m_paddle2.Y > MAX_Y)
{
m_paddle2.Y = MAX_Y;
}
}
}
/// <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)
{
// our game-specific drawing logic
Render();
base.Draw(gameTime);
}
// draw the score at the specified location
public void DrawScore(float x, float y, int score)
{
spriteBatch.Draw((Texture2D)m_textureNumbers,
new Vector2(x, y),
m_ScoreRect[score % 10],
Color.Gray);
}
// actually draw our game objects
public void Render()
{
// black background
graphics.GraphicsDevice.Clear(Color.Black);
// start rendering our game graphics
spriteBatch.Begin();
// draw the score first, so the ball can
// move over it without being obscured
DrawScore((float)SCREEN_WIDTH * 0.25f,
20, m_Score1);
DrawScore((float)SCREEN_WIDTH * 0.65f,
20, m_Score2);
// render the game objects
spriteBatch.Draw((Texture2D)m_ball.Visual,
m_ball.Rect, Color.White);
spriteBatch.Draw((Texture2D)m_paddle1.Visual,
m_paddle1.Rect, Color.White);
spriteBatch.Draw((Texture2D)m_paddle2.Visual,
m_paddle2.Rect, Color.White);
// we're done drawing
spriteBatch.End();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Diagnostics;
namespace System.IO.Compression
{
internal sealed partial class WrappedStream : Stream
{
private readonly Stream _baseStream;
private readonly bool _closeBaseStream;
// Delegate that will be invoked on stream disposing
private readonly Action<ZipArchiveEntry> _onClosed;
// Instance that will be passed to _onClose delegate
private readonly ZipArchiveEntry _zipArchiveEntry;
private bool _isDisposed;
internal WrappedStream(Stream baseStream, bool closeBaseStream)
: this(baseStream, closeBaseStream, null, null) { }
private WrappedStream(Stream baseStream, bool closeBaseStream, ZipArchiveEntry entry, Action<ZipArchiveEntry> onClosed)
{
_baseStream = baseStream;
_closeBaseStream = closeBaseStream;
_onClosed = onClosed;
_zipArchiveEntry = entry;
_isDisposed = false;
}
internal WrappedStream(Stream baseStream, ZipArchiveEntry entry, Action<ZipArchiveEntry> onClosed)
: this(baseStream, false, entry, onClosed) { }
public override long Length
{
get
{
ThrowIfDisposed();
return _baseStream.Length;
}
}
public override long Position
{
get
{
ThrowIfDisposed();
return _baseStream.Position;
}
set
{
ThrowIfDisposed();
ThrowIfCantSeek();
_baseStream.Position = value;
}
}
public override bool CanRead => !_isDisposed && _baseStream.CanRead;
public override bool CanSeek => !_isDisposed && _baseStream.CanSeek;
public override bool CanWrite => !_isDisposed && _baseStream.CanWrite;
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(GetType().ToString(), SR.HiddenStreamName);
}
private void ThrowIfCantRead()
{
if (!CanRead)
throw new NotSupportedException(SR.ReadingNotSupported);
}
private void ThrowIfCantWrite()
{
if (!CanWrite)
throw new NotSupportedException(SR.WritingNotSupported);
}
private void ThrowIfCantSeek()
{
if (!CanSeek)
throw new NotSupportedException(SR.SeekingNotSupported);
}
public override int Read(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
ThrowIfCantRead();
return _baseStream.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
ThrowIfDisposed();
ThrowIfCantSeek();
return _baseStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
ThrowIfDisposed();
ThrowIfCantSeek();
ThrowIfCantWrite();
_baseStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
ThrowIfCantWrite();
_baseStream.Write(buffer, offset, count);
}
public override void Flush()
{
ThrowIfDisposed();
ThrowIfCantWrite();
_baseStream.Flush();
}
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
_onClosed?.Invoke(_zipArchiveEntry);
if (_closeBaseStream)
_baseStream.Dispose();
_isDisposed = true;
}
base.Dispose(disposing);
}
}
internal sealed partial class SubReadStream : Stream
{
private readonly long _startInSuperStream;
private long _positionInSuperStream;
private readonly long _endInSuperStream;
private readonly Stream _superStream;
private bool _canRead;
private bool _isDisposed;
public SubReadStream(Stream superStream, long startPosition, long maxLength)
{
_startInSuperStream = startPosition;
_positionInSuperStream = startPosition;
_endInSuperStream = startPosition + maxLength;
_superStream = superStream;
_canRead = true;
_isDisposed = false;
}
public override long Length
{
get
{
Contract.Ensures(Contract.Result<long>() >= 0);
ThrowIfDisposed();
return _endInSuperStream - _startInSuperStream;
}
}
public override long Position
{
get
{
Contract.Ensures(Contract.Result<long>() >= 0);
ThrowIfDisposed();
return _positionInSuperStream - _startInSuperStream;
}
set
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override bool CanRead => _superStream.CanRead && _canRead;
public override bool CanSeek => false;
public override bool CanWrite => false;
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(GetType().ToString(), SR.HiddenStreamName);
}
private void ThrowIfCantRead()
{
if (!CanRead)
throw new NotSupportedException(SR.ReadingNotSupported);
}
public override int Read(byte[] buffer, int offset, int count)
{
// parameter validation sent to _superStream.Read
int origCount = count;
ThrowIfDisposed();
ThrowIfCantRead();
if (_superStream.Position != _positionInSuperStream)
_superStream.Seek(_positionInSuperStream, SeekOrigin.Begin);
if (_positionInSuperStream + count > _endInSuperStream)
count = (int)(_endInSuperStream - _positionInSuperStream);
Debug.Assert(count >= 0);
Debug.Assert(count <= origCount);
int ret = _superStream.Read(buffer, offset, count);
_positionInSuperStream += ret;
return ret;
}
public override long Seek(long offset, SeekOrigin origin)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
public override void SetLength(long value)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SetLengthRequiresSeekingAndWriting);
}
public override void Write(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.WritingNotSupported);
}
public override void Flush()
{
ThrowIfDisposed();
throw new NotSupportedException(SR.WritingNotSupported);
}
// Close the stream for reading. Note that this does NOT close the superStream (since
// the substream is just 'a chunk' of the super-stream
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
_canRead = false;
_isDisposed = true;
}
base.Dispose(disposing);
}
}
internal sealed partial class CheckSumAndSizeWriteStream : Stream
{
private readonly Stream _baseStream;
private readonly Stream _baseBaseStream;
private long _position;
private uint _checksum;
private readonly bool _leaveOpenOnClose;
private bool _canWrite;
private bool _isDisposed;
private bool _everWritten;
// this is the position in BaseBaseStream
private long _initialPosition;
private readonly ZipArchiveEntry _zipArchiveEntry;
private readonly EventHandler _onClose;
// Called when the stream is closed.
// parameters are initialPosition, currentPosition, checkSum, baseBaseStream, zipArchiveEntry and onClose handler
private readonly Action<long, long, uint, Stream, ZipArchiveEntry, EventHandler> _saveCrcAndSizes;
// parameters to saveCrcAndSizes are
// initialPosition (initialPosition in baseBaseStream),
// currentPosition (in this CheckSumAndSizeWriteStream),
// checkSum (of data passed into this CheckSumAndSizeWriteStream),
// baseBaseStream it's a backingStream, passed here so as to avoid closure allocation,
// zipArchiveEntry passed here so as to avoid closure allocation,
// onClose handler passed here so as to avoid closure allocation
public CheckSumAndSizeWriteStream(Stream baseStream, Stream baseBaseStream, bool leaveOpenOnClose,
ZipArchiveEntry entry, EventHandler onClose,
Action<long, long, uint, Stream, ZipArchiveEntry, EventHandler> saveCrcAndSizes)
{
_baseStream = baseStream;
_baseBaseStream = baseBaseStream;
_position = 0;
_checksum = 0;
_leaveOpenOnClose = leaveOpenOnClose;
_canWrite = true;
_isDisposed = false;
_initialPosition = 0;
_zipArchiveEntry = entry;
_onClose = onClose;
_saveCrcAndSizes = saveCrcAndSizes;
}
public override long Length
{
get
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override long Position
{
get
{
Contract.Ensures(Contract.Result<long>() >= 0);
ThrowIfDisposed();
return _position;
}
set
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => _canWrite;
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(GetType().ToString(), SR.HiddenStreamName);
}
public override int Read(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.ReadingNotSupported);
}
public override long Seek(long offset, SeekOrigin origin)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
public override void SetLength(long value)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SetLengthRequiresSeekingAndWriting);
}
public override void Write(byte[] buffer, int offset, int count)
{
// we can't pass the argument checking down a level
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentNeedNonNegative);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentNeedNonNegative);
if ((buffer.Length - offset) < count)
throw new ArgumentException(SR.OffsetLengthInvalid);
Contract.EndContractBlock();
// if we're not actually writing anything, we don't want to trigger as if we did write something
ThrowIfDisposed();
Debug.Assert(CanWrite);
if (count == 0)
return;
if (!_everWritten)
{
_initialPosition = _baseBaseStream.Position;
_everWritten = true;
}
_checksum = Crc32Helper.UpdateCrc32(_checksum, buffer, offset, count);
_baseStream.Write(buffer, offset, count);
_position += count;
}
public override void Flush()
{
ThrowIfDisposed();
// assume writable if not disposed
Debug.Assert(CanWrite);
_baseStream.Flush();
}
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
// if we never wrote through here, save the position
if (!_everWritten)
_initialPosition = _baseBaseStream.Position;
if (!_leaveOpenOnClose)
_baseStream.Dispose(); // Close my super-stream (flushes the last data)
_saveCrcAndSizes?.Invoke(_initialPosition, Position, _checksum, _baseBaseStream, _zipArchiveEntry, _onClose);
_isDisposed = true;
}
base.Dispose(disposing);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Text;
using System.Linq;
namespace System.IO.Packaging
{
/// <summary>
/// This class has the utility methods for composing and parsing an Uri of pack:// scheme
/// </summary>
public static partial class PackUriHelper
{
// We need to perform Escaping for the following - '%'; '@'; ',' and '?'
// !!Important!! - The order is important - The '%' sign should be escaped first.
// If any more characters need to be added to the array below they should be added at the end.
// All of these arrays must maintain the same ordering.
private static readonly char[] s_specialCharacterChars = { '%', '@', ',', '?' };
#region Public Methods
/// <summary>
/// This method is used to create a valid pack Uri
/// </summary>
/// <param name="packageUri">This is the uri that points to the entire package.
/// This parameter should be an absolute Uri. This parameter cannot be null or empty
/// This method will create a valid pack uri that references the entire package</param>
/// <returns>A Uri with the "pack://" scheme</returns>
/// <exception cref="ArgumentNullException">If packageUri parameter is null</exception>
/// <exception cref="ArgumentException">If packageUri parameter is not an absolute Uri</exception>
public static Uri Create(Uri packageUri)
{
return Create(packageUri, null, null);
}
/// <summary>
/// This method is used to create a valid pack Uri
/// </summary>
/// <param name="packageUri">This is the uri that points to the entire package.
/// This parameter should be an absolute Uri. This parameter cannot be null or empty </param>
/// <param name="partUri">This is the uri that points to the part within the package
/// This parameter should be a relative Uri.
/// This parameter can be null in which case we will create a valid pack uri
/// that references the entire package</param>
/// <returns>A Uri with the "pack://" scheme</returns>
/// <exception cref="ArgumentNullException">If packageUri parameter is null</exception>
/// <exception cref="ArgumentException">If packageUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
public static Uri Create(Uri packageUri, Uri partUri)
{
return Create(packageUri, partUri, null);
}
/// <summary>
/// This method is used to create a valid pack Uri
/// </summary>
/// <param name="packageUri">This is the uri that points to the entire package.
/// This parameter should be an absolute Uri. This parameter cannot be null or empty </param>
/// <param name="partUri">This is the uri that points to the part within the package
/// This parameter should be a relative Uri.
/// This parameter can be null in which case we will create a valid pack uri
/// that references the entire package</param>
/// <param name="fragment">Fragment for the resulting Pack URI. This parameter can be null
/// The fragment string must start with a "#"</param>
/// <returns>A Uri with the "pack://" scheme</returns>
/// <exception cref="ArgumentNullException">If packageUri parameter is null</exception>
/// <exception cref="ArgumentException">If packageUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
/// <exception cref="ArgumentException">If fragment parameter is empty or does not start with a "#"</exception>
public static Uri Create(Uri packageUri, Uri partUri, string fragment)
{
// Step 1 - Validate input parameters
packageUri = ValidatePackageUri(packageUri);
if (partUri != null)
partUri = ValidatePartUri(partUri);
if (fragment != null)
{
if (fragment == string.Empty || fragment[0] != '#')
throw new ArgumentException(SR.Format(SR.FragmentMustStartWithHash, nameof(fragment)));
}
// Step 2 - Remove fragment identifier from the package URI, if it is present
// Since '#" is an excluded character in Uri syntax, it can only occur as the
// fragment identifier, in all other places it should be escaped.
// Hence we can safely use IndexOf to find the begining of the fragment.
string absolutePackageUri = packageUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
if (!string.IsNullOrEmpty(packageUri.Fragment))
{
absolutePackageUri = absolutePackageUri.Substring(0, absolutePackageUri.IndexOf('#'));
}
// Step 3 - Escape: "%", "?", "@", "#" and "," in the package URI
absolutePackageUri = EscapeSpecialCharacters(absolutePackageUri);
// Step 4 - Replace all '/' with ',' in the resulting string
absolutePackageUri = absolutePackageUri.Replace('/', ',');
// Step 5 - Append pack:// at the begining and a '/' at the end of the pack uri obtained so far
absolutePackageUri = string.Concat(PackUriHelper.UriSchemePack, Uri.SchemeDelimiter, absolutePackageUri);
Uri packUri = new Uri(absolutePackageUri);
// Step 6 - Append the part Uri if present.
if (partUri != null)
packUri = new Uri(packUri, partUri);
// Step 7 - Append fragment if present
if (fragment != null)
packUri = new Uri(string.Concat(packUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped), fragment));
// We want to ensure that internal content of resulting Uri has canonical form
// i.e. result.OrignalString would appear as perfectly formatted Uri string
// so we roundtrip the result.
return new Uri(packUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped));
}
/// <summary>
/// This method parses the pack uri and returns the inner
/// Uri that points to the package as a whole.
/// </summary>
/// <param name="packUri">Uri which has pack:// scheme</param>
/// <returns>Returns the inner uri that points to the entire package</returns>
/// <exception cref="ArgumentNullException">If packUri parameter is null</exception>
/// <exception cref="ArgumentException">If packUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If packUri parameter does not have "pack://" scheme</exception>
/// <exception cref="ArgumentException">If inner packageUri extracted from the packUri has a fragment component</exception>
public static Uri GetPackageUri(Uri packUri)
{
//Parameter Validation is done in the following method
ValidateAndGetPackUriComponents(packUri, out Uri packageUri, out _);
return packageUri;
}
/// <summary>
/// This method parses the pack uri and returns the absolute
/// path of the URI. This corresponds to the part within the
/// package. This corresponds to the absolute path component in
/// the Uri. If there is no part component present, this method
/// returns a null
/// </summary>
/// <param name="packUri">Returns a relative Uri that represents the
/// part within the package. If the pack Uri points to the entire
/// package then we return a null</param>
/// <returns>Returns a relative URI with an absolute path that points to a part within a package</returns>
/// <exception cref="ArgumentNullException">If packUri parameter is null</exception>
/// <exception cref="ArgumentException">If packUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If packUri parameter does not have "pack://" scheme</exception>
/// <exception cref="ArgumentException">If partUri extracted from packUri does not conform to the valid partUri syntax</exception>
public static Uri GetPartUri(Uri packUri)
{
//Parameter Validation is done in the following method
ValidateAndGetPackUriComponents(packUri, out _, out Uri partUri);
return partUri;
}
/// <summary>
/// This method compares two pack uris and returns an int to indicate the equivalence.
/// </summary>
/// <param name="firstPackUri">First Uri of pack:// scheme to be compared</param>
/// <param name="secondPackUri">Second Uri of pack:// scheme to be compared</param>
/// <returns>A 32-bit signed integer indicating the lexical relationship between the compared Uri components.
/// Value - Less than zero means firstUri is less than secondUri
/// Value - Equal to zero means both the Uris are equal
/// Value - Greater than zero means firstUri is greater than secondUri </returns>
/// <exception cref="ArgumentException">If either of the Uris are not absolute or if either of the Uris are not with pack:// scheme</exception>
/// <exception cref="ArgumentException">If firstPackUri or secondPackUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If firstPackUri or secondPackUri parameter does not have "pack://" scheme</exception>
public static int ComparePackUri(Uri firstPackUri, Uri secondPackUri)
{
//If any of the operands are null then we simply call System.Uri compare to return the correct value
if (firstPackUri == null || secondPackUri == null)
{
return CompareUsingSystemUri(firstPackUri, secondPackUri);
}
else
{
int compareResult;
ValidateAndGetPackUriComponents(firstPackUri, out Uri firstPackageUri, out Uri firstPartUri);
ValidateAndGetPackUriComponents(secondPackUri, out Uri secondPackageUri, out Uri secondPartUri);
if (firstPackageUri.Scheme == PackUriHelper.UriSchemePack && secondPackageUri.Scheme == PackUriHelper.UriSchemePack)
{
compareResult = ComparePackUri(firstPackageUri, secondPackageUri);
}
else
{
compareResult = CompareUsingSystemUri(firstPackageUri, secondPackageUri);
}
//Iff the PackageUri match do we compare the part uris.
if (compareResult == 0)
{
compareResult = System.IO.Packaging.PackUriHelper.ComparePartUri(firstPartUri, secondPartUri);
}
return compareResult;
}
}
#endregion Public Methods
#region Internal Methods
//This method validates the packUri and returns its two components if they are valid-
//1. Package Uri
//2. Part Uri
internal static void ValidateAndGetPackUriComponents(Uri packUri, out Uri packageUri, out Uri partUri)
{
//Validate if its not null and is an absolute Uri, has pack:// Scheme.
packUri = ValidatePackUri(packUri);
packageUri = GetPackageUriComponent(packUri);
partUri = GetPartUriComponent(packUri);
}
#endregion Internal Methods
#region Private Constructor
static PackUriHelper()
{
EnsurePackSchemeRegistered();
}
#endregion Private Constructor
#region Private Methods
private static void EnsurePackSchemeRegistered()
{
if (!UriParser.IsKnownScheme(UriSchemePack))
{
// Indicate that we want a default hierarchical parser with a registry based authority
UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), UriSchemePack, -1);
}
}
/// <summary>
/// This method is used to validate the package uri
/// </summary>
/// <param name="packageUri"></param>
/// <returns></returns>
private static Uri ValidatePackageUri(Uri packageUri)
{
if (packageUri == null)
throw new ArgumentNullException(nameof(packageUri));
if (!packageUri.IsAbsoluteUri)
throw new ArgumentException(SR.UriShouldBeAbsolute, nameof(packageUri));
return packageUri;
}
//validates is a given uri has pack:// scheme
private static Uri ValidatePackUri(Uri packUri)
{
if (packUri == null)
throw new ArgumentNullException(nameof(packUri));
if (!packUri.IsAbsoluteUri)
throw new ArgumentException(SR.UriShouldBeAbsolute, nameof(packUri));
if (packUri.Scheme != PackUriHelper.UriSchemePack)
throw new ArgumentException(SR.UriShouldBePackScheme, nameof(packUri));
return packUri;
}
/// <summary>
/// Escapes - %', '@', ',', '?' in the package URI
/// This method modifies the string in a culture safe and case safe manner.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static string EscapeSpecialCharacters(string path)
{
// Escaping for the following - '%'; '@'; ',' and '?'
// !!Important!! - The order is important - The '%' sign should be escaped first.
// This is currently enforced by the order of characters in the s_specialCharacterChars array
foreach (char c in s_specialCharacterChars)
{
if (path.Contains(c))
{
path = path.Replace(c.ToString(), Uri.HexEscape(c));
}
}
return path;
}
//This method validates and returns the PackageUri component
private static Uri GetPackageUriComponent(Uri packUri)
{
Debug.Assert(packUri != null, "packUri parameter cannot be null");
//Step 1 - Get the authority part of the URI. This section represents that package URI
string hostAndPort = packUri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped);
//Step 2 - Replace the ',' with '/' to reconstruct the package URI
hostAndPort = hostAndPort.Replace(',', '/');
//Step 3 - Unescape the special characters that we had escaped to construct the packUri
Uri packageUri = new Uri(Uri.UnescapeDataString(hostAndPort));
if (packageUri.Fragment != string.Empty)
throw new ArgumentException(SR.InnerPackageUriHasFragment);
return packageUri;
}
//This method validates and returns the PartUri component.
private static PackUriHelper.ValidatedPartUri GetPartUriComponent(Uri packUri)
{
Debug.Assert(packUri != null, "packUri parameter cannot be null");
string partName = GetStringForPartUriFromAnyUri(packUri);
if (partName == string.Empty)
return null;
else
return ValidatePartUri(new Uri(partName, UriKind.Relative));
}
#endregion Private Methods
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers
{
using System;
using System.ComponentModel;
using System.Text;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Renders the assembly version information for the entry assembly or a named assembly.
/// </summary>
/// <remarks>
/// As this layout renderer uses reflection and version information is unlikely to change during application execution,
/// it is recommended to use it in conjunction with the <see cref="NLog.LayoutRenderers.Wrappers.CachedLayoutRendererWrapper"/>.
/// </remarks>
/// <remarks>
/// The entry assembly can't be found in some cases e.g. ASP.NET, unit tests, etc.
/// </remarks>
[LayoutRenderer("assembly-version")]
[ThreadAgnostic]
[ThreadSafe]
public class AssemblyVersionLayoutRenderer : LayoutRenderer
{
/// <summary>
/// Initializes a new instance of the <see cref="AssemblyVersionLayoutRenderer" /> class.
/// </summary>
public AssemblyVersionLayoutRenderer()
{
Type = AssemblyVersionType.Assembly;
Format = DefaultFormat;
}
/// <summary>
/// The (full) name of the assembly. If <c>null</c>, using the entry assembly.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultParameter]
public string Name { get; set; }
/// <summary>
/// Gets or sets the type of assembly version to retrieve.
/// </summary>
/// <remarks>
/// Some version type and platform combinations are not fully supported.
/// - UWP earlier than .NET Standard 1.5: Value for <see cref="AssemblyVersionType.Assembly"/> is always returned unless the <see cref="Name"/> parameter is specified.
/// - Silverlight: Value for <see cref="AssemblyVersionType.Assembly"/> is always returned.
/// </remarks>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(nameof(AssemblyVersionType.Assembly))]
public AssemblyVersionType Type { get; set; }
private const string DefaultFormat = "major.minor.build.revision";
private string _format;
/// <summary>
/// Gets or sets the custom format of the assembly version output.
/// </summary>
/// <remarks>
/// Supported placeholders are 'major', 'minor', 'build' and 'revision'.
/// The default .NET template for version numbers is 'major.minor.build.revision'. See
/// https://docs.microsoft.com/en-gb/dotnet/api/system.version?view=netframework-4.7.2#remarks
/// for details.
/// </remarks>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(DefaultFormat)]
public string Format
{
get => _format;
set => _format = value?.ToLowerInvariant();
}
/// <summary>
/// Initializes the layout renderer.
/// </summary>
protected override void InitializeLayoutRenderer()
{
_assemblyVersion = null;
base.InitializeLayoutRenderer();
}
/// <summary>
/// Closes the layout renderer.
/// </summary>
protected override void CloseLayoutRenderer()
{
_assemblyVersion = null;
base.CloseLayoutRenderer();
}
private string _assemblyVersion;
/// <summary>
/// Renders an assembly version and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
var version = _assemblyVersion ?? (_assemblyVersion = ApplyFormatToVersion(GetVersion()));
if (string.IsNullOrEmpty(version))
{
version = $"Could not find value for {(string.IsNullOrEmpty(Name) ? "entry" : Name)} assembly and version type {Type}";
}
builder.Append(version);
}
private string ApplyFormatToVersion(string version)
{
if (Format.Equals(DefaultFormat, StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(version))
{
return version;
}
var versionParts = version.SplitAndTrimTokens('.');
version = Format.Replace("major", versionParts[0])
.Replace("minor", versionParts.Length > 1 ? versionParts[1] : "0")
.Replace("build", versionParts.Length > 2 ? versionParts[2] : "0")
.Replace("revision", versionParts.Length > 3 ? versionParts[3] : "0");
return version;
}
#if SILVERLIGHT
private string GetVersion()
{
var assemblyName = GetAssemblyName();
return assemblyName.Version.ToString();
}
private System.Reflection.AssemblyName GetAssemblyName()
{
if (string.IsNullOrEmpty(Name))
{
return new System.Reflection.AssemblyName(System.Windows.Application.Current.GetType().Assembly.FullName);
}
else
{
return new System.Reflection.AssemblyName(Name);
}
}
#elif NETSTANDARD1_3
private string GetVersion()
{
if (string.IsNullOrEmpty(Name))
{
return Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion;
}
else
{
var assembly = GetAssembly();
return assembly?.GetName().Version.ToString();
}
}
private System.Reflection.Assembly GetAssembly()
{
return System.Reflection.Assembly.Load(new System.Reflection.AssemblyName(Name));
}
#else
private string GetVersion()
{
var assembly = GetAssembly();
return GetVersion(assembly);
}
/// <summary>
/// Gets the assembly specified by <see cref="Name"/>, or entry assembly otherwise
/// </summary>
/// <returns>Found assembly</returns>
protected virtual System.Reflection.Assembly GetAssembly()
{
if (string.IsNullOrEmpty(Name))
{
return System.Reflection.Assembly.GetEntryAssembly();
}
else
{
return System.Reflection.Assembly.Load(new System.Reflection.AssemblyName(Name));
}
}
private string GetVersion(System.Reflection.Assembly assembly)
{
switch (Type)
{
case AssemblyVersionType.File:
return assembly?.GetCustomAttribute<System.Reflection.AssemblyFileVersionAttribute>()?.Version;
case AssemblyVersionType.Informational:
return assembly?.GetCustomAttribute<System.Reflection.AssemblyInformationalVersionAttribute>()?.InformationalVersion;
default:
return assembly?.GetName().Version?.ToString();
}
}
#endif
}
}
| |
// MbUnit Test Framework
//
// Copyright (c) 2004 Jonathan de Halleux
//
// 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.
//
// MbUnit HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
namespace MbUnit.Core.Reports.Serialization
{
using System;
using System.Xml;
using System.Xml.Serialization;
using MbUnit.Core.Monitoring;
/// <summary />
/// <remarks />
[XmlType(IncludeInSchema=true, TypeName="report-run")]
[XmlRoot(ElementName="reportrun")]
[Serializable]
public sealed class ReportRun
{
private long _memory;
private string _consoleError = "";
private string _name;
private string _description = "";
private string _consoleOut = "";
private int assertCount = 0;
private System.Double _duration;
private ReportException _exception;
private ReportRunResult _result;
private InvokerCollection _invokers = new InvokerCollection();
private WarningCollection _warnings = new WarningCollection();
private AssertCollection _asserts = new AssertCollection();
public static ReportRun Success(RunPipe pipe, ReportMonitor monitor)
{
ReportRun run = new ReportRun();
run.ConsoleOut = monitor.Consoler.Out;
run.ConsoleError = monitor.Consoler.Error;
run.Result = ReportRunResult.Success;
run.Name = pipe.Name;
run.AssertCount = MbUnit.Framework.Assert.AssertCount;
run.Duration = monitor.Timer.Duration;
run.Memory = monitor.Memorizer.Usage;
MbUnit.Framework.Assert.FlushWarnings(run);
return run;
}
public static ReportRun Failure(RunPipe pipe, ReportMonitor monitor, Exception ex)
{
ReportRun run = new ReportRun();
run.ConsoleOut = monitor.Consoler.Out;
run.ConsoleError = monitor.Consoler.Error;
run.Result = ReportRunResult.Failure;
run.Name = pipe.Name;
run.AssertCount = MbUnit.Framework.Assert.AssertCount;
run.Duration = monitor.Timer.Duration;
run.Memory = monitor.Memorizer.Usage;
run.Exception = ReportException.FromException(ex);
MbUnit.Framework.Assert.FlushWarnings(run);
return run;
}
public static ReportRun Ignore(RunPipe pipe, ReportMonitor monitor)
{
ReportRun run = new ReportRun();
run.ConsoleOut = monitor.Consoler.Out;
run.ConsoleError = monitor.Consoler.Error;
run.Result = ReportRunResult.Ignore;
run.Name = pipe.Name;
run.AssertCount = MbUnit.Framework.Assert.AssertCount;
run.Duration = monitor.Timer.Duration;
run.Memory = monitor.Memorizer.Usage;
MbUnit.Framework.Assert.FlushWarnings(run);
return run;
}
public static ReportRun Skip(RunPipe pipe, Exception ex)
{
ReportRun run = new ReportRun();
run.Result = ReportRunResult.Skip;
run.Name = pipe.Name;
run.Duration = 0;
run.Memory = 0;
run.AssertCount = MbUnit.Framework.Assert.AssertCount;
run.Exception = ReportException.FromException(ex);
MbUnit.Framework.Assert.FlushWarnings(run);
return run;
}
/// <summary />
/// <remarks />
[XmlArray(ElementName="invokers")]
[XmlArrayItem(ElementName="invoker", Type=typeof(ReportInvoker), IsNullable=false)]
public InvokerCollection Invokers
{
get
{
return this._invokers;
}
set
{
this._invokers = value;
}
}
[XmlArray(ElementName = "warnings")]
[XmlArrayItem(ElementName = "warning", Type = typeof(ReportWarning), IsNullable = false)]
public WarningCollection Warnings
{
get
{
return this._warnings;
}
set
{
this._warnings = value;
}
}
[XmlArray(ElementName = "asserts")]
[XmlArrayItem(ElementName = "assert", Type = typeof(ReportAssert), IsNullable = false)]
public AssertCollection Asserts
{
get
{
return this._asserts;
}
set
{
this._asserts = value;
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="")]
public string Description
{
get
{
return this._description;
}
set
{
this._description = value;
if (this._description==null)
this._description="";
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="console-out")]
public string ConsoleOut
{
get
{
return this._consoleOut;
}
set
{
this._consoleOut = value;
if (this._consoleOut==null)
this._consoleOut="";
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="console-error")]
public string ConsoleError
{
get
{
return this._consoleError;
}
set
{
this._consoleError = value;
if (this._consoleError==null)
this._consoleError="";
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="exception")]
public ReportException Exception
{
get
{
return this._exception;
}
set
{
this._exception = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="name")]
public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="result")]
public ReportRunResult Result
{
get
{
return this._result;
}
set
{
this._result = value;
}
}
[XmlAttribute(AttributeName = "assert-count")]
public int AssertCount
{
get { return this.assertCount; }
set { this.assertCount = value; }
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="duration")]
public double Duration
{
get
{
return this._duration;
}
set
{
this._duration = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="memory")]
public long Memory
{
get
{
return this._memory;
}
set
{
this._memory = value;
}
}
[Serializable]
public sealed class InvokerCollection : System.Collections.CollectionBase
{
/// <summary />
/// <remarks />
public InvokerCollection()
{}
public object this[int index]
{
get
{
return this.List[index];
}
set
{
this.List[index] = value;
}
}
/// <summary />
/// <remarks />
public void Add(object o)
{
this.List.Add(o);
}
/// <summary />
/// <remarks />
public void AddReportInvoker(ReportInvoker o)
{
this.List.Add(o);
}
/// <summary />
/// <remarks />
public bool ContainsReportInvoker(ReportInvoker o)
{
return this.List.Contains(o);
}
/// <summary />
/// <remarks />
public void RemoveReportInvoker(ReportInvoker o)
{
this.List.Remove(o);
}
}
[Serializable]
public sealed class WarningCollection : System.Collections.CollectionBase
{
public WarningCollection()
{ }
public object this[int index]
{
get
{
return this.List[index];
}
set
{
this.List[index] = value;
}
}
public void Add(object o)
{
this.List.Add(o);
}
public void AddReportWarning(ReportWarning o)
{
this.List.Add(o);
}
public bool ContainsReportWarning(ReportWarning o)
{
return this.List.Contains(o);
}
public void RemoveReportWarning(ReportWarning o)
{
this.List.Remove(o);
}
}
[Serializable]
public sealed class AssertCollection : System.Collections.CollectionBase
{
public AssertCollection()
{ }
public object this[int index]
{
get
{
return this.List[index];
}
set
{
this.List[index] = value;
}
}
public void Add(object o)
{
this.List.Add(o);
}
public void AddReportAssert(ReportAssert o)
{
this.List.Add(o);
}
public bool ContainsReportAssert(ReportAssert o)
{
return this.List.Contains(o);
}
public void RemoveReportAssert(ReportAssert o)
{
this.List.Remove(o);
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Edit.Blueprints.HitCircles.Components;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Tests.Beatmaps;
using osu.Game.Screens.Edit.Compose.Components;
using osuTK;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Editing
{
public class TestSceneEditorSelection : EditorTestScene
{
protected override Ruleset CreateEditorRuleset() => new OsuRuleset();
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) => new TestBeatmap(ruleset, false);
private EditorBlueprintContainer blueprintContainer
=> Editor.ChildrenOfType<EditorBlueprintContainer>().First();
private void moveMouseToObject(Func<HitObject> targetFunc)
{
AddStep("move mouse to object", () =>
{
var pos = blueprintContainer.SelectionBlueprints
.First(s => s.Item == targetFunc())
.ChildrenOfType<HitCirclePiece>()
.First().ScreenSpaceDrawQuad.Centre;
InputManager.MoveMouseTo(pos);
});
}
[Test]
public void TestNudgeSelection()
{
HitCircle[] addedObjects = null;
AddStep("add hitobjects", () => EditorBeatmap.AddRange(addedObjects = new[]
{
new HitCircle { StartTime = 100 },
new HitCircle { StartTime = 200, Position = new Vector2(100) },
new HitCircle { StartTime = 300, Position = new Vector2(200) },
new HitCircle { StartTime = 400, Position = new Vector2(300) },
}));
AddStep("select objects", () => EditorBeatmap.SelectedHitObjects.AddRange(addedObjects));
AddStep("nudge forwards", () => InputManager.Key(Key.K));
AddAssert("objects moved forwards in time", () => addedObjects[0].StartTime > 100);
AddStep("nudge backwards", () => InputManager.Key(Key.J));
AddAssert("objects reverted to original position", () => addedObjects[0].StartTime == 100);
}
[Test]
public void TestBasicSelect()
{
var addedObject = new HitCircle { StartTime = 100 };
AddStep("add hitobject", () => EditorBeatmap.Add(addedObject));
moveMouseToObject(() => addedObject);
AddStep("left click", () => InputManager.Click(MouseButton.Left));
AddAssert("hitobject selected", () => EditorBeatmap.SelectedHitObjects.Single() == addedObject);
var addedObject2 = new HitCircle
{
StartTime = 100,
Position = new Vector2(100),
};
AddStep("add one more hitobject", () => EditorBeatmap.Add(addedObject2));
AddAssert("selection unchanged", () => EditorBeatmap.SelectedHitObjects.Single() == addedObject);
moveMouseToObject(() => addedObject2);
AddStep("left click", () => InputManager.Click(MouseButton.Left));
AddAssert("hitobject selected", () => EditorBeatmap.SelectedHitObjects.Single() == addedObject2);
}
[Test]
public void TestMultiSelect()
{
var addedObjects = new[]
{
new HitCircle { StartTime = 100 },
new HitCircle { StartTime = 200, Position = new Vector2(100) },
new HitCircle { StartTime = 300, Position = new Vector2(200) },
new HitCircle { StartTime = 400, Position = new Vector2(300) },
};
AddStep("add hitobjects", () => EditorBeatmap.AddRange(addedObjects));
moveMouseToObject(() => addedObjects[0]);
AddStep("click first", () => InputManager.Click(MouseButton.Left));
AddAssert("hitobject selected", () => EditorBeatmap.SelectedHitObjects.Single() == addedObjects[0]);
AddStep("hold control", () => InputManager.PressKey(Key.ControlLeft));
moveMouseToObject(() => addedObjects[1]);
AddStep("click second", () => InputManager.Click(MouseButton.Left));
AddAssert("2 hitobjects selected", () => EditorBeatmap.SelectedHitObjects.Count == 2 && EditorBeatmap.SelectedHitObjects.Contains(addedObjects[1]));
moveMouseToObject(() => addedObjects[2]);
AddStep("click third", () => InputManager.Click(MouseButton.Left));
AddAssert("3 hitobjects selected", () => EditorBeatmap.SelectedHitObjects.Count == 3 && EditorBeatmap.SelectedHitObjects.Contains(addedObjects[2]));
moveMouseToObject(() => addedObjects[1]);
AddStep("click second", () => InputManager.Click(MouseButton.Left));
AddAssert("2 hitobjects selected", () => EditorBeatmap.SelectedHitObjects.Count == 2 && !EditorBeatmap.SelectedHitObjects.Contains(addedObjects[1]));
}
[TestCase(false)]
[TestCase(true)]
public void TestMultiSelectFromDrag(bool alreadySelectedBeforeDrag)
{
HitCircle[] addedObjects = null;
AddStep("add hitobjects", () => EditorBeatmap.AddRange(addedObjects = new[]
{
new HitCircle { StartTime = 100 },
new HitCircle { StartTime = 200, Position = new Vector2(100) },
new HitCircle { StartTime = 300, Position = new Vector2(200) },
new HitCircle { StartTime = 400, Position = new Vector2(300) },
}));
moveMouseToObject(() => addedObjects[0]);
AddStep("click first", () => InputManager.Click(MouseButton.Left));
AddStep("hold control", () => InputManager.PressKey(Key.ControlLeft));
moveMouseToObject(() => addedObjects[1]);
if (alreadySelectedBeforeDrag)
AddStep("click second", () => InputManager.Click(MouseButton.Left));
AddStep("mouse down on second", () => InputManager.PressButton(MouseButton.Left));
AddAssert("2 hitobjects selected", () => EditorBeatmap.SelectedHitObjects.Count == 2 && EditorBeatmap.SelectedHitObjects.Contains(addedObjects[1]));
AddStep("drag to centre", () => InputManager.MoveMouseTo(blueprintContainer.ScreenSpaceDrawQuad.Centre));
AddAssert("positions changed", () => addedObjects[0].Position != Vector2.Zero && addedObjects[1].Position != new Vector2(50));
AddStep("release control", () => InputManager.ReleaseKey(Key.ControlLeft));
AddStep("mouse up", () => InputManager.ReleaseButton(MouseButton.Left));
}
[Test]
public void TestBasicDeselect()
{
var addedObject = new HitCircle { StartTime = 100 };
AddStep("add hitobject", () => EditorBeatmap.Add(addedObject));
moveMouseToObject(() => addedObject);
AddStep("left click", () => InputManager.Click(MouseButton.Left));
AddAssert("hitobject selected", () => EditorBeatmap.SelectedHitObjects.Single() == addedObject);
AddStep("click away", () =>
{
InputManager.MoveMouseTo(blueprintContainer.ScreenSpaceDrawQuad.Centre);
InputManager.Click(MouseButton.Left);
});
AddAssert("selection lost", () => EditorBeatmap.SelectedHitObjects.Count == 0);
}
[Test]
public void TestQuickDeleteRemovesObjectInPlacement()
{
var addedObject = new HitCircle
{
StartTime = 0,
Position = OsuPlayfield.BASE_SIZE * 0.5f
};
AddStep("add hitobject", () => EditorBeatmap.Add(addedObject));
AddStep("enter placement mode", () => InputManager.PressKey(Key.Number2));
moveMouseToObject(() => addedObject);
AddStep("hold shift", () => InputManager.PressKey(Key.ShiftLeft));
AddStep("right click", () => InputManager.Click(MouseButton.Right));
AddStep("release shift", () => InputManager.ReleaseKey(Key.ShiftLeft));
AddAssert("no hitobjects in beatmap", () => EditorBeatmap.HitObjects.Count == 0);
}
[Test]
public void TestQuickDeleteRemovesObjectInSelection()
{
var addedObject = new HitCircle
{
StartTime = 0,
Position = OsuPlayfield.BASE_SIZE * 0.5f
};
AddStep("add hitobject", () => EditorBeatmap.Add(addedObject));
AddStep("select added object", () => EditorBeatmap.SelectedHitObjects.Add(addedObject));
moveMouseToObject(() => addedObject);
AddStep("hold shift", () => InputManager.PressKey(Key.ShiftLeft));
AddStep("right click", () => InputManager.Click(MouseButton.Right));
AddStep("release shift", () => InputManager.ReleaseKey(Key.ShiftLeft));
AddAssert("no hitobjects in beatmap", () => EditorBeatmap.HitObjects.Count == 0);
}
[Test]
public void TestQuickDeleteRemovesSliderControlPoint()
{
Slider slider = null;
PathControlPoint[] points =
{
new PathControlPoint(),
new PathControlPoint(new Vector2(50, 0)),
new PathControlPoint(new Vector2(100, 0))
};
AddStep("add slider", () =>
{
slider = new Slider
{
StartTime = 1000,
Path = new SliderPath(points)
};
EditorBeatmap.Add(slider);
});
AddStep("select added slider", () => EditorBeatmap.SelectedHitObjects.Add(slider));
AddStep("move mouse to controlpoint", () =>
{
var pos = blueprintContainer.ChildrenOfType<PathControlPointPiece>().ElementAt(1).ScreenSpaceDrawQuad.Centre;
InputManager.MoveMouseTo(pos);
});
AddStep("hold shift", () => InputManager.PressKey(Key.ShiftLeft));
AddStep("right click", () => InputManager.Click(MouseButton.Right));
AddAssert("slider has 2 points", () => slider.Path.ControlPoints.Count == 2);
AddStep("right click", () => InputManager.Click(MouseButton.Right));
// second click should nuke the object completely.
AddAssert("no hitobjects in beatmap", () => EditorBeatmap.HitObjects.Count == 0);
AddStep("release shift", () => InputManager.ReleaseKey(Key.ShiftLeft));
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Xunit;
namespace Microsoft.EntityFrameworkCore
{
public class LazyLoadProxyMySqlTest : LazyLoadProxyTestBase<LazyLoadProxyMySqlTest.LoadMySqlFixture>
{
public LazyLoadProxyMySqlTest(LoadMySqlFixture fixture)
: base(fixture)
{
fixture.TestSqlLoggerFactory.Clear();
}
public override void Lazy_load_collection(EntityState state, bool useAttach, bool useDetach)
{
base.Lazy_load_collection(state, useAttach, useDetach);
Assert.Equal(
@"@__get_Item_0='707' (Nullable = true)
SELECT [e].[Id], [e].[ParentId]
FROM [Child] AS [e]
WHERE [e].[ParentId] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_many_to_one_reference_to_principal(EntityState state, bool useAttach, bool useDetach)
{
base.Lazy_load_many_to_one_reference_to_principal(state, useAttach, useDetach);
Assert.Equal(
@"@__get_Item_0='707'
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE [e].[Id] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_reference_to_principal(EntityState state, bool useAttach, bool useDetach)
{
base.Lazy_load_one_to_one_reference_to_principal(state, useAttach, useDetach);
Assert.Equal(
@"@__get_Item_0='707'
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE [e].[Id] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_reference_to_dependent(EntityState state, bool useAttach, bool useDetach)
{
base.Lazy_load_one_to_one_reference_to_dependent(state, useAttach, useDetach);
Assert.Equal(
@"@__get_Item_0='707' (Nullable = true)
SELECT [e].[Id], [e].[ParentId]
FROM [Single] AS [e]
WHERE [e].[ParentId] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_PK_to_PK_reference_to_principal(EntityState state)
{
base.Lazy_load_one_to_one_PK_to_PK_reference_to_principal(state);
Assert.Equal(
@"@__get_Item_0='707'
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE [e].[Id] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_PK_to_PK_reference_to_dependent(EntityState state)
{
base.Lazy_load_one_to_one_PK_to_PK_reference_to_dependent(state);
Assert.Equal(
@"@__get_Item_0='707'
SELECT [e].[Id]
FROM [SinglePkToPk] AS [e]
WHERE [e].[Id] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_many_to_one_reference_to_principal_null_FK(EntityState state)
{
base.Lazy_load_many_to_one_reference_to_principal_null_FK(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_one_to_one_reference_to_principal_null_FK(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_principal_null_FK(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_collection_not_found(EntityState state)
{
base.Lazy_load_collection_not_found(state);
Assert.Equal(
@"@__get_Item_0='767' (Nullable = true)
SELECT [e].[Id], [e].[ParentId]
FROM [Child] AS [e]
WHERE [e].[ParentId] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_many_to_one_reference_to_principal_not_found(EntityState state)
{
base.Lazy_load_many_to_one_reference_to_principal_not_found(state);
Assert.Equal(
@"@__get_Item_0='787'
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE [e].[Id] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_reference_to_principal_not_found(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_principal_not_found(state);
Assert.Equal(
@"@__get_Item_0='787'
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE [e].[Id] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_reference_to_dependent_not_found(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_dependent_not_found(state);
Assert.Equal(
@"@__get_Item_0='767' (Nullable = true)
SELECT [e].[Id], [e].[ParentId]
FROM [Single] AS [e]
WHERE [e].[ParentId] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_collection_already_loaded(EntityState state)
{
base.Lazy_load_collection_already_loaded(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_many_to_one_reference_to_principal_already_loaded(EntityState state)
{
base.Lazy_load_many_to_one_reference_to_principal_already_loaded(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_one_to_one_reference_to_principal_already_loaded(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_principal_already_loaded(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_one_to_one_reference_to_dependent_already_loaded(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_dependent_already_loaded(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_one_to_one_PK_to_PK_reference_to_principal_already_loaded(EntityState state)
{
base.Lazy_load_one_to_one_PK_to_PK_reference_to_principal_already_loaded(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_one_to_one_PK_to_PK_reference_to_dependent_already_loaded(EntityState state)
{
base.Lazy_load_one_to_one_PK_to_PK_reference_to_dependent_already_loaded(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_many_to_one_reference_to_principal_alternate_key(EntityState state)
{
base.Lazy_load_many_to_one_reference_to_principal_alternate_key(state);
Assert.Equal(
@"@__get_Item_0='Root' (Size = 450)
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE [e].[AlternateId] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_reference_to_principal_alternate_key(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_principal_alternate_key(state);
Assert.Equal(
@"@__get_Item_0='Root' (Size = 450)
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE [e].[AlternateId] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_reference_to_dependent_alternate_key(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_dependent_alternate_key(state);
Assert.Equal(
@"@__get_Item_0='Root' (Size = 450)
SELECT [e].[Id], [e].[ParentId]
FROM [SingleAk] AS [e]
WHERE [e].[ParentId] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_many_to_one_reference_to_principal_null_FK_alternate_key(EntityState state)
{
base.Lazy_load_many_to_one_reference_to_principal_null_FK_alternate_key(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_one_to_one_reference_to_principal_null_FK_alternate_key(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_principal_null_FK_alternate_key(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_collection_shadow_fk(EntityState state)
{
base.Lazy_load_collection_shadow_fk(state);
Assert.Equal(
@"@__get_Item_0='707' (Nullable = true)
SELECT [e].[Id], [e].[ParentId]
FROM [ChildShadowFk] AS [e]
WHERE [e].[ParentId] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_many_to_one_reference_to_principal_shadow_fk(EntityState state)
{
base.Lazy_load_many_to_one_reference_to_principal_shadow_fk(state);
Assert.Equal(
@"@__get_Item_0='707'
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE [e].[Id] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_reference_to_principal_shadow_fk(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_principal_shadow_fk(state);
Assert.Equal(
@"@__get_Item_0='707'
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE [e].[Id] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_reference_to_dependent_shadow_fk(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_dependent_shadow_fk(state);
Assert.Equal(
@"@__get_Item_0='707' (Nullable = true)
SELECT [e].[Id], [e].[ParentId]
FROM [SingleShadowFk] AS [e]
WHERE [e].[ParentId] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_many_to_one_reference_to_principal_null_FK_shadow_fk(EntityState state)
{
base.Lazy_load_many_to_one_reference_to_principal_null_FK_shadow_fk(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_one_to_one_reference_to_principal_null_FK_shadow_fk(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_principal_null_FK_shadow_fk(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_collection_composite_key(EntityState state)
{
base.Lazy_load_collection_composite_key(state);
Assert.Equal(
@"@__get_Item_0='Root' (Size = 450)
@__get_Item_1='707' (Nullable = true)
SELECT [e].[Id], [e].[ParentAlternateId], [e].[ParentId]
FROM [ChildCompositeKey] AS [e]
WHERE ([e].[ParentAlternateId] = @__get_Item_0) AND ([e].[ParentId] = @__get_Item_1)",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_many_to_one_reference_to_principal_composite_key(EntityState state)
{
base.Lazy_load_many_to_one_reference_to_principal_composite_key(state);
Assert.Equal(
@"@__get_Item_0='Root' (Size = 450)
@__get_Item_1='707'
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE ([e].[AlternateId] = @__get_Item_0) AND ([e].[Id] = @__get_Item_1)",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_reference_to_principal_composite_key(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_principal_composite_key(state);
Assert.Equal(
@"@__get_Item_0='Root' (Size = 450)
@__get_Item_1='707'
SELECT [e].[Id], [e].[AlternateId]
FROM [Parent] AS [e]
WHERE ([e].[AlternateId] = @__get_Item_0) AND ([e].[Id] = @__get_Item_1)",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_one_to_one_reference_to_dependent_composite_key(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_dependent_composite_key(state);
Assert.Equal(
@"@__get_Item_0='Root' (Size = 450)
@__get_Item_1='707' (Nullable = true)
SELECT [e].[Id], [e].[ParentAlternateId], [e].[ParentId]
FROM [SingleCompositeKey] AS [e]
WHERE ([e].[ParentAlternateId] = @__get_Item_0) AND ([e].[ParentId] = @__get_Item_1)",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Lazy_load_many_to_one_reference_to_principal_null_FK_composite_key(EntityState state)
{
base.Lazy_load_many_to_one_reference_to_principal_null_FK_composite_key(state);
Assert.Equal("", Sql);
}
public override void Lazy_load_one_to_one_reference_to_principal_null_FK_composite_key(EntityState state)
{
base.Lazy_load_one_to_one_reference_to_principal_null_FK_composite_key(state);
Assert.Equal("", Sql);
}
public override async Task Load_collection(EntityState state, bool async)
{
await base.Load_collection(state, async);
if (!async)
{
Assert.Equal(
@"@__get_Item_0='707' (Nullable = true)
SELECT [e].[Id], [e].[ParentId]
FROM [Child] AS [e]
WHERE [e].[ParentId] = @__get_Item_0",
Sql,
ignoreLineEndingDifferences: true);
}
}
protected override void ClearLog() => Fixture.TestSqlLoggerFactory.Clear();
protected override void RecordLog() => Sql = Fixture.TestSqlLoggerFactory.Sql;
private string Sql { get; set; }
public class LoadMySqlFixture : LoadFixtureBase
{
public TestSqlLoggerFactory TestSqlLoggerFactory => (TestSqlLoggerFactory)ListLoggerFactory;
protected override ITestStoreFactory TestStoreFactory => MySqlTestStoreFactory.Instance;
public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
=> base.AddOptions(builder).ConfigureWarnings(
c => c
.Log(RelationalEventId.QueryClientEvaluationWarning));
}
}
}
| |
/*
* ProcessStartInfo.cs - Implementation of the
* "System.Diagnostics.ProcessStartInfo" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Diagnostics
{
#if CONFIG_EXTENDED_DIAGNOSTICS
using System.ComponentModel;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
#if CONFIG_COMPONENT_MODEL
[TypeConverter(typeof(ExpandableObjectConverter))]
#endif
public sealed class ProcessStartInfo
{
// Special flags for starting processes.
[Flags]
internal enum ProcessStartFlags
{
CreateNoWindow = 0x0001,
ErrorDialog = 0x0002,
RedirectStdin = 0x0004,
RedirectStdout = 0x0008,
RedirectStderr = 0x0010,
UseShellExecute = 0x0020,
ExecOverTop = 0x0040
}; // enum ProcessStartFlags
// Internal state.
private String arguments;
private String fileName;
internal ProcessStartFlags flags;
internal StringDictionary envVars;
private IntPtr errorDialogParent;
private String verb;
private ProcessWindowStyle style;
private String workingDirectory;
// Constructors.
public ProcessStartInfo() : this(null, null) {}
public ProcessStartInfo(String fileName) : this(fileName, null) {}
public ProcessStartInfo(String fileName, String arguments)
{
this.fileName = fileName;
this.arguments = arguments;
this.flags = ProcessStartFlags.UseShellExecute;
}
// Get a process start flag.
private bool GetFlag(ProcessStartFlags flag)
{
return ((flags & flag) != 0);
}
// Set a process start flag.
private void SetFlag(ProcessStartFlags flag, bool value)
{
if(value)
{
flags |= flag;
}
else
{
flags &= ~flag;
}
}
// Get or set object properties.
[RecommendedAsConfigurable(true)]
[DefaultValue("")]
[MonitoringDescription("ProcessArguments")]
[TypeConverter
("System.Diagnostics.Design.StringValueConverter, System.Design")]
public String Arguments
{
get
{
if(arguments == null)
{
return String.Empty;
}
else
{
return arguments;
}
}
set
{
arguments = value;
}
}
[MonitoringDescription("ProcessCreateNoWindow")]
[DefaultValue(false)]
public bool CreateNoWindow
{
get
{
return GetFlag(ProcessStartFlags.CreateNoWindow);
}
set
{
SetFlag(ProcessStartFlags.CreateNoWindow, value);
}
}
[MonitoringDescription("ProcessEnvironmentVariables")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Editor
("System.Diagnostics.Design.StringDictionaryEditor, System.Design",
"System.Drawing.Design.UITypeEditor, System.Drawing")]
public StringDictionary EnvironmentVariables
{
get
{
if(envVars == null)
{
envVars = new StringDictionary();
IDictionary env = Environment.GetEnvironmentVariables();
if(env != null)
{
IDictionaryEnumerator e = env.GetEnumerator();
while(e.MoveNext())
{
envVars.Add((String)(e.Key), (String)(e.Value));
}
}
}
return envVars;
}
}
[MonitoringDescription("ProcessErrorDialog")]
[DefaultValue(false)]
public bool ErrorDialog
{
get
{
return GetFlag(ProcessStartFlags.ErrorDialog);
}
set
{
SetFlag(ProcessStartFlags.ErrorDialog, value);
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IntPtr ErrorDialogParentHandle
{
get
{
return errorDialogParent;
}
set
{
errorDialogParent = value;
}
}
[Editor
("System.Diagnostics.Design.StartFileNameEditor, System.Design",
"System.Drawing.Design.UITypeEditor, System.Drawing")]
[TypeConverter
("System.Diagnostics.Design.StringValueConverter, System.Design")]
[DefaultValue("")]
[MonitoringDescription("ProcessFileName")]
[RecommendedAsConfigurable(true)]
public String FileName
{
get
{
if(fileName == null)
{
return String.Empty;
}
else
{
return fileName;
}
}
set
{
fileName = value;
}
}
[MonitoringDescription("ProcessRedirectStandardError")]
[DefaultValue(false)]
public bool RedirectStandardError
{
get
{
return GetFlag(ProcessStartFlags.RedirectStderr);
}
set
{
SetFlag(ProcessStartFlags.RedirectStderr, value);
}
}
[MonitoringDescription("ProcessRedirectStandardInput")]
[DefaultValue(false)]
public bool RedirectStandardInput
{
get
{
return GetFlag(ProcessStartFlags.RedirectStdin);
}
set
{
SetFlag(ProcessStartFlags.RedirectStdin, value);
}
}
[MonitoringDescription("ProcessRedirectStandardOutput")]
[DefaultValue(false)]
public bool RedirectStandardOutput
{
get
{
return GetFlag(ProcessStartFlags.RedirectStdout);
}
set
{
SetFlag(ProcessStartFlags.RedirectStdout, value);
}
}
[MonitoringDescription("ProcessUseShellExecute")]
[DefaultValue(true)]
public bool UseShellExecute
{
get
{
return GetFlag(ProcessStartFlags.UseShellExecute);
}
set
{
SetFlag(ProcessStartFlags.UseShellExecute, value);
}
}
[MonitoringDescription("ProcessVerb")]
[DefaultValue("")]
[TypeConverter("System.Diagnostics.Design.VerbConverter, System.Design")]
public String Verb
{
get
{
if(verb == null)
{
return String.Empty;
}
else
{
return verb;
}
}
set
{
verb = value;
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public String[] Verbs
{
get
{
// We don't use verb lists in this implementation.
return new String [0];
}
}
[MonitoringDescription("ProcessWindowStyle")]
public ProcessWindowStyle WindowStyle
{
get
{
return style;
}
set
{
if(((int)value) < ((int)(ProcessWindowStyle.Normal)) ||
((int)value) > ((int)(ProcessWindowStyle.Maximized)))
{
throw new InvalidEnumArgumentException
("value", (int)value, typeof(ProcessWindowStyle));
}
style = value;
}
}
[MonitoringDescription("ProcessWorkingDirectory")]
[DefaultValue("")]
[RecommendedAsConfigurable(true)]
[Editor
("System.Diagnostics.Design.WorkingDirectoryEditor, System.Design",
"System.Drawing.Design.UITypeEditor, System.Drawing")]
[TypeConverter
("System.Diagnostics.Design.StringValueConverter, System.Design")]
public String WorkingDirectory
{
get
{
if(workingDirectory == null)
{
return String.Empty;
}
else
{
return workingDirectory;
}
}
set
{
workingDirectory = value;
}
}
// Quote a string if necessary.
private static String Quote(String str)
{
// Handle the empty string case first.
if(str == null || str == String.Empty)
{
return "\"\"";
}
// Determine if there is a character that needs quoting.
bool quote = false;
foreach(char ch in str)
{
if(Char.IsWhiteSpace(ch) || ch == '"' || ch == '\'')
{
quote = true;
break;
}
}
if(!quote)
{
return str;
}
// Quote the string and return it.
StringBuilder builder = new StringBuilder();
builder.Append('"');
foreach(char ch2 in str)
{
if(ch2 == '"')
{
builder.Append('"');
builder.Append('"');
}
else
{
builder.Append(ch2);
}
}
builder.Append('"');
return builder.ToString();
}
// Convert an argv array into an argument string, with appropriate quoting.
internal static String ArgVToArguments
(String[] argv, int startIndex, String separator)
{
if(argv == null)
{
return String.Empty;
}
StringBuilder builder = new StringBuilder();
int index = startIndex;
while(index < argv.Length)
{
if(index > startIndex)
{
builder.Append(separator);
}
builder.Append(Quote(argv[index]));
++index;
}
return builder.ToString();
}
// Convert an argument string into an argv array, undoing quoting.
internal static String[] ArgumentsToArgV(String arguments)
{
// Handle the null case first.
if(arguments == null)
{
return new String [0];
}
// Count the number of arguments in the string.
int count = 0;
int posn = 0;
char ch, quotech;
while(posn < arguments.Length)
{
ch = arguments[posn];
if(Char.IsWhiteSpace(ch))
{
++posn;
continue;
}
++count;
if(ch == '"' || ch == '\'')
{
// Start of a quoted argument.
++posn;
quotech = ch;
while(posn < arguments.Length)
{
ch = arguments[posn];
if(ch == quotech)
{
if((posn + 1) < arguments.Length &&
arguments[posn + 1] == quotech)
{
// Escaped quote character.
++posn;
}
else
{
// End of quoted sequence.
++posn;
break;
}
}
++posn;
}
}
else
{
// Start of an unquoted argument.
while(posn < arguments.Length)
{
ch = arguments[posn];
if(Char.IsWhiteSpace(ch) ||
ch == '"' || ch == '\'')
{
break;
}
++posn;
}
}
}
// Create the argument array and populate it.
String[] argv = new String [count];
StringBuilder builder;
int start;
count = 0;
posn = 0;
while(posn < arguments.Length)
{
ch = arguments[posn];
if(Char.IsWhiteSpace(ch))
{
++posn;
continue;
}
if(ch == '"' || ch == '\'')
{
// Start of a quoted argument.
++posn;
quotech = ch;
builder = new StringBuilder();
while(posn < arguments.Length)
{
ch = arguments[posn];
if(ch == quotech)
{
if((posn + 1) < arguments.Length &&
arguments[posn + 1] == quotech)
{
// Escaped quote character.
builder.Append(ch);
++posn;
}
else
{
// End of quoted sequence.
++posn;
break;
}
}
else
{
builder.Append(ch);
}
++posn;
}
argv[count++] = builder.ToString();
}
else
{
// Start of an unquoted argument.
start = posn;
while(posn < arguments.Length)
{
ch = arguments[posn];
if(Char.IsWhiteSpace(ch) ||
ch == '"' || ch == '\'')
{
break;
}
++posn;
}
argv[count++] = arguments.Substring
(start, posn - start);
}
}
// Return the argument array to the caller.
return argv;
}
}; // class ProcessStartInfo
#endif // CONFIG_EXTENDED_DIAGNOSTICS
}; // namespace System.Diagnostics
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Windows.Forms;
using System.IO;
using WeifenLuo.WinFormsUI.Docking;
using Scintilla;
using Scintilla.Forms;
using Scintilla.Enums;
using Scintilla.Configuration;
using MyMeta;
namespace MyGeneration.UI.Plugins.SqlTool
{
public partial class SqlToolUserControl : UserControl
{
private IMyGenerationMDI _mdi;
private ScintillaConfig _scintillaConfig;
private string _filename = string.Empty;
private string _fileId;
private string _dbDriver = null;
private string _connString = null;
private string _databaseName = null;
private string _commandSeperator = "GO";
private List<string> _databaseNames = new List<string>();
private bool _isNew = true;
private bool _isUsingCurrentConnection = false;
public SqlToolUserControl()
{
InitializeComponent();
_scintillaConfig = new ScintillaConfig();
this.scintilla.Configure = _scintillaConfig.Configure;
this.scintilla.ConfigurationLanguage = "sql";
this.scintilla.SmartIndentType = SmartIndent.Simple;
}
public void Initialize(IMyGenerationMDI mdi, ToolStripItemCollection menuItems)
{
this.scintilla.AddShortcuts(menuItems);
this._fileId = Guid.NewGuid().ToString();
_mdi = mdi;
RefreshConnectionInfo();
}
public dbRoot CurrentDbRoot()
{
dbRoot mymeta = null;
try
{
mymeta = _mdi.PerformMdiFunction(this.Parent as IMyGenContent, "getstaticdbroot") as dbRoot;
_isUsingCurrentConnection = true;
if (!(mymeta is dbRoot))
{
mymeta = new dbRoot();
mymeta.Connect(DbDriver, ConnectionString);
_isUsingCurrentConnection = false;
}
}
catch (Exception ex)
{
this._mdi.ErrorList.AddErrors(ex);
}
return mymeta;
}
public IDbConnection OpenConnection()
{
return OpenConnection(null);
}
public IDbConnection OpenConnection(string database)
{
//dbRoot mymeta = new dbRoot();
dbRoot mymeta = CurrentDbRoot();
IDbConnection _connection = null;
try
{
// special code to handle databases that cannot have multiple open connections.
object v = mymeta.PluginSpecificData(DbDriver, "requiresinternalconnection");
if (v != null && v.GetType() == typeof(bool))
{
if ((bool)v)
{
_connection = mymeta.PluginSpecificData(DbDriver, "internalconnection") as IDbConnection;
}
}
// The standard connection code.
if (_connection == null)
{
_connection = mymeta.BuildConnection(DbDriver, ConnectionString);
}
if (_connection != null)
{
if (_connection.State != ConnectionState.Open)
{
_connection.Open();
}
if (!string.IsNullOrEmpty(database))
{
mymeta.ChangeDatabase(_connection, database);
}
}
}
catch (Exception ex)
{
this._mdi.ErrorList.AddErrors(ex);
}
return _connection;
}
public void CloseConnection(IDbConnection connection)
{
if (_isUsingCurrentConnection)
{
connection.Close();
connection.Dispose();
connection = null;
}
}
public bool IsEmpty
{
get { return (this.scintilla.Length == 0); }
}
public bool IsNew
{
get { return (this._isNew); }
}
public List<string> DatabaseNames
{
get
{
return _databaseNames;
}
}
public string CommandSeperator
{
get
{
return _commandSeperator;
}
set
{
this._commandSeperator = value;
}
}
public string SelectedDatabase
{
get
{
return _databaseName;
}
set
{
this._databaseName = value;
}
}
public string ConnectionString
{
get
{
if (_connString == null)
{
_connString = _mdi.PerformMdiFunction(this.Parent as IMyGenContent, "getmymetaconnection") as String;
}
return _connString;
}
}
public string DbDriver
{
get
{
if (_dbDriver == null)
{
_dbDriver = _mdi.PerformMdiFunction(this.Parent as IMyGenContent, "getmymetadbdriver") as String;
}
return _dbDriver;
}
}
public void RefreshConnectionInfo()
{
_dbDriver = null;
_connString = null;
dbRoot mymeta = CurrentDbRoot();
_databaseNames.Clear();
if (mymeta.Databases != null)
{
foreach (IDatabase db in mymeta.Databases)
{
_databaseNames.Add(db.Name);
}
if (mymeta.Databases.Count >= 1)
{
try
{
//show databases dropdown - select current
if (mymeta.DefaultDatabase != null && (string.IsNullOrEmpty(_databaseName)) || (!_databaseNames.Contains(_databaseName)))
{
this._databaseName = mymeta.DefaultDatabase.Name;
}
}
catch (Exception)
{
this._databaseName = mymeta.Databases[0].Name;
}
}
}
}
public void Open(string filename)
{
this._filename = filename;
if (File.Exists(_filename))
{
try
{
this.scintilla.Clear();
this.scintilla.Text = File.ReadAllText(_filename);
_isNew = false;
SetClean();
}
catch (Exception x)
{
_mdi.Console.Write(x);
_isNew = true;
}
}
}
public List<string> SqlToExecute
{
get
{
List<string> commands = new List<string>();
StringBuilder sb = new StringBuilder();
string exectext = this.scintilla.GetSelectedText();
if (string.IsNullOrEmpty(exectext))
{
if (string.IsNullOrEmpty(this.CommandSeperator))
{
commands.Add(scintilla.Text);
}
else
{
for (int i = 0; i < scintilla.LineCount; i++)
{
string line = scintilla.Line[i].TrimEnd('\r', '\n');
if (line.TrimEnd() == CommandSeperator)
{
exectext = sb.ToString().Trim();
if (exectext.Length > 0)
{
commands.Add(exectext);
}
sb.Remove(0, sb.Length);
}
else
{
sb.AppendLine(line);
}
}
exectext = sb.ToString().Trim();
if (exectext.Length > 0)
{
commands.Add(exectext);
}
}
}
else
{
if (string.IsNullOrEmpty(this.CommandSeperator))
{
commands.Add(exectext);
}
else
{
string[] lines = exectext.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i].TrimEnd('\r', '\n');
if (line.TrimEnd() == CommandSeperator)
{
exectext = sb.ToString().Trim();
if (exectext.Length > 0)
{
commands.Add(exectext);
}
sb.Remove(0, sb.Length);
}
else
{
sb.AppendLine(line);
}
}
exectext = sb.ToString().Trim();
if (exectext.Length > 0)
{
commands.Add(exectext);
}
}
}
return commands;
}
}
private void FileSave()
{
if (!string.IsNullOrEmpty(this.FileName))
{
string path = this.FileName;
FileInfo fi = new FileInfo(path);
if (fi.Exists && fi.IsReadOnly)
{
MessageBox.Show(this, "File is read only.");
this._mdi.Console.Write("File \"{0}\" is read only, cannot save.", fi.FullName);
}
else
{
try
{
File.WriteAllText(path, scintilla.Text);
SetClean();
}
catch (Exception ex)
{
MessageBox.Show(this, "Error saving file. " + ex.Message);
this._mdi.Console.Write(ex);
}
}
}
}
private void FileSaveAs(string path)
{
bool isopen = _mdi.IsDocumentOpen(path, this.Parent as IMyGenDocument);
if (!isopen)
{
FileInfo fi = new FileInfo(path);
if (fi.Exists)
{
if (fi.IsReadOnly)
{
MessageBox.Show(this, "File is read only, cannot save.");
this._mdi.Console.Write("File \"{0}\" is read only, cannot save.", fi.FullName);
}
else
{
try
{
File.WriteAllText(path, scintilla.Text);
this._filename = path;
SetClean();
}
catch (Exception ex)
{
MessageBox.Show(this, "Error saving file. " + ex.Message);
this._mdi.Console.Write("Error saving file.");
this._mdi.Console.Write(ex);
}
}
}
}
else
{
MessageBox.Show(this, "The template you are trying to overwrite is currently open.\r\nClose the editor window for that template if you want to overwrite it.");
}
}
public void Save()
{
if (this._isNew)
{
this.SaveAs();
}
else
{
this.FileSave();
}
this.scintilla.GrabFocus();
}
public void SaveAs()
{
Stream myStream;
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "SQL Files (*.sql)|*.sql|All files (*.*)|*.*";
saveFileDialog.FilterIndex = 1;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.FileName = this.FileName;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
myStream = saveFileDialog.OpenFile();
if (null != myStream)
{
myStream.Close();
this.FileSaveAs(saveFileDialog.FileName);
_isNew = false;
}
}
this.scintilla.GrabFocus();
}
public void Execute()
{
for (int i = (this.tabControlResults.TabPages.Count-1); i > 0 ; i--)
{
this.tabControlResults.TabPages.RemoveAt(i);
}
IDbConnection conn = null;
IDataReader r = null;
int resultSetIndex = 0, numRows = 0, gridIndex = 1;
try
{
conn = OpenConnection(_databaseName);
List<string> sqlCommands = this.SqlToExecute;
foreach (string sql in sqlCommands)
{
if (conn == null)
{
conn = OpenConnection(_databaseName);
}
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
IDbCommand db = conn.CreateCommand();
db.CommandText = sql;
r = db.ExecuteReader();
do
{
DataGridView dgv;
if (resultSetIndex > 0)
{
dgv = new DataGridView();
dgv.Dock = DockStyle.Fill;
dgv.AllowUserToAddRows = false;
dgv.AllowUserToDeleteRows = false;
dgv.AllowUserToOrderColumns = true;
dgv.ClipboardCopyMode = System.Windows.Forms.DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
dgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dgv.ReadOnly = true;
}
else
{
dgv = this.dataGridViewResults;
}
dgv.Rows.Clear();
dgv.Columns.Clear();
int rowindex = 0;
if ((r != null) && (!r.IsClosed))
{
while (r.Read())
{
if (rowindex == 0)
{
for (int i = 0; i < r.FieldCount; i++)
{
dgv.Columns.Add(r.GetName(i), r.GetName(i));
}
}
dgv.Rows.Add();
for (int i = 0; i < r.FieldCount; i++)
{
dgv.Rows[rowindex].Cells[i].Value = r[i];
}
rowindex++;
numRows++;
}
}
if (resultSetIndex > 0)
{
if (rowindex > 0)
{
string post = (++gridIndex).ToString().PadLeft(2, '0');
dgv.Name = "dataGridViewResults" + post;
TabPage ntp = new TabPage("Results " + post);
ntp.Controls.Add(dgv);
this.tabControlResults.TabPages.Add(ntp);
}
else
{
dgv.Dispose();
dgv = null;
}
}
resultSetIndex++;
} while (r.NextResult());
r.Close();
r.Dispose();
if (numRows == 0)
{
dataGridViewResults.Columns.Add("Result", "Result");
dataGridViewResults.Rows.Add();
dataGridViewResults.Rows[0].Cells[0].Value = "";
}
}
CloseConnection(conn);
}
catch (Exception ex)
{
if (r != null) r.Dispose();
if (conn != null) conn.Dispose();
dataGridViewResults.Rows.Clear();
dataGridViewResults.Columns.Clear();
dataGridViewResults.Columns.Add("Error", "Error");
dataGridViewResults.Rows.Add();
dataGridViewResults.Rows[0].Cells[0].Value = ex.Message;
this._mdi.ErrorList.AddErrors(ex);
}
}
public string FileName
{
get
{
return _filename;
}
}
public bool IsDirty
{
get
{
return (this.scintilla.IsModify);
}
}
public string DocumentIndentity
{
get { return string.IsNullOrEmpty(_filename) ? _fileId : _filename; }
}
public string TextContent
{
get
{
return scintilla.Text;
}
set
{
this.scintilla.Text = value;
}
}
protected void SetClean()
{
scintilla.EmptyUndoBuffer();
scintilla.SetSavePoint();
}
public void Cut()
{
if (this.scintilla.Focused)
{
this.scintilla.Cut();
}
}
public void Copy()
{
if (this.scintilla.Focused)
{
this.scintilla.Copy();
}
}
public void Paste()
{
if (this.scintilla.Focused)
{
this.scintilla.Paste();
}
}
}
}
| |
//----------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.Generic;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Diagnostics;
using System.ServiceModel.Diagnostics;
using System.Xml;
using System.Threading;
abstract class ReplyOverDuplexChannelListenerBase<TOuterChannel, TInnerChannel> : LayeredChannelListener<TOuterChannel>
where TOuterChannel : class, IReplyChannel
where TInnerChannel : class, IDuplexChannel
{
IChannelListener<TInnerChannel> innerChannelListener;
public ReplyOverDuplexChannelListenerBase(BindingContext context)
: base(context.Binding, context.BuildInnerChannelListener<TInnerChannel>())
{
}
protected override void OnOpening()
{
this.innerChannelListener = (IChannelListener<TInnerChannel>)this.InnerChannelListener;
base.OnOpening();
}
protected override TOuterChannel OnAcceptChannel(TimeSpan timeout)
{
TInnerChannel innerChannel = this.innerChannelListener.AcceptChannel(timeout);
return WrapInnerChannel(innerChannel);
}
protected override IAsyncResult OnBeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.innerChannelListener.BeginAcceptChannel(timeout, callback, state);
}
protected override TOuterChannel OnEndAcceptChannel(IAsyncResult result)
{
TInnerChannel innerChannel = this.innerChannelListener.EndAcceptChannel(result);
return WrapInnerChannel(innerChannel);
}
protected override bool OnWaitForChannel(TimeSpan timeout)
{
return this.innerChannelListener.WaitForChannel(timeout);
}
protected override IAsyncResult OnBeginWaitForChannel(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.innerChannelListener.BeginWaitForChannel(timeout, callback, state);
}
protected override bool OnEndWaitForChannel(IAsyncResult result)
{
return this.innerChannelListener.EndWaitForChannel(result);
}
protected abstract TOuterChannel CreateWrappedChannel(ChannelManagerBase channelManager, TInnerChannel innerChannel);
TOuterChannel WrapInnerChannel(TInnerChannel innerChannel)
{
if (innerChannel == null)
{
return null;
}
else
{
return CreateWrappedChannel(this, innerChannel);
}
}
}
class ReplyOverDuplexChannelListener : ReplyOverDuplexChannelListenerBase<IReplyChannel, IDuplexChannel>
{
public ReplyOverDuplexChannelListener(BindingContext context)
: base(context)
{
}
protected override IReplyChannel CreateWrappedChannel(ChannelManagerBase channelManager, IDuplexChannel innerChannel)
{
return new ReplyOverDuplexChannel(channelManager, innerChannel);
}
}
class ReplySessionOverDuplexSessionChannelListener : ReplyOverDuplexChannelListenerBase<IReplySessionChannel, IDuplexSessionChannel>
{
public ReplySessionOverDuplexSessionChannelListener(BindingContext context)
: base(context)
{
}
protected override IReplySessionChannel CreateWrappedChannel(ChannelManagerBase channelManager, IDuplexSessionChannel innerChannel)
{
return new ReplySessionOverDuplexSessionChannel(channelManager, innerChannel);
}
}
abstract class ReplyOverDuplexChannelBase<TInnerChannel> : LayeredChannel<TInnerChannel>, IReplyChannel
where TInnerChannel : class, IDuplexChannel
{
public ReplyOverDuplexChannelBase(ChannelManagerBase channelManager, TInnerChannel innerChannel)
: base(channelManager, innerChannel)
{
}
public EndpointAddress LocalAddress
{
get
{
return this.InnerChannel.LocalAddress;
}
}
public RequestContext ReceiveRequest()
{
return ReceiveRequest(this.DefaultReceiveTimeout);
}
public RequestContext ReceiveRequest(TimeSpan timeout)
{
return ReplyChannel.HelpReceiveRequest(this, timeout);
}
public IAsyncResult BeginReceiveRequest(AsyncCallback callback, object state)
{
return BeginReceiveRequest(this.DefaultReceiveTimeout, callback, state);
}
public IAsyncResult BeginReceiveRequest(TimeSpan timeout, AsyncCallback callback, object state)
{
return ReplyChannel.HelpBeginReceiveRequest(this, timeout, callback, state);
}
public RequestContext EndReceiveRequest(IAsyncResult result)
{
return ReplyChannel.HelpEndReceiveRequest(result);
}
public bool TryReceiveRequest(TimeSpan timeout, out RequestContext context)
{
Message message;
if (!this.InnerChannel.TryReceive(timeout, out message))
{
context = null;
return false;
}
context = WrapInnerMessage(message);
return true;
}
public IAsyncResult BeginTryReceiveRequest(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.InnerChannel.BeginTryReceive(timeout, callback, state);
}
public bool EndTryReceiveRequest(IAsyncResult result, out RequestContext context)
{
Message message;
if (!this.InnerChannel.EndTryReceive(result, out message))
{
context = null;
return false;
}
context = WrapInnerMessage(message);
return true;
}
public bool WaitForRequest(TimeSpan timeout)
{
return this.InnerChannel.WaitForMessage(timeout);
}
public IAsyncResult BeginWaitForRequest(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.InnerChannel.BeginWaitForMessage(timeout, callback, state);
}
public bool EndWaitForRequest(IAsyncResult result)
{
return this.InnerChannel.EndWaitForMessage(result);
}
RequestContext WrapInnerMessage(Message message)
{
if (message == null)
{
return null;
}
else
{
return new DuplexRequestContext(message, this.Manager, this.InnerChannel);
}
}
class DuplexRequestContext : RequestContext
{
IDuplexChannel innerChannel;
IDefaultCommunicationTimeouts defaultTimeouts;
Message request;
EndpointAddress replyTo;
bool disposed;
Object thisLock;
public DuplexRequestContext(Message request, IDefaultCommunicationTimeouts defaultTimeouts, IDuplexChannel innerChannel)
{
this.request = request;
this.defaultTimeouts = defaultTimeouts;
this.innerChannel = innerChannel;
if (request != null)
{
replyTo = request.Headers.ReplyTo;
}
thisLock = new Object();
}
public override Message RequestMessage
{
get
{
return this.request;
}
}
public override void Abort()
{
Dispose(true);
}
public override void Close()
{
this.Close(this.defaultTimeouts.CloseTimeout);
}
public override void Close(TimeSpan timeout)
{
this.Dispose(true);
}
public override void Reply(Message message)
{
this.Reply(message, this.defaultTimeouts.SendTimeout);
}
public override void Reply(Message message, TimeSpan timeout)
{
PrepareReply(message);
this.innerChannel.Send(message);
}
public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state)
{
return BeginReply(message, this.defaultTimeouts.SendTimeout, callback, state);
}
public override IAsyncResult BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
PrepareReply(message);
return this.innerChannel.BeginSend(message, timeout, callback, state);
}
public override void EndReply(IAsyncResult result)
{
this.innerChannel.EndSend(result);
}
void PrepareReply(Message message)
{
if (this.replyTo != null)
{
this.replyTo.ApplyTo(message);
}
}
protected override void Dispose(bool disposing)
{
bool cleanup = false;
lock (thisLock)
{
if (!disposed)
{
this.disposed = true;
cleanup = true;
}
}
if (cleanup && this.request != null)
{
this.request.Close();
}
}
}
}
class ReplyOverDuplexChannel : ReplyOverDuplexChannelBase<IDuplexChannel>
{
public ReplyOverDuplexChannel(ChannelManagerBase channelManager, IDuplexChannel innerChannel)
: base(channelManager, innerChannel)
{
}
}
class ReplySessionOverDuplexSessionChannel : ReplyOverDuplexChannelBase<IDuplexSessionChannel>, IReplySessionChannel
{
ReplySessionOverDuplexSession session;
public ReplySessionOverDuplexSessionChannel(ChannelManagerBase channelManager, IDuplexSessionChannel innerChannel)
: base(channelManager, innerChannel)
{
this.session = new ReplySessionOverDuplexSession(innerChannel.Session);
}
public IInputSession Session
{
get
{
return this.session;
}
}
class ReplySessionOverDuplexSession : IInputSession
{
IDuplexSession innerSession;
public ReplySessionOverDuplexSession(IDuplexSession innerSession)
{
if (innerSession == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerSession");
}
this.innerSession = innerSession;
}
public string Id
{
get
{
return this.innerSession.Id;
}
}
}
}
class ReplyAdapterBindingElement : BindingElement
{
public ReplyAdapterBindingElement()
{
}
public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
{
if (!this.CanBuildChannelListener<TChannel>(context))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
if (context.CanBuildInnerChannelListener<IReplySessionChannel>() ||
context.CanBuildInnerChannelListener<IReplyChannel>())
{
return context.BuildInnerChannelListener<TChannel>();
}
else if ((typeof(TChannel) == typeof(IReplySessionChannel)) && context.CanBuildInnerChannelListener<IDuplexSessionChannel>())
{
return (IChannelListener<TChannel>)new ReplySessionOverDuplexSessionChannelListener(context);
}
else if ((typeof(TChannel) == typeof(IReplyChannel)) && context.CanBuildInnerChannelListener<IDuplexChannel>())
{
return (IChannelListener<TChannel>)new ReplyOverDuplexChannelListener(context);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
}
public override bool CanBuildChannelListener<TChannel>(BindingContext context)
{
if (typeof(TChannel) == typeof(IReplySessionChannel))
{
return (context.CanBuildInnerChannelListener<IReplySessionChannel>()
|| context.CanBuildInnerChannelListener<IDuplexSessionChannel>());
}
else if (typeof(TChannel) == typeof(IReplyChannel))
{
return (context.CanBuildInnerChannelListener<IReplyChannel>()
|| context.CanBuildInnerChannelListener<IDuplexChannel>());
}
else
{
return false;
}
}
public override BindingElement Clone()
{
return new ReplyAdapterBindingElement();
}
public override T GetProperty<T>(BindingContext context)
{
return context.GetInnerProperty<T>();
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the RequestSpotInstances operation.
/// Creates a Spot instance request. Spot instances are instances that Amazon EC2 launches
/// when the bid price that you specify exceeds the current Spot price. Amazon EC2 periodically
/// sets the Spot price based on available Spot Instance capacity and current Spot instance
/// requests. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html">Spot
/// Instance Requests</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </summary>
public partial class RequestSpotInstancesRequest : AmazonEC2Request
{
private string _availabilityZoneGroup;
private int? _blockDurationMinutes;
private string _clientToken;
private int? _instanceCount;
private string _launchGroup;
private LaunchSpecification _launchSpecification;
private string _spotPrice;
private SpotInstanceType _type;
private DateTime? _validFrom;
private DateTime? _validUntil;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public RequestSpotInstancesRequest() { }
/// <summary>
/// Instantiates RequestSpotInstancesRequest with the parameterized properties
/// </summary>
/// <param name="spotPrice">The maximum hourly price (bid) for any Spot instance launched to fulfill the request.</param>
public RequestSpotInstancesRequest(string spotPrice)
{
_spotPrice = spotPrice;
}
/// <summary>
/// Gets and sets the property AvailabilityZoneGroup.
/// <para>
/// The user-specified name for a logical grouping of bids.
/// </para>
///
/// <para>
/// When you specify an Availability Zone group in a Spot Instance request, all Spot instances
/// in the request are launched in the same Availability Zone. Instance proximity is maintained
/// with this parameter, but the choice of Availability Zone is not. The group applies
/// only to bids for Spot Instances of the same instance type. Any additional Spot instance
/// requests that are specified with the same Availability Zone group name are launched
/// in that same Availability Zone, as long as at least one instance from the group is
/// still active.
/// </para>
///
/// <para>
/// If there is no active instance running in the Availability Zone group that you specify
/// for a new Spot instance request (all instances are terminated, the bid is expired,
/// or the bid falls below current market), then Amazon EC2 launches the instance in any
/// Availability Zone where the constraint can be met. Consequently, the subsequent set
/// of Spot instances could be placed in a different zone from the original request, even
/// if you specified the same Availability Zone group.
/// </para>
///
/// <para>
/// Default: Instances are launched in any available Availability Zone.
/// </para>
/// </summary>
public string AvailabilityZoneGroup
{
get { return this._availabilityZoneGroup; }
set { this._availabilityZoneGroup = value; }
}
// Check to see if AvailabilityZoneGroup property is set
internal bool IsSetAvailabilityZoneGroup()
{
return this._availabilityZoneGroup != null;
}
/// <summary>
/// Gets and sets the property BlockDurationMinutes.
/// <para>
/// The required duration for the Spot instances, in minutes. This value must be a multiple
/// of 60 (60, 120, 180, 240, 300, or 360).
/// </para>
///
/// <para>
/// The duration period starts as soon as your Spot instance receives its instance ID.
/// At the end of the duration period, Amazon EC2 marks the Spot instance for termination
/// and provides a Spot instance termination notice, which gives the instance a two-minute
/// warning before it terminates.
/// </para>
///
/// <para>
/// Note that you can't specify an Availability Zone group or a launch group if you specify
/// a duration.
/// </para>
/// </summary>
public int BlockDurationMinutes
{
get { return this._blockDurationMinutes.GetValueOrDefault(); }
set { this._blockDurationMinutes = value; }
}
// Check to see if BlockDurationMinutes property is set
internal bool IsSetBlockDurationMinutes()
{
return this._blockDurationMinutes.HasValue;
}
/// <summary>
/// Gets and sets the property ClientToken.
/// <para>
/// Unique, case-sensitive identifier that you provide to ensure the idempotency of the
/// request. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html">How
/// to Ensure Idempotency</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public string ClientToken
{
get { return this._clientToken; }
set { this._clientToken = value; }
}
// Check to see if ClientToken property is set
internal bool IsSetClientToken()
{
return this._clientToken != null;
}
/// <summary>
/// Gets and sets the property InstanceCount.
/// <para>
/// The maximum number of Spot instances to launch.
/// </para>
///
/// <para>
/// Default: 1
/// </para>
/// </summary>
public int InstanceCount
{
get { return this._instanceCount.GetValueOrDefault(); }
set { this._instanceCount = value; }
}
// Check to see if InstanceCount property is set
internal bool IsSetInstanceCount()
{
return this._instanceCount.HasValue;
}
/// <summary>
/// Gets and sets the property LaunchGroup.
/// <para>
/// The instance launch group. Launch groups are Spot instances that launch together and
/// terminate together.
/// </para>
///
/// <para>
/// Default: Instances are launched and terminated individually
/// </para>
/// </summary>
public string LaunchGroup
{
get { return this._launchGroup; }
set { this._launchGroup = value; }
}
// Check to see if LaunchGroup property is set
internal bool IsSetLaunchGroup()
{
return this._launchGroup != null;
}
/// <summary>
/// Gets and sets the property LaunchSpecification.
/// </summary>
public LaunchSpecification LaunchSpecification
{
get { return this._launchSpecification; }
set { this._launchSpecification = value; }
}
// Check to see if LaunchSpecification property is set
internal bool IsSetLaunchSpecification()
{
return this._launchSpecification != null;
}
/// <summary>
/// Gets and sets the property SpotPrice.
/// <para>
/// The maximum hourly price (bid) for any Spot instance launched to fulfill the request.
/// </para>
/// </summary>
public string SpotPrice
{
get { return this._spotPrice; }
set { this._spotPrice = value; }
}
// Check to see if SpotPrice property is set
internal bool IsSetSpotPrice()
{
return this._spotPrice != null;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The Spot instance request type.
/// </para>
///
/// <para>
/// Default: <code>one-time</code>
/// </para>
/// </summary>
public SpotInstanceType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
/// <summary>
/// Gets and sets the property ValidFrom.
/// <para>
/// The start date of the request. If this is a one-time request, the request becomes
/// active at this date and time and remains active until all instances launch, the request
/// expires, or the request is canceled. If the request is persistent, the request becomes
/// active at this date and time and remains active until it expires or is canceled.
/// </para>
///
/// <para>
/// Default: The request is effective indefinitely.
/// </para>
/// </summary>
public DateTime ValidFrom
{
get { return this._validFrom.GetValueOrDefault(); }
set { this._validFrom = value; }
}
// Check to see if ValidFrom property is set
internal bool IsSetValidFrom()
{
return this._validFrom.HasValue;
}
/// <summary>
/// Gets and sets the property ValidUntil.
/// <para>
/// The end date of the request. If this is a one-time request, the request remains active
/// until all instances launch, the request is canceled, or this date is reached. If the
/// request is persistent, it remains active until it is canceled or this date and time
/// is reached.
/// </para>
///
/// <para>
/// Default: The request is effective indefinitely.
/// </para>
/// </summary>
public DateTime ValidUntil
{
get { return this._validUntil.GetValueOrDefault(); }
set { this._validUntil = value; }
}
// Check to see if ValidUntil property is set
internal bool IsSetValidUntil()
{
return this._validUntil.HasValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
internal interface IContentFocusManager
{
void Activate(IDockContent content);
void GiveUpFocus(IDockContent content);
void AddToList(IDockContent content);
void RemoveFromList(IDockContent content);
}
partial class DockPanel
{
private interface IFocusManager
{
void SuspendFocusTracking();
void ResumeFocusTracking();
bool IsFocusTrackingSuspended { get; }
IDockContent ActiveContent { get; }
DockPane ActivePane { get; }
IDockContent ActiveDocument { get; }
DockPane ActiveDocumentPane { get; }
}
private class FocusManagerImpl : Component, IContentFocusManager, IFocusManager
{
private class HookEventArgs : EventArgs
{
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
public int HookCode;
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
public IntPtr wParam;
public IntPtr lParam;
}
private class LocalWindowsHook : IDisposable
{
// Internal properties
private IntPtr m_hHook = IntPtr.Zero;
private NativeMethods.HookProc m_filterFunc = null;
private Win32.HookType m_hookType;
// Event delegate
public delegate void HookEventHandler(object sender, HookEventArgs e);
// Event: HookInvoked
public event HookEventHandler HookInvoked;
protected void OnHookInvoked(HookEventArgs e)
{
if (HookInvoked != null)
HookInvoked(this, e);
}
public LocalWindowsHook(Win32.HookType hook)
{
m_hookType = hook;
m_filterFunc = new NativeMethods.HookProc(this.CoreHookProc);
}
// Default filter function
public IntPtr CoreHookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0)
return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam);
// Let clients determine what to do
HookEventArgs e = new HookEventArgs();
e.HookCode = code;
e.wParam = wParam;
e.lParam = lParam;
OnHookInvoked(e);
// Yield to the next hook in the chain
return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam);
}
// Install the hook
public void Install()
{
if (m_hHook != IntPtr.Zero)
Uninstall();
int threadId = NativeMethods.GetCurrentThreadId();
m_hHook = NativeMethods.SetWindowsHookEx(m_hookType, m_filterFunc, IntPtr.Zero, threadId);
}
// Uninstall the hook
public void Uninstall()
{
if (m_hHook != IntPtr.Zero)
{
NativeMethods.UnhookWindowsHookEx(m_hHook);
m_hHook = IntPtr.Zero;
}
}
~LocalWindowsHook()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
Uninstall();
}
}
// Use a static instance of the windows hook to prevent stack overflows in the windows kernel.
[ThreadStatic]
private static LocalWindowsHook sm_localWindowsHook;
private readonly LocalWindowsHook.HookEventHandler m_hookEventHandler;
public FocusManagerImpl(DockPanel dockPanel)
{
m_dockPanel = dockPanel;
if (Win32Helper.IsRunningOnMono)
return;
m_hookEventHandler = new LocalWindowsHook.HookEventHandler(HookEventHandler);
// Ensure the windows hook has been created for this thread
if (sm_localWindowsHook == null)
{
sm_localWindowsHook = new LocalWindowsHook(Win32.HookType.WH_CALLWNDPROCRET);
sm_localWindowsHook.Install();
}
sm_localWindowsHook.HookInvoked += m_hookEventHandler;
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private bool m_disposed = false;
protected override void Dispose(bool disposing)
{
if (!m_disposed && disposing)
{
if (!Win32Helper.IsRunningOnMono)
{
sm_localWindowsHook.HookInvoked -= m_hookEventHandler;
}
m_disposed = true;
}
base.Dispose(disposing);
}
private IDockContent m_contentActivating = null;
private IDockContent ContentActivating
{
get { return m_contentActivating; }
set { m_contentActivating = value; }
}
public void Activate(IDockContent content)
{
if (IsFocusTrackingSuspended)
{
ContentActivating = content;
return;
}
if (content == null)
return;
DockContentHandler handler = content.DockHandler;
if (handler.Form.IsDisposed)
return; // Should not reach here, but better than throwing an exception
if (ContentContains(content, handler.ActiveWindowHandle))
{
if (!Win32Helper.IsRunningOnMono)
{
NativeMethods.SetFocus(handler.ActiveWindowHandle);
}
}
if (handler.Form.ContainsFocus)
return;
if (handler.Form.SelectNextControl(handler.Form.ActiveControl, true, true, true, true))
return;
if (Win32Helper.IsRunningOnMono)
return;
// Since DockContent Form is not selectalbe, use Win32 SetFocus instead
NativeMethods.SetFocus(handler.Form.Handle);
}
private List<IDockContent> m_listContent = new List<IDockContent>();
private List<IDockContent> ListContent
{
get { return m_listContent; }
}
public void AddToList(IDockContent content)
{
if (ListContent.Contains(content) || IsInActiveList(content))
return;
ListContent.Add(content);
}
public void RemoveFromList(IDockContent content)
{
if (IsInActiveList(content))
RemoveFromActiveList(content);
if (ListContent.Contains(content))
ListContent.Remove(content);
}
private IDockContent m_lastActiveContent = null;
private IDockContent LastActiveContent
{
get { return m_lastActiveContent; }
set { m_lastActiveContent = value; }
}
private bool IsInActiveList(IDockContent content)
{
return !(content.DockHandler.NextActive == null && LastActiveContent != content);
}
private void AddLastToActiveList(IDockContent content)
{
IDockContent last = LastActiveContent;
if (last == content)
return;
DockContentHandler handler = content.DockHandler;
if (IsInActiveList(content))
RemoveFromActiveList(content);
handler.PreviousActive = last;
handler.NextActive = null;
LastActiveContent = content;
if (last != null)
last.DockHandler.NextActive = LastActiveContent;
}
private void RemoveFromActiveList(IDockContent content)
{
if (LastActiveContent == content)
LastActiveContent = content.DockHandler.PreviousActive;
IDockContent prev = content.DockHandler.PreviousActive;
IDockContent next = content.DockHandler.NextActive;
if (prev != null)
prev.DockHandler.NextActive = next;
if (next != null)
next.DockHandler.PreviousActive = prev;
content.DockHandler.PreviousActive = null;
content.DockHandler.NextActive = null;
}
public void GiveUpFocus(IDockContent content)
{
DockContentHandler handler = content.DockHandler;
if (!handler.Form.ContainsFocus)
return;
if (IsFocusTrackingSuspended)
DockPanel.DummyControl.Focus();
if (LastActiveContent == content)
{
IDockContent prev = handler.PreviousActive;
if (prev != null)
Activate(prev);
else if (ListContent.Count > 0)
Activate(ListContent[ListContent.Count - 1]);
}
else if (LastActiveContent != null)
Activate(LastActiveContent);
else if (ListContent.Count > 0)
Activate(ListContent[ListContent.Count - 1]);
}
private static bool ContentContains(IDockContent content, IntPtr hWnd)
{
Control control = Control.FromChildHandle(hWnd);
for (Control parent = control; parent != null; parent = parent.Parent)
if (parent == content.DockHandler.Form)
return true;
return false;
}
private uint m_countSuspendFocusTracking = 0;
public void SuspendFocusTracking()
{
if (m_disposed)
return;
if (m_countSuspendFocusTracking++ == 0)
{
if (!Win32Helper.IsRunningOnMono)
sm_localWindowsHook.HookInvoked -= m_hookEventHandler;
}
}
public void ResumeFocusTracking()
{
if (m_disposed || m_countSuspendFocusTracking == 0)
return;
if (--m_countSuspendFocusTracking == 0)
{
if (ContentActivating != null)
{
Activate(ContentActivating);
ContentActivating = null;
}
if (!Win32Helper.IsRunningOnMono)
sm_localWindowsHook.HookInvoked += m_hookEventHandler;
if (!InRefreshActiveWindow)
RefreshActiveWindow();
}
}
public bool IsFocusTrackingSuspended
{
get { return m_countSuspendFocusTracking != 0; }
}
// Windows hook event handler
private void HookEventHandler(object sender, HookEventArgs e)
{
Win32.Msgs msg = (Win32.Msgs)Marshal.ReadInt32(e.lParam, IntPtr.Size * 3);
if (msg == Win32.Msgs.WM_KILLFOCUS)
{
IntPtr wParam = Marshal.ReadIntPtr(e.lParam, IntPtr.Size * 2);
DockPane pane = GetPaneFromHandle(wParam);
if (pane == null)
RefreshActiveWindow();
}
else if (msg == Win32.Msgs.WM_SETFOCUS || msg == Win32.Msgs.WM_MDIACTIVATE)
RefreshActiveWindow();
}
private DockPane GetPaneFromHandle(IntPtr hWnd)
{
Control control = Control.FromChildHandle(hWnd);
IDockContent content = null;
DockPane pane = null;
for (; control != null; control = control.Parent)
{
content = control as IDockContent;
if (content != null)
content.DockHandler.ActiveWindowHandle = hWnd;
if (content != null && content.DockHandler.DockPanel == DockPanel)
return content.DockHandler.Pane;
pane = control as DockPane;
if (pane != null && pane.DockPanel == DockPanel)
break;
}
return pane;
}
private bool m_inRefreshActiveWindow = false;
private bool InRefreshActiveWindow
{
get { return m_inRefreshActiveWindow; }
}
private void RefreshActiveWindow()
{
SuspendFocusTracking();
m_inRefreshActiveWindow = true;
DockPane oldActivePane = ActivePane;
IDockContent oldActiveContent = ActiveContent;
IDockContent oldActiveDocument = ActiveDocument;
SetActivePane();
SetActiveContent();
SetActiveDocumentPane();
SetActiveDocument();
DockPanel.AutoHideWindow.RefreshActivePane();
ResumeFocusTracking();
m_inRefreshActiveWindow = false;
if (oldActiveContent != ActiveContent)
DockPanel.OnActiveContentChanged(EventArgs.Empty);
if (oldActiveDocument != ActiveDocument)
DockPanel.OnActiveDocumentChanged(EventArgs.Empty);
if (oldActivePane != ActivePane)
DockPanel.OnActivePaneChanged(EventArgs.Empty);
}
private DockPane m_activePane = null;
public DockPane ActivePane
{
get { return m_activePane; }
}
private void SetActivePane()
{
DockPane value = Win32Helper.IsRunningOnMono ? null : GetPaneFromHandle(NativeMethods.GetFocus());
if (m_activePane == value)
return;
if (m_activePane != null)
m_activePane.SetIsActivated(false);
m_activePane = value;
if (m_activePane != null)
m_activePane.SetIsActivated(true);
}
private IDockContent m_activeContent = null;
public IDockContent ActiveContent
{
get { return m_activeContent; }
}
internal void SetActiveContent()
{
IDockContent value = ActivePane == null ? null : ActivePane.ActiveContent;
if (m_activeContent == value)
return;
if (m_activeContent != null)
m_activeContent.DockHandler.IsActivated = false;
m_activeContent = value;
if (m_activeContent != null)
{
m_activeContent.DockHandler.IsActivated = true;
if (!DockHelper.IsDockStateAutoHide((m_activeContent.DockHandler.DockState)))
AddLastToActiveList(m_activeContent);
}
}
private DockPane m_activeDocumentPane = null;
public DockPane ActiveDocumentPane
{
get { return m_activeDocumentPane; }
}
private void SetActiveDocumentPane()
{
DockPane value = null;
if (ActivePane != null && ActivePane.DockState == DockState.Document)
value = ActivePane;
if (value == null && DockPanel.DockWindows != null)
{
if (ActiveDocumentPane == null)
value = DockPanel.DockWindows[DockState.Document].DefaultPane;
else if (ActiveDocumentPane.DockPanel != DockPanel || ActiveDocumentPane.DockState != DockState.Document)
value = DockPanel.DockWindows[DockState.Document].DefaultPane;
else
value = ActiveDocumentPane;
}
if (m_activeDocumentPane == value)
return;
if (m_activeDocumentPane != null)
m_activeDocumentPane.SetIsActiveDocumentPane(false);
m_activeDocumentPane = value;
if (m_activeDocumentPane != null)
m_activeDocumentPane.SetIsActiveDocumentPane(true);
}
private IDockContent m_activeDocument = null;
public IDockContent ActiveDocument
{
get { return m_activeDocument; }
}
private void SetActiveDocument()
{
IDockContent value = ActiveDocumentPane == null ? null : ActiveDocumentPane.ActiveContent;
if (m_activeDocument == value)
return;
m_activeDocument = value;
}
}
private IFocusManager FocusManager
{
get { return m_focusManager; }
}
internal IContentFocusManager ContentFocusManager
{
get { return m_focusManager; }
}
internal void SaveFocus()
{
DummyControl.Focus();
}
[Browsable(false)]
public IDockContent ActiveContent
{
get { return FocusManager.ActiveContent; }
}
[Browsable(false)]
public DockPane ActivePane
{
get { return FocusManager.ActivePane; }
}
[Browsable(false)]
public IDockContent ActiveDocument
{
get { return FocusManager.ActiveDocument; }
}
[Browsable(false)]
public DockPane ActiveDocumentPane
{
get { return FocusManager.ActiveDocumentPane; }
}
private static readonly object ActiveDocumentChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActiveDocumentChanged_Description")]
public event EventHandler ActiveDocumentChanged
{
add { Events.AddHandler(ActiveDocumentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveDocumentChangedEvent, value); }
}
protected virtual void OnActiveDocumentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveDocumentChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object ActiveContentChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActiveContentChanged_Description")]
public event EventHandler ActiveContentChanged
{
add { Events.AddHandler(ActiveContentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveContentChangedEvent, value); }
}
protected void OnActiveContentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveContentChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object DocumentDraggedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActiveContentChanged_Description")]
public event EventHandler DocumentDragged
{
add { Events.AddHandler(DocumentDraggedEvent, value); }
remove { Events.RemoveHandler(DocumentDraggedEvent, value); }
}
internal void OnDocumentDragged()
{
EventHandler handler = (EventHandler)Events[DocumentDraggedEvent];
if (handler != null)
handler(this, EventArgs.Empty);
}
private static readonly object ActivePaneChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActivePaneChanged_Description")]
public event EventHandler ActivePaneChanged
{
add { Events.AddHandler(ActivePaneChangedEvent, value); }
remove { Events.RemoveHandler(ActivePaneChangedEvent, value); }
}
protected virtual void OnActivePaneChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActivePaneChangedEvent];
if (handler != null)
handler(this, e);
}
}
}
| |
// 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.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.CSharp.Completion.CompletionProviders
{
[ExportCompletionProvider("OverrideCompletionProvider", LanguageNames.CSharp)]
internal partial class OverrideCompletionProvider : AbstractOverrideCompletionProvider, ICustomCommitCompletionProvider
{
[ImportingConstructor]
public OverrideCompletionProvider(
IWaitIndicator waitIndicator)
: base(waitIndicator)
{
}
protected override SyntaxNode GetSyntax(SyntaxToken token)
{
return (SyntaxNode)token.GetAncestor<EventFieldDeclarationSyntax>()
?? (SyntaxNode)token.GetAncestor<EventDeclarationSyntax>()
?? (SyntaxNode)token.GetAncestor<PropertyDeclarationSyntax>()
?? (SyntaxNode)token.GetAncestor<IndexerDeclarationSyntax>()
?? (SyntaxNode)token.GetAncestor<MethodDeclarationSyntax>();
}
protected override TextSpan GetTextChangeSpan(SourceText text, int position)
{
return CompletionUtilities.GetTextChangeSpan(text, position);
}
public override bool SendEnterThroughToEditor(CompletionItem completionItem, string textTypedSoFar)
{
return false;
}
public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options)
{
return CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options);
}
protected override SyntaxToken GetToken(MemberInsertionCompletionItem completionItem, SyntaxTree tree, CancellationToken cancellationToken)
{
var token = completionItem.Token;
return tree.FindTokenOnLeftOfPosition(token.Span.End, cancellationToken);
}
public override bool TryDetermineReturnType(SyntaxToken startToken, SemanticModel semanticModel, CancellationToken cancellationToken, out ITypeSymbol returnType, out SyntaxToken nextToken)
{
nextToken = startToken;
returnType = null;
if (startToken.Parent is TypeSyntax)
{
var typeSyntax = (TypeSyntax)startToken.Parent;
// 'partial' is actually an identifier. If we see it just bail. This does mean
// we won't handle overrides that actually return a type called 'partial'. And
// not a single tear was shed.
if (typeSyntax is IdentifierNameSyntax &&
((IdentifierNameSyntax)typeSyntax).Identifier.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword))
{
return false;
}
returnType = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type;
nextToken = typeSyntax.GetFirstToken().GetPreviousToken();
}
return true;
}
public override bool TryDetermineModifiers(SyntaxToken startToken, SourceText text, int startLine, out Accessibility seenAccessibility,
out DeclarationModifiers modifiers)
{
var token = startToken;
modifiers = new DeclarationModifiers();
seenAccessibility = Accessibility.NotApplicable;
var overrideToken = default(SyntaxToken);
bool isUnsafe = false;
bool isSealed = false;
bool isAbstract = false;
while (IsOnStartLine(token.SpanStart, text, startLine) && !token.IsKind(SyntaxKind.None))
{
switch (token.Kind())
{
case SyntaxKind.UnsafeKeyword:
isUnsafe = true;
break;
case SyntaxKind.OverrideKeyword:
overrideToken = token;
break;
case SyntaxKind.SealedKeyword:
isSealed = true;
break;
case SyntaxKind.AbstractKeyword:
isAbstract = true;
break;
case SyntaxKind.ExternKeyword:
break;
// Filter on the most recently typed accessibility; keep the first one we see
case SyntaxKind.PublicKeyword:
if (seenAccessibility == Accessibility.NotApplicable)
{
seenAccessibility = Accessibility.Public;
}
break;
case SyntaxKind.InternalKeyword:
if (seenAccessibility == Accessibility.NotApplicable)
{
seenAccessibility = Accessibility.Internal;
}
// If we see internal AND protected, filter for protected internal
if (seenAccessibility == Accessibility.Protected)
{
seenAccessibility = Accessibility.ProtectedOrInternal;
}
break;
case SyntaxKind.ProtectedKeyword:
if (seenAccessibility == Accessibility.NotApplicable)
{
seenAccessibility = Accessibility.Protected;
}
// If we see protected AND internal, filter for protected internal
if (seenAccessibility == Accessibility.Internal)
{
seenAccessibility = Accessibility.ProtectedOrInternal;
}
break;
default:
// Anything else and we bail.
return false;
}
var previousToken = token.GetPreviousToken();
// We want only want to consume modifiers
if (previousToken.IsKind(SyntaxKind.None) || !IsOnStartLine(previousToken.SpanStart, text, startLine))
{
break;
}
token = previousToken;
}
startToken = token;
modifiers = new DeclarationModifiers(isUnsafe: isUnsafe, isAbstract: isAbstract, isOverride: true, isSealed: isSealed);
return overrideToken.IsKind(SyntaxKind.OverrideKeyword) && IsOnStartLine(overrideToken.Parent.SpanStart, text, startLine);
}
public override SyntaxToken FindStartingToken(SyntaxTree tree, int position, CancellationToken cancellationToken)
{
var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
return token.GetPreviousTokenIfTouchingWord(position);
}
public override ISet<ISymbol> FilterOverrides(ISet<ISymbol> members, ITypeSymbol returnType)
{
var filteredMembers = new HashSet<ISymbol>(
from m in members
where SymbolEquivalenceComparer.Instance.Equals(GetReturnType(m), returnType)
select m);
// Don't filter by return type if we would then have nothing to show.
// This way, the user gets completion even if they speculatively typed the wrong return type
if (filteredMembers.Count > 0)
{
members = filteredMembers;
}
return members;
}
protected override int GetTargetCaretPosition(SyntaxNode caretTarget)
{
// Inserted Event declarations are a single line, so move to the end of the line.
if (caretTarget is EventFieldDeclarationSyntax)
{
return caretTarget.GetLocation().SourceSpan.End;
}
else if (caretTarget is MethodDeclarationSyntax)
{
var methodDeclaration = (MethodDeclarationSyntax)caretTarget;
// abstract override blah(); : move to the end of the line
if (methodDeclaration.Body == null)
{
return methodDeclaration.GetLocation().SourceSpan.End;
}
else
{
// move to the end of the last statement in the method
var lastStatement = methodDeclaration.Body.Statements.Last();
return lastStatement.GetLocation().SourceSpan.End;
}
}
else if (caretTarget is PropertyDeclarationSyntax)
{
// property: no accesors; move to the end of the declaration
var propertyDeclaration = (PropertyDeclarationSyntax)caretTarget;
if (!propertyDeclaration.AccessorList.Accessors.Any())
{
return propertyDeclaration.GetLocation().SourceSpan.End;
}
else
{
// move to the end of the last statement of the first accessor
var firstAccessorStatement = propertyDeclaration.AccessorList.Accessors.First().Body.Statements.Last();
return firstAccessorStatement.GetLocation().SourceSpan.End;
}
}
else
{
// indexer: move to the end of the last statement
var indexerDeclaration = (IndexerDeclarationSyntax)caretTarget;
var firstAccessorStatement = indexerDeclaration.AccessorList.Accessors.First().Body.Statements.Last();
return firstAccessorStatement.GetLocation().SourceSpan.End;
}
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
namespace SharpDX.IO
{
/// <summary>
/// Windows File Helper.
/// </summary>
public class NativeFileStream : Stream
{
private bool canRead;
private bool canWrite;
private bool canSeek;
private IntPtr handle;
private long position;
/// <summary>
/// Initializes a new instance of the <see cref="NativeFileStream"/> class.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="fileMode">The file mode.</param>
/// <param name="access">The access mode.</param>
/// <param name="share">The share mode.</param>
public unsafe NativeFileStream(string fileName, NativeFileMode fileMode, NativeFileAccess access, NativeFileShare share = NativeFileShare.Read)
{
#if STORE_APP
//uint newAccess = 0;
//const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
//const int FILE_FLAG_RANDOM_ACCESS = 0x10000000;
//const int FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000;
//var extendedParams = default(NativeFile.CREATEFILE2_EXTENDED_PARAMETERS);
//extendedParams.dwSize = (uint)Utilities.SizeOf<NativeFile.CREATEFILE2_EXTENDED_PARAMETERS>();
//extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
//extendedParams.dwFileFlags = FILE_FLAG_RANDOM_ACCESS;
//extendedParams.dwSecurityQosFlags = 0;
//extendedParams.lpSecurityAttributes = IntPtr.Zero;
//extendedParams.hTemplateFile = IntPtr.Zero;
//if ((access & NativeFileAccess.Read) != 0)
//{
// // Sets GENERIC_READ
// newAccess |= 0x00120089;
//}
//if ((access & NativeFileAccess.Write) != 0)
//{
// newAccess |= 0x00120116;
//}
//if ((access & NativeFileAccess.Execute) != 0)
//{
// newAccess |= 0x001200a0;
//}
//handle = NativeFile.Create(fileName, (NativeFileAccess)newAccess, share, fileMode, new IntPtr(&extendedParams));
handle = NativeFile.Create(fileName, access, share, fileMode, IntPtr.Zero);
#else
handle = NativeFile.Create(fileName, access, share, IntPtr.Zero, fileMode, NativeFileOptions.None, IntPtr.Zero);
#endif
if (handle == new IntPtr(-1))
{
var lastWin32Error = MarshalGetLastWin32Error();
if (lastWin32Error == 2)
{
throw new FileNotFoundException("Unable to find file", fileName);
}
var lastError = Result.GetResultFromWin32Error(lastWin32Error);
throw new IOException(string.Format(CultureInfo.InvariantCulture, "Unable to open file {0}", fileName), lastError.Code);
}
canRead = 0 != (access & NativeFileAccess.Read);
canWrite = 0 != (access & NativeFileAccess.Write);
// TODO how setup correctly canSeek flags?
// Kernel32.GetFileType(SafeFileHandle handle); is not available on W8CORE
canSeek = true;
}
public IntPtr Handle
{
get { return handle; }
}
private static int MarshalGetLastWin32Error()
{
return Marshal.GetLastWin32Error();
}
/// <inheritdoc/>
public override void Flush()
{
if (!NativeFile.FlushFileBuffers(handle))
throw new IOException("Unable to flush stream", MarshalGetLastWin32Error());
}
/// <inheritdoc/>
public override long Seek(long offset, SeekOrigin origin)
{
long newPosition;
if (!NativeFile.SetFilePointerEx(handle, offset, out newPosition, origin))
throw new IOException("Unable to seek to this position", MarshalGetLastWin32Error());
position = newPosition;
return position;
}
/// <inheritdoc/>
public override void SetLength(long value)
{
long newPosition;
if (!NativeFile.SetFilePointerEx(handle, value, out newPosition, SeekOrigin.Begin))
throw new IOException("Unable to seek to this position", MarshalGetLastWin32Error());
if (!NativeFile.SetEndOfFile(handle))
throw new IOException("Unable to set the new length", MarshalGetLastWin32Error());
if (position < value)
{
Seek(position, SeekOrigin.Begin);
}
else
{
Seek(0, SeekOrigin.End);
}
}
/// <inheritdoc/>
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
unsafe
{
fixed (void* pbuffer = buffer)
return Read((IntPtr) pbuffer, offset, count);
}
}
/// <summary>
/// Reads a block of bytes from the stream and writes the data in a given buffer.
/// </summary>
/// <param name="buffer">When this method returns, contains the specified buffer with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. </param>
/// <param name="offset">The byte offset in array at which the read bytes will be placed. </param>
/// <param name="count">The maximum number of bytes to read. </param>
/// <exception cref="ArgumentNullException">array is null. </exception>
/// <returns>The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached.</returns>
public int Read(IntPtr buffer, int offset, int count)
{
if (buffer == IntPtr.Zero)
throw new ArgumentNullException("buffer");
int numberOfBytesRead;
unsafe
{
void* pbuffer = (byte*) buffer + offset;
{
if (!NativeFile.ReadFile(handle, (IntPtr)pbuffer, count, out numberOfBytesRead, IntPtr.Zero))
throw new IOException("Unable to read from file", MarshalGetLastWin32Error());
}
position += numberOfBytesRead;
}
return numberOfBytesRead;
}
/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
unsafe
{
fixed (void* pbuffer = buffer)
Write((IntPtr)pbuffer, offset, count);
}
}
/// <summary>
/// Writes a block of bytes to this stream using data from a buffer.
/// </summary>
/// <param name="buffer">The buffer containing data to write to the stream.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream. </param>
/// <param name="count">The number of bytes to be written to the current stream. </param>
public void Write(IntPtr buffer, int offset, int count)
{
if (buffer == IntPtr.Zero)
throw new ArgumentNullException("buffer");
int numberOfBytesWritten;
unsafe
{
void* pbuffer = (byte*) buffer + offset;
{
if (!NativeFile.WriteFile(handle, (IntPtr)pbuffer, count, out numberOfBytesWritten, IntPtr.Zero))
throw new IOException("Unable to write to file", MarshalGetLastWin32Error());
}
position += numberOfBytesWritten;
}
}
/// <inheritdoc/>
public override bool CanRead
{
get
{
return canRead;
}
}
/// <inheritdoc/>
public override bool CanSeek
{
get
{
return canSeek;
}
}
/// <inheritdoc/>
public override bool CanWrite
{
get
{
return canWrite;
}
}
/// <inheritdoc/>
public override long Length
{
get
{
long length;
if (!NativeFile.GetFileSizeEx(handle, out length))
throw new IOException("Unable to get file length", MarshalGetLastWin32Error());
return length;
}
}
/// <inheritdoc/>
public override long Position
{
get
{
return position;
}
set
{
Seek(value, SeekOrigin.Begin);
position = value;
}
}
protected override void Dispose(bool disposing)
{
Utilities.CloseHandle(handle);
handle = IntPtr.Zero;
base.Dispose(disposing);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using IBatisNet.DataMapper.Test.Domain;
using NUnit.Framework;
using IBatisNet.DataMapper;
using IBatisNet.Common;
using CategoryAttribute = NUnit.Framework.CategoryAttribute;
namespace IBatisNet.DataMapper.Test.NUnit.SqlMapTests.Perf
{
[TestFixture]
[Category("Performance")]
public class PerformanceTest : BaseTest
{
#region SetUp & TearDown
/// <summary>
/// SetUp
/// </summary>
[SetUp]
public void Init()
{
InitScript( sqlMap.DataSource, ScriptDirectory + "simple-init.sql" );
}
/// <summary>
/// TearDown
/// </summary>
[TearDown]
public void Dispose()
{ /* ... */ }
#endregion
#region DataMapper
[Test]
public void IbatisOnly()
{
for (int n = 2; n < 4000; n *= 2)
{
Simple[] simples = new Simple[n];
object[] ids = new object[n];
for (int i = 0; i < n; i++)
{
simples[i] = new Simple();
simples[i].Init();
simples[i].Count = i;
simples[i].Id = i;
}
//Now do timings
Timer timer = new Timer();
GC.Collect();
GC.WaitForPendingFinalizers();
sqlMap.OpenConnection();
timer.Start();
Ibatis(simples, n, "h1");
timer.Stop();
double ibatis = 1000000 * (timer.Duration / (double)n);
sqlMap.CloseConnection();
sqlMap.OpenConnection();
timer.Start();
Ibatis(simples, n, "h2");
timer.Stop();
ibatis += 1000000 * (timer.Duration / (double)n);
sqlMap.CloseConnection();
sqlMap.OpenConnection();
timer.Start();
Ibatis(simples, n, "h2");
timer.Stop();
ibatis += 1000000 * (timer.Duration / (double)n);
sqlMap.CloseConnection();
System.Console.WriteLine("Objects: " + n + " - iBATIS DataMapper: " + ibatis.ToString("F3"));
}
System.GC.Collect();
}
private void Ibatis(Simple[] simples, int N, string runname)
{
sqlMap.BeginTransaction(false);
for (int i = 0; i < N; i++)
{
sqlMap.Insert("InsertSimple", simples[i]);
}
for (int i = 0; i < N; i++)
{
simples[i].Name = "NH - " + i + N + runname + " - " + System.DateTime.Now.Ticks;
sqlMap.Update("UpdateSimple", simples[i]);
}
for (int i = 0; i < N; i++)
{
sqlMap.Delete("DeleteSimple", simples[i].Id);
}
sqlMap.CommitTransaction(false);
}
#endregion
#region ADO.NET
[Test]
public void AdoNetOnly()
{
for (int n = 2; n < 4000; n *= 2)
{
Simple[] simples = new Simple[n];
for (int i = 0; i < n; i++)
{
simples[i] = new Simple();
simples[i].Init();
simples[i].Count = i;
simples[i].Id = i;
}
//Now do timings
Timer timer = new Timer();
IDbConnection _connection = sqlMap.DataSource.DbProvider.CreateConnection();
_connection.ConnectionString = sqlMap.DataSource.ConnectionString;
_connection.Open();
timer.Start();
DirectAdoNet(_connection, simples, n, "j1");
timer.Stop();
double adonet = 1000000 * (timer.Duration / (double)n);
_connection.Close();
_connection.Open();
timer.Start();
DirectAdoNet(_connection, simples, n, "j2");
timer.Stop();
adonet += 1000000 * (timer.Duration / (double)n);
_connection.Close();
_connection.Open();
timer.Start();
DirectAdoNet(_connection, simples, n, "j2");
timer.Stop();
adonet += 1000000 * (timer.Duration / (double)n);
_connection.Close();
System.Console.Out.WriteLine("Objects: " + n + " Direct ADO.NET: " + adonet.ToString("F3"));
}
System.GC.Collect();
}
private void DirectAdoNet(IDbConnection c, Simple[] simples, int N, string runname)
{
IDbCommand insert = InsertCommand();
IDbCommand delete = DeleteCommand();
IDbCommand select = SelectCommand();
IDbCommand update = UpdateCommand();
IDbTransaction t = c.BeginTransaction();
insert.Connection = c;
delete.Connection = c;
select.Connection = c;
update.Connection = c;
insert.Transaction = t;
delete.Transaction = t;
select.Transaction = t;
update.Transaction = t;
insert.Prepare();
delete.Prepare();
select.Prepare();
update.Prepare();
for (int i = 0; i < N; i++)
{
((IDbDataParameter)insert.Parameters[0]).Value = simples[i].Name;
((IDbDataParameter)insert.Parameters[1]).Value = simples[i].Address;
((IDbDataParameter)insert.Parameters[2]).Value = simples[i].Count;
((IDbDataParameter)insert.Parameters[3]).Value = simples[i].Date;
((IDbDataParameter)insert.Parameters[4]).Value = simples[i].Pay;
((IDbDataParameter)insert.Parameters[5]).Value = simples[i].Id;
insert.ExecuteNonQuery();
}
for (int i = 0; i < N; i++)
{
((IDbDataParameter)update.Parameters[0]).Value = "DR - " + i + N + runname + " - " + System.DateTime.Now.Ticks;
((IDbDataParameter)update.Parameters[1]).Value = simples[i].Address;
((IDbDataParameter)update.Parameters[2]).Value = simples[i].Count;
((IDbDataParameter)update.Parameters[3]).Value = simples[i].Date;
((IDbDataParameter)update.Parameters[4]).Value = simples[i].Pay;
((IDbDataParameter)update.Parameters[5]).Value = simples[i].Id;
update.ExecuteNonQuery();
}
for (int i = 0; i < N; i++)
{
((IDbDataParameter)delete.Parameters[0]).Value = simples[i].Id;
delete.ExecuteNonQuery();
}
t.Commit();
}
private IDbCommand DeleteCommand()
{
string sql = "delete from Simples where id = ";
sql += sqlMap.DataSource.DbProvider.FormatNameForSql("id");
IDbCommand cmd = sqlMap.DataSource.DbProvider.CreateCommand();
cmd.CommandText = sql;
IDbDataParameter prm = cmd.CreateParameter();
prm.ParameterName = sqlMap.DataSource.DbProvider.FormatNameForParameter("id");
prm.DbType = DbType.Int32;
cmd.Parameters.Add(prm);
return cmd;
}
private IDbCommand InsertCommand()
{
string sql = "insert into Simples ( name, address, count, date, pay, id ) values (";
for (int i = 0; i < 6; i++)
{
if (i > 0) sql += ", ";
sql += sqlMap.DataSource.DbProvider.FormatNameForSql("param" + i.ToString());
}
sql += ")";
IDbCommand cmd = sqlMap.DataSource.DbProvider.CreateCommand();
cmd.CommandText = sql;
AppendInsertUpdateParams(cmd);
return cmd;
}
private IDbCommand SelectCommand()
{
string sql = "SELECT s.id, s.name, s.address, s.count, s.date, s.pay FROM Simples s";
IDbCommand cmd = sqlMap.DataSource.DbProvider.CreateCommand();
cmd.CommandText = sql;
return cmd;
}
private IDbCommand UpdateCommand()
{
string sql = "update Simples set";
sql += (" name = " + sqlMap.DataSource.DbProvider.FormatNameForSql("param0"));
sql += (", address = " + sqlMap.DataSource.DbProvider.FormatNameForSql("param1"));
sql += (", count = " + sqlMap.DataSource.DbProvider.FormatNameForSql("param2"));
sql += (", date = " + sqlMap.DataSource.DbProvider.FormatNameForSql("param3"));
sql += (", pay = " + sqlMap.DataSource.DbProvider.FormatNameForSql("param4"));
sql += " where id = " + sqlMap.DataSource.DbProvider.FormatNameForSql("param5");
IDbCommand cmd = sqlMap.DataSource.DbProvider.CreateCommand();
cmd.CommandText = sql;
AppendInsertUpdateParams(cmd);
return cmd;
}
private void AppendInsertUpdateParams(IDbCommand cmd)
{
IDbDataParameter[] prm = new IDbDataParameter[6];
for (int j = 0; j < 6; j++)
{
prm[j] = cmd.CreateParameter();
prm[j].ParameterName = sqlMap.DataSource.DbProvider.FormatNameForParameter("param" + j.ToString());
cmd.Parameters.Add(prm[j]);
}
int i = 0;
prm[i].DbType = DbType.String;
prm[i].Size = 255;
i++;
prm[i].DbType = DbType.String;
prm[i].Size = 200;
i++;
prm[i].DbType = DbType.Int32;
i++;
prm[i].DbType = DbType.DateTime;
i++;
prm[i].DbType = DbType.Decimal;
prm[i].Scale = 2;
prm[i].Precision = 5;
i++;
prm[i].DbType = DbType.Int32;
i++;
}
#endregion
[Test]
public void Many()
{
double ibatis = 0;
double adonet = 0;
for (int n = 0; n < 5; n++)
{
Simple[] simples = new Simple[n];
for (int i = 0; i < n; i++)
{
simples[i] = new Simple();
simples[i].Init();
simples[i].Count = i;
simples[i].Id = i;
}
sqlMap.OpenConnection();
Ibatis(simples, n, "h0");
sqlMap.CloseConnection();
IDbConnection _connection = sqlMap.DataSource.DbProvider.CreateConnection();
_connection.ConnectionString = sqlMap.DataSource.ConnectionString;
_connection.Open();
DirectAdoNet(_connection, simples, n, "j0");
_connection.Close();
sqlMap.OpenConnection();
Ibatis(simples, n, "h0");
sqlMap.CloseConnection();
_connection.Open();
DirectAdoNet(_connection, simples, n, "j0");
_connection.Close();
// now do timings
int loops = 30;
Timer timer = new Timer();
for (int runIndex = 1; runIndex < 4; runIndex++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
timer.Start();
for (int i = 0; i < loops; i++)
{
sqlMap.OpenConnection();
Ibatis(simples, n, "h" + runIndex.ToString());
sqlMap.CloseConnection();
}
timer.Stop();
ibatis += 1000000 * (timer.Duration / (double)loops);
GC.Collect();
GC.WaitForPendingFinalizers();
timer.Start();
for (int i = 0; i < loops; i++)
{
_connection.Open();
DirectAdoNet(_connection, simples, n, "j" + runIndex.ToString());
_connection.Close();
}
timer.Stop();
adonet += 1000000 * (timer.Duration / (double)loops);
}
}
System.Console.Out.WriteLine("iBatis DataMapper : " + ibatis.ToString("F3") + " / Direct ADO.NET: " + adonet.ToString("F3") + " Ratio: " + ((ibatis / adonet)).ToString("F3"));
System.GC.Collect();
}
[Test]
public void Simultaneous()
{
double ibatis = 0;
double adonet = 0;
IDbConnection _connection = sqlMap.DataSource.DbProvider.CreateConnection();
_connection.ConnectionString = sqlMap.DataSource.ConnectionString;
for (int n = 2; n < 4000; n *= 2)
{
Simple[] simples = new Simple[n];
for (int i = 0; i < n; i++)
{
simples[i] = new Simple();
simples[i].Init();
simples[i].Count = i;
simples[i].Id = i;
}
sqlMap.OpenConnection();
Ibatis(simples, n, "h0");
sqlMap.CloseConnection();
_connection.Open();
DirectAdoNet(_connection, simples, n, "j0");
_connection.Close();
sqlMap.OpenConnection();
Ibatis(simples, n, "h0");
sqlMap.CloseConnection();
_connection.Open();
DirectAdoNet(_connection, simples, n, "j0");
_connection.Close();
//Now do timings
Timer timer = new Timer();
GC.Collect();
GC.WaitForPendingFinalizers();
sqlMap.OpenConnection();
timer.Start();
Ibatis(simples, n, "h1");
timer.Stop();
ibatis = 1000000 * (timer.Duration / (double)n);
sqlMap.CloseConnection();
_connection.Open();
timer.Start();
DirectAdoNet(_connection, simples, n, "j1");
timer.Stop();
adonet = 1000000 * (timer.Duration / (double)n);
_connection.Close();
sqlMap.OpenConnection();
timer.Start();
Ibatis(simples, n, "h2");
timer.Stop();
ibatis += 1000000 * (timer.Duration / (double)n);
sqlMap.CloseConnection();
_connection.Open();
timer.Start();
DirectAdoNet(_connection, simples, n, "j2");
timer.Stop();
adonet += 1000000 * (timer.Duration / (double)n);
_connection.Close();
sqlMap.OpenConnection();
timer.Start();
Ibatis(simples, n, "h2");
timer.Stop();
ibatis += 1000000 * (timer.Duration / (double)n);
sqlMap.CloseConnection();
_connection.Open();
timer.Start();
DirectAdoNet(_connection, simples, n, "j2");
timer.Stop();
adonet += 1000000 * (timer.Duration / (double)n);
_connection.Close();
System.Console.Out.WriteLine("Objects " + n + " iBATIS DataMapper : " + ibatis.ToString("F3") + " / Direct ADO.NET: " + adonet.ToString("F3") + " Ratio: " + ((ibatis / adonet)).ToString("F3"));
}
System.GC.Collect();
}
internal class Timer
{
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
private long startTime, stopTime;
private long freq;
public Timer()
{
startTime = 0;
stopTime = 0;
if (QueryPerformanceFrequency(out freq) == false)
{
throw new Win32Exception();
}
}
public void Start()
{
Thread.Sleep(0);
QueryPerformanceCounter(out startTime);
}
public void Stop()
{
QueryPerformanceCounter(out stopTime);
}
public double Duration
{
get { return (double) (stopTime - startTime)/(double) freq; }
}
}
}
}
| |
// 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.
/*============================================================
**
**
**
** Provides a way for an app to not start an operation unless
** there's a reasonable chance there's enough memory
** available for the operation to succeed.
**
**
===========================================================*/
using System;
using System.IO;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
/*
This class allows an application to fail before starting certain
activities. The idea is to fail early instead of failing in the middle
of some long-running operation to increase the survivability of the
application and ensure you don't have to write tricky code to handle an
OOM anywhere in your app's code (which implies state corruption, meaning you
should unload the appdomain, if you have a transacted environment to ensure
rollback of individual transactions). This is an incomplete tool to attempt
hoisting all your OOM failures from anywhere in your worker methods to one
particular point where it is easier to handle an OOM failure, and you can
optionally choose to not start a workitem if it will likely fail. This does
not help the performance of your code directly (other than helping to avoid
AD unloads). The point is to avoid starting work if it is likely to fail.
The Enterprise Services team has used these memory gates effectively in the
unmanaged world for a decade.
In Whidbey, we will simply check to see if there is enough memory available
in the OS's page file & attempt to ensure there might be enough space free
within the process's address space (checking for address space fragmentation
as well). We will not commit or reserve any memory. To avoid race conditions with
other threads using MemoryFailPoints, we'll also keep track of a
process-wide amount of memory "reserved" via all currently-active
MemoryFailPoints. This has two problems:
1) This can account for memory twice. If a thread creates a
MemoryFailPoint for 100 MB then allocates 99 MB, we'll see 99 MB
less free memory and 100 MB less reserved memory. Yet, subtracting
off the 100 MB is necessary because the thread may not have started
allocating memory yet. Disposing of this class immediately after
front-loaded allocations have completed is a great idea.
2) This is still vulnerable to race conditions with other threads that don't use
MemoryFailPoints.
So this class is far from perfect. But it may be good enough to
meaningfully reduce the frequency of OutOfMemoryExceptions in managed apps.
In Orcas or later, we might allocate some memory from the OS and add it
to a allocation context for this thread. Obviously, at that point we need
some way of conveying when we release this block of memory. So, we
implemented IDisposable on this type in Whidbey and expect all users to call
this from within a using block to provide lexical scope for their memory
usage. The call to Dispose (implicit with the using block) will give us an
opportunity to release this memory, perhaps. We anticipate this will give
us the possibility of a more effective design in a future version.
In Orcas, we may also need to differentiate between allocations that would
go into the normal managed heap vs. the large object heap, or we should
consider checking for enough free space in both locations (with any
appropriate adjustments to ensure the memory is contiguous).
*/
namespace System.Runtime
{
public sealed class MemoryFailPoint : CriticalFinalizerObject, IDisposable
{
// Find the top section of user mode memory. Avoid the last 64K.
// Windows reserves that block for the kernel, apparently, and doesn't
// let us ask about that memory. But since we ask for memory in 1 MB
// chunks, we don't have to special case this. Also, we need to
// deal with 32 bit machines in 3 GB mode.
// Using Win32's GetSystemInfo should handle all this for us.
private static readonly ulong TopOfMemory;
// Walking the address space is somewhat expensive, taking around half
// a millisecond. Doing that per transaction limits us to a max of
// ~2000 transactions/second. Instead, let's do this address space
// walk once every 10 seconds, or when we will likely fail. This
// amortization scheme can reduce the cost of a memory gate by about
// a factor of 100.
private static long hiddenLastKnownFreeAddressSpace = 0;
private static long hiddenLastTimeCheckingAddressSpace = 0;
private const int CheckThreshold = 10 * 1000; // 10 seconds
private static long LastKnownFreeAddressSpace
{
get { return Volatile.Read(ref hiddenLastKnownFreeAddressSpace); }
set { Volatile.Write(ref hiddenLastKnownFreeAddressSpace, value); }
}
private static long AddToLastKnownFreeAddressSpace(long addend)
{
return Interlocked.Add(ref hiddenLastKnownFreeAddressSpace, addend);
}
private static long LastTimeCheckingAddressSpace
{
get { return Volatile.Read(ref hiddenLastTimeCheckingAddressSpace); }
set { Volatile.Write(ref hiddenLastTimeCheckingAddressSpace, value); }
}
// When allocating memory segment by segment, we've hit some cases
// where there are only 22 MB of memory available on the machine,
// we need 1 16 MB segment, and the OS does not succeed in giving us
// that memory. Reasons for this could include:
// 1) The GC does allocate memory when doing a collection.
// 2) Another process on the machine could grab that memory.
// 3) Some other part of the runtime might grab this memory.
// If we build in a little padding, we can help protect
// ourselves against some of these cases, and we want to err on the
// conservative side with this class.
private const int LowMemoryFudgeFactor = 16 << 20;
// Round requested size to a 16MB multiple to have a better granularity
// when checking for available memory.
private const int MemoryCheckGranularity = 16;
// Note: This may become dynamically tunable in the future.
// Also note that we can have different segment sizes for the normal vs.
// large object heap. We currently use the max of the two.
private static readonly ulong GCSegmentSize;
// For multi-threaded workers, we want to ensure that if two workers
// use a MemoryFailPoint at the same time, and they both succeed, that
// they don't trample over each other's memory. Keep a process-wide
// count of "reserved" memory, and decrement this in Dispose and
// in the critical finalizer. See
// SharedStatics.MemoryFailPointReservedMemory
private ulong _reservedMemory; // The size of this request (from user)
private bool _mustSubtractReservation; // Did we add data to SharedStatics?
static MemoryFailPoint()
{
GetMemorySettings(out GCSegmentSize, out TopOfMemory);
}
// We can remove this link demand in a future version - we will
// have scenarios for this in partial trust in the future, but
// we're doing this just to restrict this in case the code below
// is somehow incorrect.
public MemoryFailPoint(int sizeInMegabytes)
{
if (sizeInMegabytes <= 0)
throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
#if !FEATURE_PAL // Remove this when CheckForAvailableMemory is able to provide legitimate estimates
ulong size = ((ulong)sizeInMegabytes) << 20;
_reservedMemory = size;
// Check to see that we both have enough memory on the system
// and that we have enough room within the user section of the
// process's address space. Also, we need to use the GC segment
// size, not the amount of memory the user wants to allocate.
// Consider correcting this to reflect free memory within the GC
// heap, and to check both the normal & large object heaps.
ulong segmentSize = (ulong)(Math.Ceiling((double)size / GCSegmentSize) * GCSegmentSize);
if (segmentSize >= TopOfMemory)
throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig);
ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity);
//re-convert into bytes
requestedSizeRounded <<= 20;
ulong availPageFile = 0; // available VM (physical + page file)
ulong totalAddressSpaceFree = 0; // non-contiguous free address space
// Check for available memory, with 2 attempts at getting more
// memory.
// Stage 0: If we don't have enough, trigger a GC.
// Stage 1: If we don't have enough, try growing the swap file.
// Stage 2: Update memory state, then fail or leave loop.
//
// (In the future, we could consider adding another stage after
// Stage 0 to run finalizers. However, before doing that make sure
// that we could abort this constructor when we call
// GC.WaitForPendingFinalizers, noting that this method uses a CER
// so it can't be aborted, and we have a critical finalizer. It
// would probably work, but do some thinking first.)
for (int stage = 0; stage < 3; stage++)
{
CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree);
// If we have enough room, then skip some stages.
// Note that multiple threads can still lead to a race condition for our free chunk
// of address space, which can't be easily solved.
ulong reserved = SharedStatics.MemoryFailPointReservedMemory;
ulong segPlusReserved = segmentSize + reserved;
bool overflow = segPlusReserved < segmentSize || segPlusReserved < reserved;
bool needPageFile = availPageFile < (requestedSizeRounded + reserved + LowMemoryFudgeFactor) || overflow;
bool needAddressSpace = totalAddressSpaceFree < segPlusReserved || overflow;
// Ensure our cached amount of free address space is not stale.
long now = Environment.TickCount; // Handle wraparound.
if ((now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace) ||
LastKnownFreeAddressSpace < (long)segmentSize)
{
CheckForFreeAddressSpace(segmentSize, false);
}
bool needContiguousVASpace = (ulong)LastKnownFreeAddressSpace < segmentSize;
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checking for {0} MB, for allocation size of {1} MB, stage {9}. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved via process's MemoryFailPoints: {8} MB",
segmentSize >> 20, sizeInMegabytes, needPageFile,
needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved, stage);
if (!needPageFile && !needAddressSpace && !needContiguousVASpace)
break;
switch (stage)
{
case 0:
// The GC will release empty segments to the OS. This will
// relieve us from having to guess whether there's
// enough memory in either GC heap, and whether
// internal fragmentation will prevent those
// allocations from succeeding.
GC.Collect();
continue;
case 1:
// Do this step if and only if the page file is too small.
if (!needPageFile)
continue;
// Attempt to grow the OS's page file. Note that we ignore
// any allocation routines from the host intentionally.
RuntimeHelpers.PrepareConstrainedRegions();
// This shouldn't overflow due to the if clauses above.
UIntPtr numBytes = new UIntPtr(segmentSize);
unsafe
{
void* pMemory = Win32Native.VirtualAlloc(null, numBytes, Win32Native.MEM_COMMIT, Win32Native.PAGE_READWRITE);
if (pMemory != null)
{
bool r = Win32Native.VirtualFree(pMemory, UIntPtr.Zero, Win32Native.MEM_RELEASE);
if (!r)
__Error.WinIOError();
}
}
continue;
case 2:
// The call to CheckForAvailableMemory above updated our
// state.
if (needPageFile || needAddressSpace)
{
InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint);
#if _DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
if (needContiguousVASpace)
{
InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
#if _DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
break;
default:
Debug.Assert(false, "Fell through switch statement!");
break;
}
}
// Success - we have enough room the last time we checked.
// Now update our shared state in a somewhat atomic fashion
// and handle a simple race condition with other MemoryFailPoint instances.
AddToLastKnownFreeAddressSpace(-((long)size));
if (LastKnownFreeAddressSpace < 0)
CheckForFreeAddressSpace(segmentSize, true);
RuntimeHelpers.PrepareConstrainedRegions();
SharedStatics.AddMemoryFailPointReservation((long)size);
_mustSubtractReservation = true;
#endif
}
private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree)
{
bool r;
Win32Native.MEMORYSTATUSEX memory = new Win32Native.MEMORYSTATUSEX();
r = Win32Native.GlobalMemoryStatusEx(ref memory);
if (!r)
__Error.WinIOError();
availPageFile = memory.availPageFile;
totalAddressSpaceFree = memory.availVirtual;
//Console.WriteLine("Memory gate: Mem load: {0}% Available memory (physical + page file): {1} MB Total free address space: {2} MB GC Heap: {3} MB", memory.memoryLoad, memory.availPageFile >> 20, memory.availVirtual >> 20, GC.GetTotalMemory(true) >> 20);
}
// Based on the shouldThrow parameter, this will throw an exception, or
// returns whether there is enough space. In all cases, we update
// our last known free address space, hopefully avoiding needing to
// probe again.
private static unsafe bool CheckForFreeAddressSpace(ulong size, bool shouldThrow)
{
// Start walking the address space at 0. VirtualAlloc may wrap
// around the address space. We don't need to find the exact
// pages that VirtualAlloc would return - we just need to
// know whether VirtualAlloc could succeed.
ulong freeSpaceAfterGCHeap = MemFreeAfterAddress(null, size);
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checked for free VA space. Found enough? {0} Asked for: {1} Found: {2}", (freeSpaceAfterGCHeap >= size), size, freeSpaceAfterGCHeap);
// We may set these without taking a lock - I don't believe
// this will hurt, as long as we never increment this number in
// the Dispose method. If we do an extra bit of checking every
// once in a while, but we avoid taking a lock, we may win.
LastKnownFreeAddressSpace = (long)freeSpaceAfterGCHeap;
LastTimeCheckingAddressSpace = Environment.TickCount;
if (freeSpaceAfterGCHeap < size && shouldThrow)
throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
return freeSpaceAfterGCHeap >= size;
}
// Returns the amount of consecutive free memory available in a block
// of pages. If we didn't have enough address space, we still return
// a positive value < size, to help potentially avoid the overhead of
// this check if we use a MemoryFailPoint with a smaller size next.
private static unsafe ulong MemFreeAfterAddress(void* address, ulong size)
{
if (size >= TopOfMemory)
return 0;
ulong largestFreeRegion = 0;
Win32Native.MEMORY_BASIC_INFORMATION memInfo = new Win32Native.MEMORY_BASIC_INFORMATION();
UIntPtr sizeOfMemInfo = (UIntPtr)Marshal.SizeOf(memInfo);
while (((ulong)address) + size < TopOfMemory)
{
UIntPtr r = Win32Native.VirtualQuery(address, ref memInfo, sizeOfMemInfo);
if (r == UIntPtr.Zero)
__Error.WinIOError();
ulong regionSize = memInfo.RegionSize.ToUInt64();
if (memInfo.State == Win32Native.MEM_FREE)
{
if (regionSize >= size)
return regionSize;
else
largestFreeRegion = Math.Max(largestFreeRegion, regionSize);
}
address = (void*)((ulong)address + regionSize);
}
return largestFreeRegion;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void GetMemorySettings(out ulong maxGCSegmentSize, out ulong topOfMemory);
~MemoryFailPoint()
{
Dispose(false);
}
// Applications must call Dispose, which conceptually "releases" the
// memory that was "reserved" by the MemoryFailPoint. This affects a
// global count of reserved memory in this version (helping to throttle
// future MemoryFailPoints) in this version. We may in the
// future create an allocation context and release it in the Dispose
// method. While the finalizer will eventually free this block of
// memory, apps will help their performance greatly by calling Dispose.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// This is just bookkeeping to ensure multiple threads can really
// get enough memory, and this does not actually reserve memory
// within the GC heap.
if (_mustSubtractReservation)
{
RuntimeHelpers.PrepareConstrainedRegions();
SharedStatics.AddMemoryFailPointReservation(-((long)_reservedMemory));
_mustSubtractReservation = false;
}
/*
// Prototype performance
// Let's pretend that we returned at least some free memory to
// the GC heap. We don't know this is true - the objects could
// have a longer lifetime, and the memory could be elsewhere in the
// GC heap. Additionally, we subtracted off the segment size, not
// this size. That's ok - we don't mind if this slowly degrades
// and requires us to refresh the value a little bit sooner.
// But releasing the memory here should help us avoid probing for
// free address space excessively with large workItem sizes.
Interlocked.Add(ref LastKnownFreeAddressSpace, _reservedMemory);
*/
}
#if _DEBUG
[Serializable]
internal sealed class MemoryFailPointState
{
private ulong _segmentSize;
private int _allocationSizeInMB;
private bool _needPageFile;
private bool _needAddressSpace;
private bool _needContiguousVASpace;
private ulong _availPageFile;
private ulong _totalFreeAddressSpace;
private long _lastKnownFreeAddressSpace;
private ulong _reservedMem;
private String _stackTrace; // Where did we fail, for additional debugging.
internal MemoryFailPointState(int allocationSizeInMB, ulong segmentSize, bool needPageFile, bool needAddressSpace, bool needContiguousVASpace, ulong availPageFile, ulong totalFreeAddressSpace, long lastKnownFreeAddressSpace, ulong reservedMem)
{
_allocationSizeInMB = allocationSizeInMB;
_segmentSize = segmentSize;
_needPageFile = needPageFile;
_needAddressSpace = needAddressSpace;
_needContiguousVASpace = needContiguousVASpace;
_availPageFile = availPageFile;
_totalFreeAddressSpace = totalFreeAddressSpace;
_lastKnownFreeAddressSpace = lastKnownFreeAddressSpace;
_reservedMem = reservedMem;
try
{
_stackTrace = Environment.StackTrace;
}
catch (System.Security.SecurityException)
{
_stackTrace = "no permission";
}
catch (OutOfMemoryException)
{
_stackTrace = "out of memory";
}
}
public override String ToString()
{
return String.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB",
_segmentSize >> 20, _allocationSizeInMB, _needPageFile,
_needAddressSpace, _needContiguousVASpace,
_availPageFile >> 20, _totalFreeAddressSpace >> 20,
_lastKnownFreeAddressSpace >> 20, _reservedMem);
}
}
#endif
}
}
| |
using System;
using System.Threading;
namespace Skewworks.NETMF.Controls
{
/// <summary>
/// Base class for creating controls
/// </summary>
[Serializable]
public class Control : MarshalByRefObject, IControl
{
#region Variables
// Name & Tag
private string _name;
private object _tag;
// Size & Location
private int _x;
private int _y;
private int _offsetX;
private int _offsetY;
private int _w;
private int _h;
// Owner
private IContainer _parent;
// States
private bool _enabled = true;
private bool _visible = true;
private bool _suspended;
// Touch
private bool _mDown; // Touching when true
private point _ptTapHold; // Location where touch down occurred
private Thread _thHold; // Tap & Hold thread
private long _lStop; // Stop waiting for hold after this tick
private TapState _eTapHold; // Current tap state
private long _lastTap; // Tick count of last time occurrence
// Dispose
private bool _disposing;
#endregion
/// <summary>
/// Initializes the control
/// </summary>
protected Control()
{ }
/// <summary>
/// Initializes the control
/// </summary>
/// <param name="name">Name of the control</param>
protected Control(string name)
{
_name = name;
}
/// <summary>
/// Initializes the control
/// </summary>
/// <param name="name">Name of the control</param>
/// <param name="x">X position relative to it's parent</param>
/// <param name="y">Y position relative to it's parent</param>
protected Control(string name, int x, int y) :
this(name)
{
_x = x;
_y = y;
}
/// <summary>
/// Initializes the control
/// </summary>
/// <param name="name">Name of the control</param>
/// <param name="x">X position relative to it's parent</param>
/// <param name="y">Y position relative to it's parent</param>
/// <param name="width">Width of the control in pixel</param>
/// <param name="height">Height of the control in pixel</param>
protected Control(string name, int x, int y, int width, int height) :
this(name, x, y)
{
_w = width;
_h = height;
}
#region Events
/// <summary>
/// Adds or removes callback methods for ButtonPressed events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a button press occurs
/// </remarks>
public event OnButtonPressed ButtonPressed;
/// <summary>
/// Fires the ButtonPressed event
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="buttonId">Integer ID corresponding to the affected button</param>
protected virtual void OnButtonPressed(object sender, int buttonId)
{
if (ButtonPressed != null)
{
ButtonPressed(sender, buttonId);
}
}
/// <summary>
/// Adds or removes callback methods for ButtonReleased events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a button release occurs
/// </remarks>
public event OnButtonReleased ButtonReleased;
/// <summary>
/// Fires the ButtonReleased event
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="buttonId">Integer ID corresponding to the affected button</param>
protected virtual void OnButtonReleased(object sender, int buttonId)
{
if (ButtonReleased != null)
{
ButtonReleased(sender, buttonId);
}
}
/// <summary>
/// Adds or removes callback methods for DoubleTap events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a Double Tap occurs
/// </remarks>
public event OnDoubleTap DoubleTap;
/// <summary>
/// Fires the DoubleTap event
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen event is occurring</param>
protected virtual void OnDoubleTap(object sender, point point)
{
if (DoubleTap != null)
{
DoubleTap(sender, point);
}
}
/// <summary>
/// Adds or removes callback methods for GotFocus events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a control gets focus
/// </remarks>
public event OnGotFocus GotFocus;
/// <summary>
/// Fires the GotFocus event
/// </summary>
/// <param name="sender">Object sending the event</param>
protected virtual void OnGotFocus(object sender)
{
if (GotFocus != null)
{
GotFocus(sender);
}
}
/// <summary>
/// Adds or removes callback methods for KeyboardAltKey events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a keyboard alt key press/release occurs
/// </remarks>
public event OnKeyboardAltKey KeyboardAltKey;
/// <summary>
/// Fires the KeyboardAltKey event
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="key">Integer value of the Alt key affected</param>
/// <param name="pressed">True if the key is currently being pressed; false if released</param>
protected virtual void OnKeyboardAltKey(object sender, int key, bool pressed)
{
if (KeyboardAltKey != null)
{
KeyboardAltKey(sender, key, pressed);
}
}
/// <summary>
/// Adds or removes callback methods for KeyboardKey events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a keyboard key press/release occurs
/// </remarks>
public event OnKeyboardKey KeyboardKey;
/// <summary>
/// Fires the KeyboardKey event
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="key">Integer value of the key affected</param>
/// <param name="pressed">True if the key is currently being pressed; false if released</param>
protected virtual void OnKeyboardKey(object sender, char key, bool pressed)
{
if (KeyboardKey != null)
{
KeyboardKey(sender, key, pressed);
}
}
/// <summary>
/// Adds or removes callback methods for LostFocus events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a control loses focus
/// </remarks>
public event OnLostFocus LostFocus;
/// <summary>
/// Fires the LostFocus event
/// </summary>
/// <param name="sender">Object sending the event</param>
protected virtual void OnLostFocus(object sender)
{
if (LostFocus != null)
{
LostFocus(sender);
}
}
/// <summary>
/// Adds or removes callback methods for Tap events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a Tap occurs
/// </remarks>
public event OnTap Tap;
/// <summary>
/// Fires the Tap event
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen event is occurring</param>
public virtual void OnTap(object sender, point point)
{
if (Tap != null)
{
Tap(sender, point);
}
}
/// <summary>
/// Adds or removes callback methods for TapHold events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a Tap and Hold occurs
/// </remarks>
public event OnTapHold TapHold;
/// <summary>
/// Fires the TapHold event
/// </summary>
/// <param name="sender">>Object sending the event</param>
/// <param name="point">Point on screen event is occurring</param>
public virtual void OnTapHold(object sender, point point)
{
if (TapHold != null)
{
TapHold(sender, point);
}
}
/// <summary>
/// Adds or removes callback methods for TouchDown events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a touch down occurs
/// </remarks>
public event OnTouchDown TouchDown;
/// <summary>
/// Fires the TouchDown event
/// </summary>
/// <param name="sender">>Object sending the event</param>
/// <param name="point">Point on screen event is occurring</param>
public virtual void OnTouchDown(object sender, point point)
{
if (TouchDown != null)
{
TouchDown(sender, point);
}
}
/// <summary>
/// Adds or removes callback methods for TouchGesture events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a touch gesture occurs
/// </remarks>
public event OnTouchGesture TouchGesture;
/// <summary>
/// Fires the TouchGesture event
/// </summary>
/// <param name="sender">>Object sending the event</param>
/// <param name="type">Type of gesture being sent</param>
/// <param name="force">Force associated with gesture (0.0 to 1.0)</param>
public virtual void OnTouchGesture(object sender, TouchType type, float force)
{
if (TouchGesture != null)
{
TouchGesture(sender, type, force);
}
}
/// <summary>
/// Adds or removes callback methods for TouchMove events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a touch move occurs
/// </remarks>
public event OnTouchMove TouchMove;
/// <summary>
/// Fires the TouchMove event
/// </summary>
/// <param name="sender">>Object sending the event</param>
/// <param name="point">Point on screen event is occurring</param>
public virtual void OnTouchMove(object sender, point point)
{
if (TouchMove != null)
{
TouchMove(sender, point);
}
}
/// <summary>
/// Adds or removes callback methods for TouchUp events
/// </summary>
/// <remarks>
/// Applications can subscribe to this event to be notified when a touch release occurs
/// </remarks>
public event OnTouchUp TouchUp;
/// <summary>
/// Fires the TouchUp event
/// </summary>
/// <param name="sender">>Object sending the event</param>
/// <param name="point">Point on screen event is occurring</param>
public virtual void OnTouchUp(object sender, point point)
{
if (TouchUp != null)
{
TouchUp(sender, point);
}
}
#endregion
#region Properties
/// <summary>
/// Allows internally direct access to the Suspended flag of the control
/// </summary>
protected internal bool InternalSuspended
{
get { return _suspended; }
set { _suspended = value; }
}
/// <summary>
/// Gets the controls ability to receive focus
/// </summary>
/// <remarks>
/// Controls can only receive button and keyboard messages when focused
/// </remarks>
public virtual bool CanFocus
{
get { return true; }
}
/// <summary>
/// Gets the disposing state of the control
/// </summary>
/// <remarks>
/// Controls being disposed are not available for use
/// </remarks>
public bool Disposing
{
get { return _disposing; }
}
/// <summary>
/// Gets/Sets the enabled state of the control
/// </summary>
/// <remarks>
/// Controls must be enabled to respond to touch, keyboard, or button events
/// </remarks>
public bool Enabled
{
get { return _enabled; }
set
{
if (_enabled == value)
return;
_enabled = value;
Render(true);
}
}
/// <summary>
/// Gets if the control is currently focused
/// </summary>
/// <remarks>
/// Being focused means to be the active child of the parent.
/// </remarks>
public bool Focused
{
get
{
if (_parent == null)
{
return false;
}
return _parent.ActiveChild == this;
}
}
/// <summary>
/// Gets/Sets the height of the control in pixels
/// </summary>
public virtual int Height
{
get { return _h; }
set
{
if (_h == value)
{
return;
}
// Create Update Region
var r = new rect(Left, Top, Width, Math.Max(_h, value));
_h = value;
Invalidate(r);
/*if (_parent != null)
{
_parent.Render(r, true);
}*/
}
}
/// <summary>
/// Gets the coordinates of the last point touched
/// </summary>
/// <remarks>
/// If control is currently being touch LastTouch returns current position
/// </remarks>
public point LastTouch
{
get { return _ptTapHold; }
protected set { _ptTapHold = value; }
}
/// <summary>
/// Gets or sets the location of the control
/// </summary>
/// <remarks>
/// Location is equivalent to X and Y.
/// </remarks>
public virtual point Location
{
get { return new point(_x, _y); }
set
{
bool changed = false;
var r = new rect(Left, Top, Width, Height);
if (_x != value.X)
{
r.X = Math.Min(_x, value.X);
r.Width = Math.Abs(_x - value.X) + Width;
_x = value.X;
changed = true;
}
if (_y != value.Y)
{
//rect r = new rect(Left, System.Math.Min(_y, value), Width, System.Math.Abs(_y - value) + Height);
r.Y = Math.Min(_y, value.Y);
r.Height = Math.Abs(_y - value.Y) + Height;
_y = value.Y;
changed = true;
}
if (changed)// && _parent != null)
{
Invalidate(r);
//_parent.Render(r, true);
}
}
}
/// <summary>
/// Gets the absolute X position of the control accounting for parental offsets
/// </summary>
public int Left
{
get { return X + _offsetX; }
}
/// <summary>
/// Gets the name of the control
/// </summary>
public string Name
{
get { return _name; }
protected set { _name = value; }
}
/// <summary>
/// Gets/Sets the control's container
/// </summary>
/// <remarks>
/// Parent is automatically set when you add a control to a container
/// </remarks>
public virtual IContainer Parent
{
get { return _parent; }
set
{
if (_parent == value)
{
return;
}
if (_parent != null)
{
_parent.RemoveChild(this);
}
_parent = value;
UpdateOffsets();
}
}
/// <summary>
/// Gets the exact location of the control in pixels on the screen
/// </summary>
/// <remarks>
/// X and Y are relative to the parent container, which might have an offset as well.
/// ScreenBounds returns the absolute coordinates of the control.
/// </remarks>
public rect ScreenBounds
{
get { return new rect(Left, Top, Width, Height); }
}
/// <summary>
/// Gets/Sets the suspended state
/// </summary>
/// <remarks>
/// When Suspended is set to false the control will automatically refresh. While true the control will not render or respond to events.
/// </remarks>
public virtual bool Suspended
{
get
{
if (_parent != null && _parent.Suspended)
{
return true;
}
return _suspended;
}
set
{
if (_suspended == value)
{
return;
}
_suspended = value;
if (!_suspended)
{
Invalidate();
}
}
}
/// <summary>
/// Gets or sets a user defined tag for the control
/// </summary>
public object Tag
{
get { return _tag; }
set { _tag = value; }
}
/// <summary>
/// Gets the absolute Y position of the control accounting for parental offsets
/// </summary>
public int Top
{
get { return Y + _offsetY; }
}
/// <summary>
/// Gets the current touch state of the control
/// </summary>
/// <remarks>
/// Returns true if the control is currently being touched
/// </remarks>
public virtual bool Touching
{
get { return _mDown; }
}
/// <summary>
/// Gets/Sets the visibility of the control
/// </summary>
/// <remarks>
/// Controls that are not visible will not be rendered or respond to touch, button or keyboard events
/// </remarks>
public virtual bool Visible
{
get { return _visible; }
set
{
if (_visible == value)
{
return;
}
_visible = value;
if (_parent != null)
{
_parent.Render(new rect(Left, Top, Width, Height), true);
}
}
}
/// <summary>
/// Gets/Sets the width of the control in pixels
/// </summary>
public virtual int Width
{
get { return _w; }
set
{
if (_w == value)
{
return;
}
// Create Update Region
var r = new rect(Left, Top, Math.Max(_w, value), Height);
_w = value;
Invalidate(r);
/*if (_parent != null)
{
_parent.Render(r, true);
}*/
}
}
/// <summary>
/// Gets/Sets the X position in pixels
/// </summary>
/// <remarks>
/// X is a relative location inside the parent, Left is the exact location on the screen
/// </remarks>
public virtual int X
{
get { return _x; }
set
{
if (_x == value)
{
return;
}
// Create update region
var r = new rect(Math.Min(_x, value), Top, Math.Abs(_x - value) + Width, Height);
_x = value;
Invalidate(r);
/*if (_parent != null)
{
_parent.Render(r, true);
}*/
}
}
/// <summary>
/// Gets/Sets the Y position in pixels
/// </summary>
/// <remarks>
/// Y is a relative location inside the parent, Top is the exact location on the screen
/// </remarks>
public virtual int Y
{
get { return _y; }
set
{
if (_y == value)
{
return;
}
// Create update region
var r = new rect(Left, Math.Min(_y, value), Width, Math.Abs(_y - value) + Height);
_y = value;
Invalidate(r);
/*if (_parent != null)
{
_parent.Render(r, true);
}*/
}
}
#endregion
#region Buttons
/// <summary>
/// Override this message to handle button pressed events internally.
/// </summary>
/// <param name="buttonId">Integer ID corresponding to the affected button</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
protected virtual void ButtonPressedMessage(int buttonId, ref bool handled)
{ }
/// <summary>
/// Override this message to handle button released events internally.
/// </summary>
/// <param name="buttonId">Integer ID corresponding to the affected button</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
protected virtual void ButtonReleasedMessage(int buttonId, ref bool handled)
{ }
/// <summary>
/// Directly inform control of button events
/// </summary>
/// <param name="buttonId">Integer ID corresponding to the affected button</param>
/// <param name="pressed">True if the button is currently being pressed; false if released</param>
public void SendButtonEvent(int buttonId, bool pressed)
{
bool handled = false;
if (pressed)
{
ButtonPressedMessage(buttonId, ref handled);
if (handled)
{
return;
}
OnButtonPressed(this, buttonId);
if (buttonId == (int) ButtonIDs.Click || buttonId == (int) ButtonIDs.Select)
{
SendTouchDown(this, Core.MousePosition);
}
}
else
{
ButtonReleasedMessage(buttonId, ref handled);
if (handled)
{
return;
}
if (buttonId == (int) ButtonIDs.Click || buttonId == (int) ButtonIDs.Select)
{
SendTouchUp(this, Core.MousePosition);
}
OnButtonReleased(this, buttonId);
}
}
#endregion
#region Keyboard
/// <summary>
/// Override this message to handle alt key events internally.
/// </summary>
/// <param name="key">Integer value of the Alt key affected</param>
/// <param name="pressed">True if the key is currently being pressed; false if released</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
protected virtual void KeyboardAltKeyMessage(int key, bool pressed, ref bool handled)
{ }
/// <summary>
/// Override this message to handle key events internally.
/// </summary>
/// <param name="key">Integer value of the key affected</param>
/// <param name="pressed">True if the key is currently being pressed; false if released</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
protected virtual void KeyboardKeyMessage(char key, bool pressed, ref bool handled)
{ }
/// <summary>
/// Directly inform control of keyboard alt key events
/// </summary>
/// <param name="key">Integer value of the Alt key affected</param>
/// <param name="pressed">True if the key is currently being pressed; false if released</param>
public void SendKeyboardAltKeyEvent(int key, bool pressed)
{
bool handled = false;
KeyboardAltKeyMessage(key, pressed, ref handled);
if (!handled)
{
OnKeyboardAltKey(this, key, pressed);
}
}
/// <summary>
/// Directly inform control of keyboard key events
/// </summary>
/// <param name="key">Integer value of the key affected</param>
/// <param name="pressed">True if the key is currently being pressed; false if released</param>
public void SendKeyboardKeyEvent(char key, bool pressed)
{
bool handled = false;
KeyboardKeyMessage(key, pressed, ref handled);
if (!handled)
{
OnKeyboardKey(this, key, pressed);
}
}
#endregion
#region Touch
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
protected virtual void TouchDownMessage(object sender, point point, ref bool handled)
{ }
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="type">Type of touch gesture</param>
/// <param name="force">Force associated with gesture (0.0 to 1.0)</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
protected virtual void TouchGestureMessage(object sender, TouchType type, float force, ref bool handled)
{ }
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
protected virtual void TouchMoveMessage(object sender, point point, ref bool handled)
{ }
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
protected virtual void TouchUpMessage(object sender, point point, ref bool handled)
{ }
/// <summary>
/// Directly inform control of touch down event
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
public void SendTouchDown(object sender, point point)
{
// Exit if needed
if (!_enabled || !_visible || _suspended)
{
return;
}
bool bHandled = false;
// Allow Override
TouchDownMessage(sender, point, ref bHandled);
// Exit if handled
if (bHandled)
{
return;
}
// Set down state
_mDown = true;
// Begin Tap/Hold
_ptTapHold = point;
_eTapHold = TapState.TapHoldWaiting;
_lStop = DateTime.Now.Ticks + (500 * TimeSpan.TicksPerMillisecond);
if (_thHold == null || !_thHold.IsAlive)
{
_thHold = new Thread(TapHoldWaiter);
_thHold.Start();
}
// Raise Event
OnTouchDown(sender, point);
}
/// <summary>
/// Directly inform control of touch up event
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
public void SendTouchUp(object sender, point point)
{
if (!_enabled || !_visible || _suspended)
{
_mDown = false;
return;
}
bool bHandled = false;
// Check Tap Hold
_eTapHold = TapState.Normal;
// Allow Override
TouchUpMessage(sender, point, ref bHandled);
// Exit if handled
if (bHandled)
{
return;
}
// Perform normal tap
if (_mDown)
{
if (new rect(Left, Top, Width, Height).Contains(point))
{
if (DateTime.Now.Ticks - _lastTap < (TimeSpan.TicksPerMillisecond * 500))
{
OnDoubleTap(this, new point(point.X - Left, point.Y - Top));
_lastTap = 0;
}
else
{
OnTap(this, new point(point.X - Left, point.Y - Top));
_lastTap = DateTime.Now.Ticks;
}
}
_mDown = false;
OnTouchUp(this, point);
}
}
/// <summary>
/// Directly inform control of touch move event
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
public void SendTouchMove(object sender, point point)
{
if (!_enabled || !_visible || _suspended)
{
return;
}
bool bHandled = false;
// Allow Override
TouchMoveMessage(sender, point, ref bHandled);
// Exit if handled
if (bHandled)
{
return;
}
_eTapHold = TapState.Normal;
OnTouchMove(this, point);
}
/// <summary>
/// Directly inform control of touch gesture event
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="type">Type of gesture being sent</param>
/// <param name="force">Force associated with gesture (0.0 to 1.0)</param>
public void SendTouchGesture(object sender, TouchType type, float force)
{
if (!_enabled || !_visible || _suspended)
{
return;
}
bool bHandled = false;
// Allow Override
TouchGestureMessage(sender, type, force, ref bHandled);
// Exit if handled
if (bHandled)
{
return;
}
OnTouchGesture(this, type, force);
}
/// <summary>
/// Method for detecting Tap & Hold
/// </summary>
private void TapHoldWaiter()
{
while (DateTime.Now.Ticks < _lStop)
{
Thread.Sleep(10);
if (_eTapHold == TapState.Normal)
{
return;
}
}
if (_eTapHold == TapState.Normal || !_enabled || !_visible || _suspended)
{
return;
}
//_mDown = false;
_eTapHold = TapState.Normal;
OnTapHold(this, _ptTapHold);
}
#endregion
#region Disposing
/// <summary>
/// Disposes the control
/// </summary>
/// <remarks>
/// All resources used by this control will be freed
/// </remarks>
public void Dispose()
{
if (_disposing)
{
return;
}
_disposing = true;
// Remove Events
DoubleTap = null;
Tap = null;
TapHold = null;
TouchDown = null;
TouchGesture = null;
TouchMove = null;
TouchUp = null;
}
#endregion
#region Focus
/// <summary>
/// Activates the control
/// </summary>
/// <remarks>
/// Activate is called by a container when a control becomes focused. Calling Activate by itself will only invoke Invalidate().
/// </remarks>
public virtual void Activate()
{
Invalidate();
}
/// <summary>
/// Deactivates the control
/// </summary>
/// <remarks>
/// Called by the parent when a control loses focus. If called by itself this will only result in Invalidate() being invoked.
/// </remarks>
public virtual void Blur()
{
_mDown = false;
Invalidate();
}
/// <summary>
/// Checks if a point is inside of the control
/// </summary>
/// <param name="point">Point to check if is inside control's ScreenBounds</param>
/// <returns>Returns true if the point is inside the bounds of the control; else false</returns>
/// <remarks>
/// HitTest checks a point based on the control's ScreenBounds (Left, Top, Width, Height).
/// The results of this method are used to determine if a control is being affected by touch events or should be rendered during partial screen updates.
/// </remarks>
public virtual bool HitTest(point point)
{
return ScreenBounds.Contains(point);
}
#endregion
#region GUI
/// <summary>
/// Safely redraws control
/// </summary>
/// <remarks>
/// Invalidating a control means that every control in the parent container that intersects the controls area is redrawn. This helps keep z-ordering intact.
/// </remarks>
public void Invalidate()
{
if ((_parent == null && Core.ActiveContainer != this) || (_parent != null && _parent.Suspended) || !_visible ||
_suspended)
{
return;
}
if (_parent == null)
{
Render(true);
}
else
{
_parent.TopLevelContainer.Render(ScreenBounds, true);
}
}
/// <summary>
/// Safely redraws control
/// </summary>
/// <param name="area">Defines the area of the control to be redrawn</param>
/// <remarks>
/// If rect area is null the entire control will be redrawn.
/// Invalidating a control means that every control in the parent container that intersects the controls area is redrawn. This helps keep z-ordering intact.
/// </remarks>
public void Invalidate(rect area)
{
if ((_parent == null && Core.ActiveContainer != this) || (_parent != null && _parent.Suspended) || !_visible ||
_suspended)
{
return;
}
if (_parent == null)
{
Render(true);
}
else
{
_parent.TopLevelContainer.Render(area, true);
}
}
/// <summary>
/// Unsafely renders control
/// </summary>
/// <param name="flush">When true the updates will be pushed to the screen, otherwise they will sit in the buffer</param>
/// <remarks>
/// Rendering a control will not cause other controls in the same space to be rendered, calling this method can break z-index ordering.
/// If it is certain no other controls will overlap the rendered control calling Render() can result in faster speeds than Invalidate().
/// </remarks>
public void Render(bool flush = false)
{
// Check if we actually need to render
if ((_parent == null && Core.ActiveContainer != this) || (_parent != null && _parent.Suspended) || !_visible ||
_suspended)
{
return;
}
int cw, ch;
if (_parent == null)
{
cw = Width;
ch = Height;
}
else
{
cw = Math.Min(_parent.Width - X, Width);
ch = Math.Min(_parent.Height - Y, Height);
}
if (cw < 1 || ch < 1)
{
return;
}
// Update clip
Core.Screen.SetClippingRectangle(Left, Top, cw, ch);
// Render control
lock (Core.Screen)
{
OnRender(Left, Top, cw, ch);
}
// Reset clip
//Core.Screen.SetClippingRectangle(0, 0, Core.ScreenWidth, Core.ScreenHeight);
// Flush as needed
if (flush)
{
Core.SafeFlush(Left, Top, cw, ch);
}
}
/// <summary>
/// Renders the control contents
/// </summary>
/// <param name="x">X position in screen coordinates</param>
/// <param name="y">Y position in screen coordinates</param>
/// <param name="width">Width in pixel</param>
/// <param name="height">Height in pixel</param>
/// <remarks>
/// Override this method to render the contents of the control
/// </remarks>
protected virtual void OnRender(int x, int y, int width, int height)
{ }
/// <summary>
/// Update the X/Y position offset of the control
/// </summary>
public void UpdateOffsets()
{
if (_parent != null)
{
_offsetX = _parent.Left;
_offsetY = _parent.Top;
}
else
{
_offsetX = 0;
_offsetY = 0;
}
// Handle Containers
var container = this as Container;
if (container != null)
{
if (container.Children != null)
{
for (int i = 0; i < container.Children.Length; i++)
{
container.Children[i].UpdateOffsets();
}
}
}
}
/// <summary>
/// Update the X/Y position offset of the control
/// </summary>
/// <param name="pt">When supplied this sets an exact offset for the control, regardless of its parent position and offset</param>
/// <remarks>
/// If point pt is passed the native offsetting is ignored in favor of the supplied coordinated; this can yield unexpected results.
/// </remarks>
public void UpdateOffsets(point pt)
{
_offsetX = pt.X;
_offsetY = pt.Y;
// Handle Containers
var container = this as Container;
if (container != null)
{
if (container.Children != null)
{
for (int i = 0; i < container.Children.Length; i++)
{
container.Children[i].UpdateOffsets();
}
}
}
}
#endregion
}
}
| |
/*************************************************************************
Copyright (c) 1992-2007 The University of Tennessee. All rights reserved.
Contributors:
* Sergey Bochkanov (ALGLIB project). Translation from FORTRAN to
pseudocode.
See subroutines comments for additional copyrights.
>>> SOURCE LICENSE >>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation (www.fsf.org); either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************/
using System;
namespace FuncLib.Mathematics.LinearAlgebra.AlgLib
{
internal class sblas
{
public static void symmetricmatrixvectormultiply(ref double[,] a,
bool isupper,
int i1,
int i2,
ref double[] x,
double alpha,
ref double[] y)
{
int i = 0;
int ba1 = 0;
int ba2 = 0;
int by1 = 0;
int by2 = 0;
int bx1 = 0;
int bx2 = 0;
int n = 0;
double v = 0;
int i_ = 0;
int i1_ = 0;
n = i2 - i1 + 1;
if (n <= 0)
{
return;
}
//
// Let A = L + D + U, where
// L is strictly lower triangular (main diagonal is zero)
// D is diagonal
// U is strictly upper triangular (main diagonal is zero)
//
// A*x = L*x + D*x + U*x
//
// Calculate D*x first
//
for (i = i1; i <= i2; i++)
{
y[i - i1 + 1] = a[i, i] * x[i - i1 + 1];
}
//
// Add L*x + U*x
//
if (isupper)
{
for (i = i1; i <= i2 - 1; i++)
{
//
// Add L*x to the result
//
v = x[i - i1 + 1];
by1 = i - i1 + 2;
by2 = n;
ba1 = i + 1;
ba2 = i2;
i1_ = (ba1) - (by1);
for (i_ = by1; i_ <= by2; i_++)
{
y[i_] = y[i_] + v * a[i, i_ + i1_];
}
//
// Add U*x to the result
//
bx1 = i - i1 + 2;
bx2 = n;
ba1 = i + 1;
ba2 = i2;
i1_ = (ba1) - (bx1);
v = 0.0;
for (i_ = bx1; i_ <= bx2; i_++)
{
v += x[i_] * a[i, i_ + i1_];
}
y[i - i1 + 1] = y[i - i1 + 1] + v;
}
}
else
{
for (i = i1 + 1; i <= i2; i++)
{
//
// Add L*x to the result
//
bx1 = 1;
bx2 = i - i1;
ba1 = i1;
ba2 = i - 1;
i1_ = (ba1) - (bx1);
v = 0.0;
for (i_ = bx1; i_ <= bx2; i_++)
{
v += x[i_] * a[i, i_ + i1_];
}
y[i - i1 + 1] = y[i - i1 + 1] + v;
//
// Add U*x to the result
//
v = x[i - i1 + 1];
by1 = 1;
by2 = i - i1;
ba1 = i1;
ba2 = i - 1;
i1_ = (ba1) - (by1);
for (i_ = by1; i_ <= by2; i_++)
{
y[i_] = y[i_] + v * a[i, i_ + i1_];
}
}
}
for (i_ = 1; i_ <= n; i_++)
{
y[i_] = alpha * y[i_];
}
}
public static void symmetricrank2update(ref double[,] a,
bool isupper,
int i1,
int i2,
ref double[] x,
ref double[] y,
ref double[] t,
double alpha)
{
int i = 0;
int tp1 = 0;
int tp2 = 0;
double v = 0;
int i_ = 0;
int i1_ = 0;
if (isupper)
{
for (i = i1; i <= i2; i++)
{
tp1 = i + 1 - i1;
tp2 = i2 - i1 + 1;
v = x[i + 1 - i1];
for (i_ = tp1; i_ <= tp2; i_++)
{
t[i_] = v * y[i_];
}
v = y[i + 1 - i1];
for (i_ = tp1; i_ <= tp2; i_++)
{
t[i_] = t[i_] + v * x[i_];
}
for (i_ = tp1; i_ <= tp2; i_++)
{
t[i_] = alpha * t[i_];
}
i1_ = (tp1) - (i);
for (i_ = i; i_ <= i2; i_++)
{
a[i, i_] = a[i, i_] + t[i_ + i1_];
}
}
}
else
{
for (i = i1; i <= i2; i++)
{
tp1 = 1;
tp2 = i + 1 - i1;
v = x[i + 1 - i1];
for (i_ = tp1; i_ <= tp2; i_++)
{
t[i_] = v * y[i_];
}
v = y[i + 1 - i1];
for (i_ = tp1; i_ <= tp2; i_++)
{
t[i_] = t[i_] + v * x[i_];
}
for (i_ = tp1; i_ <= tp2; i_++)
{
t[i_] = alpha * t[i_];
}
i1_ = (tp1) - (i1);
for (i_ = i1; i_ <= i; i_++)
{
a[i, i_] = a[i, i_] + t[i_ + i1_];
}
}
}
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Org.OpenAPITools.Converters;
namespace Org.OpenAPITools.Models
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class InputStepImpl : IEquatable<InputStepImpl>
{
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Links
/// </summary>
[DataMember(Name="_links", EmitDefaultValue=false)]
public InputStepImpllinks Links { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Message
/// </summary>
[DataMember(Name="message", EmitDefaultValue=false)]
public string Message { get; set; }
/// <summary>
/// Gets or Sets Ok
/// </summary>
[DataMember(Name="ok", EmitDefaultValue=false)]
public string Ok { get; set; }
/// <summary>
/// Gets or Sets Parameters
/// </summary>
[DataMember(Name="parameters", EmitDefaultValue=false)]
public List<StringParameterDefinition> Parameters { get; set; }
/// <summary>
/// Gets or Sets Submitter
/// </summary>
[DataMember(Name="submitter", EmitDefaultValue=false)]
public string Submitter { 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 InputStepImpl {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Links: ").Append(Links).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Message: ").Append(Message).Append("\n");
sb.Append(" Ok: ").Append(Ok).Append("\n");
sb.Append(" Parameters: ").Append(Parameters).Append("\n");
sb.Append(" Submitter: ").Append(Submitter).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 Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.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 (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((InputStepImpl)obj);
}
/// <summary>
/// Returns true if InputStepImpl instances are equal
/// </summary>
/// <param name="other">Instance of InputStepImpl to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InputStepImpl other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Class == other.Class ||
Class != null &&
Class.Equals(other.Class)
) &&
(
Links == other.Links ||
Links != null &&
Links.Equals(other.Links)
) &&
(
Id == other.Id ||
Id != null &&
Id.Equals(other.Id)
) &&
(
Message == other.Message ||
Message != null &&
Message.Equals(other.Message)
) &&
(
Ok == other.Ok ||
Ok != null &&
Ok.Equals(other.Ok)
) &&
(
Parameters == other.Parameters ||
Parameters != null &&
other.Parameters != null &&
Parameters.SequenceEqual(other.Parameters)
) &&
(
Submitter == other.Submitter ||
Submitter != null &&
Submitter.Equals(other.Submitter)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
// Suitable nullity checks etc, of course :)
if (Class != null)
hashCode = hashCode * 59 + Class.GetHashCode();
if (Links != null)
hashCode = hashCode * 59 + Links.GetHashCode();
if (Id != null)
hashCode = hashCode * 59 + Id.GetHashCode();
if (Message != null)
hashCode = hashCode * 59 + Message.GetHashCode();
if (Ok != null)
hashCode = hashCode * 59 + Ok.GetHashCode();
if (Parameters != null)
hashCode = hashCode * 59 + Parameters.GetHashCode();
if (Submitter != null)
hashCode = hashCode * 59 + Submitter.GetHashCode();
return hashCode;
}
}
#region Operators
#pragma warning disable 1591
public static bool operator ==(InputStepImpl left, InputStepImpl right)
{
return Equals(left, right);
}
public static bool operator !=(InputStepImpl left, InputStepImpl right)
{
return !Equals(left, right);
}
#pragma warning restore 1591
#endregion Operators
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Extensions;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Models.Collections
{
public abstract class Item : IEntity, ICanBeDirty
{
private bool _withChanges = true; // should we track changes?
private bool _hasIdentity;
private int _id;
private Guid _key;
protected Item() => _propertyChangedInfo = new Dictionary<string, bool>();
/// <summary>
/// Gets or sets the integer Id
/// </summary>
[DataMember]
public int Id
{
get => _id;
set
{
_id = value;
HasIdentity = true;
}
}
/// <summary>
/// Gets or sets the Guid based Id
/// </summary>
/// <remarks>The key is currectly used to store the Unique Id from the
/// umbracoNode table, which many of the entities are based on.</remarks>
[DataMember]
public Guid Key
{
get => _key == Guid.Empty ? _id.ToGuid() : _key;
set => _key = value;
}
/// <summary>
/// Gets or sets the Created Date
/// </summary>
[DataMember]
public DateTime CreateDate { get; set; }
/// <summary>
/// Gets or sets the Modified Date
/// </summary>
[DataMember]
public DateTime UpdateDate { get; set; }
/// <summary>
/// Gets or sets the Deleted Date
/// </summary>
[DataMember]
public DateTime? DeleteDate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether some action against an entity was cancelled through some event.
/// This only exists so we have a way to check if an event was cancelled through
/// the new api, which also needs to take effect in the legacy api.
/// </summary>
[IgnoreDataMember]
internal bool WasCancelled { get; set; }
/// <summary>
/// Property changed event
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Method to call on a property setter.
/// </summary>
/// <param name="propertyInfo">The property info.</param>
protected virtual void OnPropertyChanged(PropertyInfo propertyInfo)
{
if (_withChanges == false)
{
return;
}
_propertyChangedInfo[propertyInfo.Name] = true;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyInfo.Name));
}
public virtual void ResetIdentity()
{
_hasIdentity = false;
_id = default;
}
/// <summary>
/// Method to call on entity saved when first added
/// </summary>
internal virtual void AddingEntity()
{
CreateDate = DateTime.Now;
UpdateDate = DateTime.Now;
}
/// <summary>
/// Method to call on entity saved/updated
/// </summary>
internal virtual void UpdatingEntity() => UpdateDate = DateTime.Now;
/// <summary>
/// Tracks the properties that have changed
/// </summary>
private readonly IDictionary<string, bool> _propertyChangedInfo;
/// <summary>
/// Indicates whether a specific property on the current entity is dirty.
/// </summary>
/// <param name="propertyName">Name of the property to check</param>
/// <returns>True if Property is dirty, otherwise False</returns>
public virtual bool IsPropertyDirty(string propertyName) => _propertyChangedInfo.Any(x => x.Key == propertyName);
public virtual IEnumerable<string> GetDirtyProperties() => _propertyChangedInfo.Keys;
/// <summary>
/// Indicates whether the current entity is dirty.
/// </summary>
/// <returns>True if entity is dirty, otherwise False</returns>
public virtual bool IsDirty() => _propertyChangedInfo.Any();
/// <summary>
/// Resets dirty properties by clearing the dictionary used to track changes.
/// </summary>
/// <remarks>
/// Please note that resetting the dirty properties could potentially
/// obstruct the saving of a new or updated entity.
/// </remarks>
public virtual void ResetDirtyProperties() => _propertyChangedInfo.Clear();
/// <summary>
/// Disables change tracking.
/// </summary>
public void DisableChangeTracking() => _withChanges = false;
/// <summary>
/// Enables change tracking.
/// </summary>
public void EnableChangeTracking() => _withChanges = true;
/// <summary>
/// Gets or sets a value indicating whether the current entity has an identity, eg. Id.
/// </summary>
public virtual bool HasIdentity
{
get => _hasIdentity;
protected set => _hasIdentity = value;
}
public static bool operator ==(Item left, Item right) => ReferenceEquals(left, right);
public static bool operator !=(Item left, Item right) => !(left == right);
/*public virtual bool SameIdentityAs(IEntity other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return SameIdentityAs(other as Entity);
}
public virtual bool Equals(Entity other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return SameIdentityAs(other);
}
public virtual Type GetRealType()
{
return GetType();
}
public virtual bool SameIdentityAs(Entity other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (GetType() == other.GetRealType() && HasIdentity && other.HasIdentity)
return other.Id.Equals(Id);
return false;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
return SameIdentityAs(obj as IEntity);
}
public override int GetHashCode()
{
if (!_hash.HasValue)
_hash = !HasIdentity ? new int?(base.GetHashCode()) : new int?(Id.GetHashCode() * 397 ^ GetType().GetHashCode());
return _hash.Value;
}*/
public object DeepClone() => this.MemberwiseClone();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Threading;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Interop;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Portable;
using Apache.Ignite.Core.Impl.Portable.IO;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Lifecycle;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
using PU = Apache.Ignite.Core.Impl.Portable.PortableUtils;
/// <summary>
/// This class defines a factory for the main Ignite API.
/// <p/>
/// Use <see cref="Ignition.Start()"/> method to start Ignite with default configuration.
/// <para/>
/// All members are thread-safe and may be used concurrently from multiple threads.
/// <example>
/// You can also use <see cref="IgniteConfiguration"/> to override some default configuration.
/// Below is an example on how to start Ignite with custom configuration for portable types and
/// provide path to Spring XML configuration file:
/// <code>
/// IgniteConfiguration cfg = new IgniteConfiguration();
///
/// // Create portable type configuration.
/// PortableConfiguration portableCfg = new PortableConfiguration();
///
/// cfg.SpringConfigUrl = "examples\\config\\example-cache.xml";
///
/// portableCfg.TypeConfigurations = new List<PortableTypeConfiguration>
/// {
/// new PortableTypeConfiguration(typeof(Address)),
/// new PortableTypeConfiguration(typeof(Organization))
/// };
///
/// cfg.PortableConfiguration = portableCfg;
///
/// // Start Ignite node with Ignite configuration.
/// var ignite = Ignition.Start(cfg);
/// </code>
/// </example>
/// </summary>
public static class Ignition
{
/** */
private const string DefaultCfg = "config/default-config.xml";
/** */
private static readonly object SyncRoot = new object();
/** GC warning flag. */
private static int _gcWarn;
/** */
private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>();
/** Current DLL name. */
private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
/** Startup info. */
[ThreadStatic]
private static Startup _startup;
/** Client mode flag. */
[ThreadStatic]
private static bool _clientMode;
/// <summary>
/// Static initializer.
/// </summary>
static Ignition()
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
/// <summary>
/// Gets or sets a value indicating whether Ignite should be started in client mode.
/// Client nodes cannot hold data in caches.
/// </summary>
public static bool ClientMode
{
get { return _clientMode; }
set { _clientMode = value; }
}
/// <summary>
/// Starts Ignite with default configuration. By default this method will
/// use Ignite configuration defined in <code>IGNITE/config/default-config.xml</code>
/// configuration file. If such file is not found, then all system defaults will be used.
/// </summary>
/// <returns>Started Ignite.</returns>
public static IIgnite Start()
{
return Start(new IgniteConfiguration());
}
/// <summary>
/// Starts all grids specified within given Spring XML configuration file. If Ignite with given name
/// is already started, then exception is thrown. In this case all instances that may
/// have been started so far will be stopped too.
/// </summary>
/// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be
/// absolute or relative to IGNITE_HOME.</param>
/// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st
/// found instance is returned.</returns>
public static IIgnite Start(string springCfgPath)
{
return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath});
}
/// <summary>
/// Starts Ignite with given configuration.
/// </summary>
/// <returns>Started Ignite.</returns>
public unsafe static IIgnite Start(IgniteConfiguration cfg)
{
IgniteArgumentCheck.NotNull(cfg, "cfg");
// Copy configuration to avoid changes to user-provided instance.
IgniteConfigurationEx cfgEx = cfg as IgniteConfigurationEx;
cfg = cfgEx == null ? new IgniteConfiguration(cfg) : new IgniteConfigurationEx(cfgEx);
// Set default Spring config if needed.
if (cfg.SpringConfigUrl == null)
cfg.SpringConfigUrl = DefaultCfg;
lock (SyncRoot)
{
// 1. Check GC settings.
CheckServerGc(cfg);
// 2. Create context.
IgniteUtils.LoadDlls(cfg.JvmDllPath);
var cbs = new UnmanagedCallbacks();
void* ctx = IgniteManager.GetContext(cfg, cbs);
sbyte* cfgPath0 = IgniteUtils.StringToUtf8Unmanaged(cfg.SpringConfigUrl ?? DefaultCfg);
string gridName = cfgEx != null ? cfgEx.GridName : null;
sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName);
// 3. Create startup object which will guide us through the rest of the process.
_startup = new Startup(cfg) { Context = ctx };
IUnmanagedTarget interopProc = null;
try
{
// 4. Initiate Ignite start.
interopProc = UU.IgnitionStart(cbs.Context, cfg.SpringConfigUrl ?? DefaultCfg,
cfgEx != null ? cfgEx.GridName : null, ClientMode);
// 5. At this point start routine is finished. We expect STARTUP object to have all necessary data.
Ignite node = new Ignite(cfg, _startup.Name, interopProc, _startup.Marshaller,
_startup.LifecycleBeans, cbs);
// 6. On-start callback (notify lifecycle components).
node.OnStart();
Nodes[new NodeKey(_startup.Name)] = node;
return node;
}
catch (Exception)
{
// 1. Perform keys cleanup.
string name = _startup.Name;
if (name != null)
{
NodeKey key = new NodeKey(name);
if (Nodes.ContainsKey(key))
Nodes.Remove(key);
}
// 2. Stop Ignite node if it was started.
if (interopProc != null)
UU.IgnitionStop(interopProc.Context, gridName, true);
// 3. Throw error further (use startup error if exists because it is more precise).
if (_startup.Error != null)
throw _startup.Error;
throw;
}
finally
{
_startup = null;
Marshal.FreeHGlobal((IntPtr)cfgPath0);
if ((IntPtr)gridName0 != IntPtr.Zero)
Marshal.FreeHGlobal((IntPtr)gridName0);
if (interopProc != null)
UU.ProcessorReleaseStart(interopProc);
}
}
}
/// <summary>
/// Check whether GC is set to server mode.
/// </summary>
/// <param name="cfg">Configuration.</param>
private static void CheckServerGc(IgniteConfiguration cfg)
{
if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0)
Console.WriteLine("GC server mode is not enabled, this could lead to less " +
"than optimal performance on multi-core machines (to enable see " +
"http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx).");
}
/// <summary>
/// Prepare callback invoked from Java.
/// </summary>
/// <param name="inStream">Intput stream with data.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="handleRegistry">Handle registry.</param>
internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream,
HandleRegistry handleRegistry)
{
try
{
PortableReaderImpl reader = PU.Marshaller.StartUnmarshal(inStream);
PrepareConfiguration(reader.ReadObject<InteropDotNetConfiguration>());
PrepareLifecycleBeans(reader, outStream, handleRegistry);
}
catch (Exception e)
{
_startup.Error = e;
throw;
}
}
/// <summary>
/// Preapare configuration.
/// </summary>
/// <param name="dotNetCfg">Dot net configuration.</param>
private static void PrepareConfiguration(InteropDotNetConfiguration dotNetCfg)
{
// 1. Load assemblies.
IgniteConfiguration cfg = _startup.Configuration;
LoadAssemblies(cfg.Assemblies);
if (dotNetCfg != null)
LoadAssemblies(dotNetCfg.Assemblies);
// 2. Create marshaller only after assemblies are loaded.
if (cfg.PortableConfiguration == null && dotNetCfg != null && dotNetCfg.PortableCfg != null)
cfg.PortableConfiguration = dotNetCfg.PortableCfg.ToPortableConfiguration();
_startup.Marshaller = new PortableMarshaller(cfg.PortableConfiguration);
}
/// <summary>
/// Prepare lifecycle beans.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="handleRegistry">Handle registry.</param>
private static void PrepareLifecycleBeans(PortableReaderImpl reader, PlatformMemoryStream outStream,
HandleRegistry handleRegistry)
{
IList<LifecycleBeanHolder> beans = new List<LifecycleBeanHolder>();
// 1. Read beans defined in Java.
int cnt = reader.ReadInt();
for (int i = 0; i < cnt; i++)
beans.Add(new LifecycleBeanHolder(CreateLifecycleBean(reader)));
// 2. Append beans definied in local configuration.
ICollection<ILifecycleBean> nativeBeans = _startup.Configuration.LifecycleBeans;
if (nativeBeans != null)
{
foreach (ILifecycleBean nativeBean in nativeBeans)
beans.Add(new LifecycleBeanHolder(nativeBean));
}
// 3. Write bean pointers to Java stream.
outStream.WriteInt(beans.Count);
foreach (LifecycleBeanHolder bean in beans)
outStream.WriteLong(handleRegistry.AllocateCritical(bean));
outStream.SynchronizeOutput();
// 4. Set beans to STARTUP object.
_startup.LifecycleBeans = beans;
}
/// <summary>
/// Create lifecycle bean.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>Lifecycle bean.</returns>
internal static ILifecycleBean CreateLifecycleBean(PortableReaderImpl reader)
{
// 1. Instantiate.
string assemblyName = reader.ReadString();
string clsName = reader.ReadString();
object bean = IgniteUtils.CreateInstance(assemblyName, clsName);
// 2. Set properties.
IDictionary<string, object> props = reader.ReadGenericDictionary<string, object>();
IgniteUtils.SetProperties(bean, props);
return bean as ILifecycleBean;
}
/// <summary>
/// Kernal start callback.
/// </summary>
/// <param name="stream">Stream.</param>
internal static void OnStart(IPortableStream stream)
{
try
{
// 1. Read data and leave critical state ASAP.
PortableReaderImpl reader = PU.Marshaller.StartUnmarshal(stream);
// ReSharper disable once PossibleInvalidOperationException
var name = reader.ReadString();
// 2. Set ID and name so that Start() method can use them later.
_startup.Name = name;
if (Nodes.ContainsKey(new NodeKey(name)))
throw new IgniteException("Ignite with the same name already started: " + name);
}
catch (Exception e)
{
// 5. Preserve exception to throw it later in the "Start" method and throw it further
// to abort startup in Java.
_startup.Error = e;
throw;
}
}
/// <summary>
/// Load assemblies.
/// </summary>
/// <param name="assemblies">Assemblies.</param>
private static void LoadAssemblies(IEnumerable<string> assemblies)
{
if (assemblies != null)
{
foreach (string s in assemblies)
{
// 1. Try loading as directory.
if (Directory.Exists(s))
{
string[] files = Directory.GetFiles(s, "*.dll");
#pragma warning disable 0168
foreach (string dllPath in files)
{
if (!SelfAssembly(dllPath))
{
try
{
Assembly.LoadFile(dllPath);
}
catch (BadImageFormatException)
{
// No-op.
}
}
}
#pragma warning restore 0168
continue;
}
// 2. Try loading using full-name.
try
{
Assembly assembly = Assembly.Load(s);
if (assembly != null)
continue;
}
catch (Exception e)
{
if (!(e is FileNotFoundException || e is FileLoadException))
throw new IgniteException("Failed to load assembly: " + s, e);
}
// 3. Try loading using file path.
try
{
Assembly assembly = Assembly.LoadFrom(s);
if (assembly != null)
continue;
}
catch (Exception e)
{
if (!(e is FileNotFoundException || e is FileLoadException))
throw new IgniteException("Failed to load assembly: " + s, e);
}
// 4. Not found, exception.
throw new IgniteException("Failed to load assembly: " + s);
}
}
}
/// <summary>
/// Whether assembly points to Ignite binary.
/// </summary>
/// <param name="assembly">Assembly to check..</param>
/// <returns><c>True</c> if this is one of GG assemblies.</returns>
private static bool SelfAssembly(string assembly)
{
return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Gets a named Ignite instance. If Ignite name is {@code null} or empty string,
/// then default no-name Ignite will be returned. Note that caller of this method
/// should not assume that it will return the same instance every time.
/// <p/>
/// Note that single process can run multiple Ignite instances and every Ignite instance (and its
/// node) can belong to a different grid. Ignite name defines what grid a particular Ignite
/// instance (and correspondingly its node) belongs to.
/// </summary>
/// <param name="name">Ignite name to which requested Ignite instance belongs. If <code>null</code>,
/// then Ignite instance belonging to a default no-name Ignite will be returned.
/// </param>
/// <returns>An instance of named grid.</returns>
public static IIgnite GetIgnite(string name)
{
lock (SyncRoot)
{
Ignite result;
if (!Nodes.TryGetValue(new NodeKey(name), out result))
throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name);
return result;
}
}
/// <summary>
/// Gets an instance of default no-name grid. Note that
/// caller of this method should not assume that it will return the same
/// instance every time.
/// </summary>
/// <returns>An instance of default no-name grid.</returns>
public static IIgnite GetIgnite()
{
return GetIgnite(null);
}
/// <summary>
/// Stops named grid. If <code>cancel</code> flag is set to <code>true</code> then
/// all jobs currently executing on local node will be interrupted. If
/// grid name is <code>null</code>, then default no-name Ignite will be stopped.
/// </summary>
/// <param name="name">Grid name. If <code>null</code>, then default no-name Ignite will be stopped.</param>
/// <param name="cancel">If <code>true</code> then all jobs currently executing will be cancelled
/// by calling <code>ComputeJob.cancel</code>method.</param>
/// <returns><code>true</code> if named Ignite instance was indeed found and stopped, <code>false</code>
/// othwerwise (the instance with given <code>name</code> was not found).</returns>
public static bool Stop(string name, bool cancel)
{
lock (SyncRoot)
{
NodeKey key = new NodeKey(name);
Ignite node;
if (!Nodes.TryGetValue(key, out node))
return false;
node.Stop(cancel);
Nodes.Remove(key);
GC.Collect();
return true;
}
}
/// <summary>
/// Stops <b>all</b> started grids. If <code>cancel</code> flag is set to <code>true</code> then
/// all jobs currently executing on local node will be interrupted.
/// </summary>
/// <param name="cancel">If <code>true</code> then all jobs currently executing will be cancelled
/// by calling <code>ComputeJob.cancel</code>method.</param>
public static void StopAll(bool cancel)
{
lock (SyncRoot)
{
while (Nodes.Count > 0)
{
var entry = Nodes.First();
entry.Value.Stop(cancel);
Nodes.Remove(entry.Key);
}
}
GC.Collect();
}
/// <summary>
/// Handles the AssemblyResolve event of the CurrentDomain control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="args">The <see cref="ResolveEventArgs"/> instance containing the event data.</param>
/// <returns>Manually resolved assembly, or null.</returns>
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
return LoadedAssembliesResolver.Instance.GetAssembly(args.Name);
}
/// <summary>
/// Grid key.
/// </summary>
private class NodeKey
{
/** */
private readonly string _name;
/// <summary>
/// Initializes a new instance of the <see cref="NodeKey"/> class.
/// </summary>
/// <param name="name">The name.</param>
internal NodeKey(string name)
{
_name = name;
}
/** <inheritdoc /> */
public override bool Equals(object obj)
{
var other = obj as NodeKey;
return other != null && Equals(_name, other._name);
}
/** <inheritdoc /> */
public override int GetHashCode()
{
return _name == null ? 0 : _name.GetHashCode();
}
}
/// <summary>
/// Value object to pass data between .Net methods during startup bypassing Java.
/// </summary>
private unsafe class Startup
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configuration.</param>
internal Startup(IgniteConfiguration cfg)
{
Configuration = cfg;
}
/// <summary>
/// Configuration.
/// </summary>
internal IgniteConfiguration Configuration { get; private set; }
/// <summary>
/// Lifecycle beans.
/// </summary>
internal IList<LifecycleBeanHolder> LifecycleBeans { get; set; }
/// <summary>
/// Node name.
/// </summary>
internal string Name { get; set; }
/// <summary>
/// Marshaller.
/// </summary>
internal PortableMarshaller Marshaller { get; set; }
/// <summary>
/// Start error.
/// </summary>
internal Exception Error { get; set; }
/// <summary>
/// Gets or sets the context.
/// </summary>
internal void* Context { get; set; }
}
}
}
| |
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 ASP.NET_Single_Page_application__SPA_.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="CurrencyConstantServiceClient"/> instances.</summary>
public sealed partial class CurrencyConstantServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CurrencyConstantServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CurrencyConstantServiceSettings"/>.</returns>
public static CurrencyConstantServiceSettings GetDefault() => new CurrencyConstantServiceSettings();
/// <summary>
/// Constructs a new <see cref="CurrencyConstantServiceSettings"/> object with default settings.
/// </summary>
public CurrencyConstantServiceSettings()
{
}
private CurrencyConstantServiceSettings(CurrencyConstantServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCurrencyConstantSettings = existing.GetCurrencyConstantSettings;
OnCopy(existing);
}
partial void OnCopy(CurrencyConstantServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CurrencyConstantServiceClient.GetCurrencyConstant</c> and
/// <c>CurrencyConstantServiceClient.GetCurrencyConstantAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetCurrencyConstantSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CurrencyConstantServiceSettings"/> object.</returns>
public CurrencyConstantServiceSettings Clone() => new CurrencyConstantServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CurrencyConstantServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class CurrencyConstantServiceClientBuilder : gaxgrpc::ClientBuilderBase<CurrencyConstantServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CurrencyConstantServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CurrencyConstantServiceClientBuilder()
{
UseJwtAccessWithScopes = CurrencyConstantServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CurrencyConstantServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CurrencyConstantServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CurrencyConstantServiceClient Build()
{
CurrencyConstantServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CurrencyConstantServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CurrencyConstantServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CurrencyConstantServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CurrencyConstantServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CurrencyConstantServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CurrencyConstantServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CurrencyConstantServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CurrencyConstantServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CurrencyConstantServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CurrencyConstantService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch currency constants.
/// </remarks>
public abstract partial class CurrencyConstantServiceClient
{
/// <summary>
/// The default endpoint for the CurrencyConstantService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CurrencyConstantService scopes.</summary>
/// <remarks>
/// The default CurrencyConstantService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CurrencyConstantServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="CurrencyConstantServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CurrencyConstantServiceClient"/>.</returns>
public static stt::Task<CurrencyConstantServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CurrencyConstantServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CurrencyConstantServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="CurrencyConstantServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CurrencyConstantServiceClient"/>.</returns>
public static CurrencyConstantServiceClient Create() => new CurrencyConstantServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CurrencyConstantServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CurrencyConstantServiceSettings"/>.</param>
/// <returns>The created <see cref="CurrencyConstantServiceClient"/>.</returns>
internal static CurrencyConstantServiceClient Create(grpccore::CallInvoker callInvoker, CurrencyConstantServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CurrencyConstantService.CurrencyConstantServiceClient grpcClient = new CurrencyConstantService.CurrencyConstantServiceClient(callInvoker);
return new CurrencyConstantServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CurrencyConstantService client</summary>
public virtual CurrencyConstantService.CurrencyConstantServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CurrencyConstant GetCurrencyConstant(GetCurrencyConstantRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CurrencyConstant> GetCurrencyConstantAsync(GetCurrencyConstantRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CurrencyConstant> GetCurrencyConstantAsync(GetCurrencyConstantRequest request, st::CancellationToken cancellationToken) =>
GetCurrencyConstantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the currency constant to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CurrencyConstant GetCurrencyConstant(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCurrencyConstant(new GetCurrencyConstantRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the currency constant to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CurrencyConstant> GetCurrencyConstantAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCurrencyConstantAsync(new GetCurrencyConstantRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the currency constant to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CurrencyConstant> GetCurrencyConstantAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCurrencyConstantAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the currency constant to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CurrencyConstant GetCurrencyConstant(gagvr::CurrencyConstantName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCurrencyConstant(new GetCurrencyConstantRequest
{
ResourceNameAsCurrencyConstantName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the currency constant to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CurrencyConstant> GetCurrencyConstantAsync(gagvr::CurrencyConstantName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCurrencyConstantAsync(new GetCurrencyConstantRequest
{
ResourceNameAsCurrencyConstantName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the currency constant to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CurrencyConstant> GetCurrencyConstantAsync(gagvr::CurrencyConstantName resourceName, st::CancellationToken cancellationToken) =>
GetCurrencyConstantAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CurrencyConstantService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch currency constants.
/// </remarks>
public sealed partial class CurrencyConstantServiceClientImpl : CurrencyConstantServiceClient
{
private readonly gaxgrpc::ApiCall<GetCurrencyConstantRequest, gagvr::CurrencyConstant> _callGetCurrencyConstant;
/// <summary>
/// Constructs a client wrapper for the CurrencyConstantService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="CurrencyConstantServiceSettings"/> used within this client.
/// </param>
public CurrencyConstantServiceClientImpl(CurrencyConstantService.CurrencyConstantServiceClient grpcClient, CurrencyConstantServiceSettings settings)
{
GrpcClient = grpcClient;
CurrencyConstantServiceSettings effectiveSettings = settings ?? CurrencyConstantServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCurrencyConstant = clientHelper.BuildApiCall<GetCurrencyConstantRequest, gagvr::CurrencyConstant>(grpcClient.GetCurrencyConstantAsync, grpcClient.GetCurrencyConstant, effectiveSettings.GetCurrencyConstantSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCurrencyConstant);
Modify_GetCurrencyConstantApiCall(ref _callGetCurrencyConstant);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetCurrencyConstantApiCall(ref gaxgrpc::ApiCall<GetCurrencyConstantRequest, gagvr::CurrencyConstant> call);
partial void OnConstruction(CurrencyConstantService.CurrencyConstantServiceClient grpcClient, CurrencyConstantServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CurrencyConstantService client</summary>
public override CurrencyConstantService.CurrencyConstantServiceClient GrpcClient { get; }
partial void Modify_GetCurrencyConstantRequest(ref GetCurrencyConstantRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::CurrencyConstant GetCurrencyConstant(GetCurrencyConstantRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCurrencyConstantRequest(ref request, ref callSettings);
return _callGetCurrencyConstant.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested currency constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::CurrencyConstant> GetCurrencyConstantAsync(GetCurrencyConstantRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCurrencyConstantRequest(ref request, ref callSettings);
return _callGetCurrencyConstant.Async(request, callSettings);
}
}
}
| |
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using System;
using System.Collections.Generic;
using System.Text;
using erl.Oracle.TnsNames.Antlr4.Runtime;
using erl.Oracle.TnsNames.Antlr4.Runtime.Misc;
using erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen;
namespace erl.Oracle.TnsNames.Antlr4.Runtime
{
/// <summary>
/// This implementation of
/// <see cref="ITokenStream"/>
/// loads tokens from a
/// <see cref="ITokenSource"/>
/// on-demand, and places the tokens in a buffer to provide
/// access to any previous token by index.
/// <p>
/// This token stream ignores the value of
/// <see cref="IToken.Channel()"/>
/// . If your
/// parser requires the token stream filter tokens to only those on a particular
/// channel, such as
/// <see cref="TokenConstants.DefaultChannel"/>
/// or
/// <see cref="TokenConstants.HiddenChannel"/>
/// , use a filtering token stream such a
/// <see cref="CommonTokenStream"/>
/// .</p>
/// </summary>
public class BufferedTokenStream : ITokenStream
{
/// <summary>
/// The
/// <see cref="ITokenSource"/>
/// from which tokens for this stream are fetched.
/// </summary>
[NotNull]
private ITokenSource _tokenSource;
/// <summary>A collection of all tokens fetched from the token source.</summary>
/// <remarks>
/// A collection of all tokens fetched from the token source. The list is
/// considered a complete view of the input once
/// <see cref="fetchedEOF"/>
/// is set
/// to
/// <see langword="true"/>
/// .
/// </remarks>
protected internal IList<IToken> tokens = new List<IToken>(100);
/// <summary>
/// The index into
/// <see cref="tokens"/>
/// of the current token (next token to
/// <see cref="Consume()"/>
/// ).
/// <see cref="tokens"/>
/// <c>[</c>
/// <see cref="p"/>
/// <c>]</c>
/// should be
/// <see cref="LT(int)">LT(1)</see>
/// .
/// <p>This field is set to -1 when the stream is first constructed or when
/// <see cref="SetTokenSource(ITokenSource)"/>
/// is called, indicating that the first token has
/// not yet been fetched from the token source. For additional information,
/// see the documentation of
/// <see cref="IIntStream"/>
/// for a description of
/// Initializing Methods.</p>
/// </summary>
protected internal int p = -1;
/// <summary>
/// Indicates whether the
/// <see cref="TokenConstants.EOF"/>
/// token has been fetched from
/// <see cref="_tokenSource"/>
/// and added to
/// <see cref="tokens"/>
/// . This field improves
/// performance for the following cases:
/// <ul>
/// <li>
/// <see cref="Consume()"/>
/// : The lookahead check in
/// <see cref="Consume()"/>
/// to prevent
/// consuming the EOF symbol is optimized by checking the values of
/// <see cref="fetchedEOF"/>
/// and
/// <see cref="p"/>
/// instead of calling
/// <see cref="LA(int)"/>
/// .</li>
/// <li>
/// <see cref="Fetch(int)"/>
/// : The check to prevent adding multiple EOF symbols into
/// <see cref="tokens"/>
/// is trivial with this field.</li>
/// </ul>
/// </summary>
protected internal bool fetchedEOF;
public BufferedTokenStream(ITokenSource tokenSource)
{
if (tokenSource == null)
{
throw new ArgumentNullException("tokenSource cannot be null");
}
this._tokenSource = tokenSource;
}
public virtual ITokenSource TokenSource
{
get
{
return _tokenSource;
}
}
public virtual int Index
{
get
{
return p;
}
}
public virtual int Mark()
{
return 0;
}
public virtual void Release(int marker)
{
}
// no resources to release
public virtual void Reset()
{
Seek(0);
}
public virtual void Seek(int index)
{
LazyInit();
p = AdjustSeekIndex(index);
}
public virtual int Size
{
get
{
return tokens.Count;
}
}
public virtual void Consume()
{
bool skipEofCheck;
if (p >= 0)
{
if (fetchedEOF)
{
// the last token in tokens is EOF. skip check if p indexes any
// fetched token except the last.
skipEofCheck = p < tokens.Count - 1;
}
else
{
// no EOF token in tokens. skip check if p indexes a fetched token.
skipEofCheck = p < tokens.Count;
}
}
else
{
// not yet initialized
skipEofCheck = false;
}
if (!skipEofCheck && LA(1) == IntStreamConstants.EOF)
{
throw new InvalidOperationException("cannot consume EOF");
}
if (Sync(p + 1))
{
p = AdjustSeekIndex(p + 1);
}
}
/// <summary>
/// Make sure index
/// <paramref name="i"/>
/// in tokens has a token.
/// </summary>
/// <returns>
///
/// <see langword="true"/>
/// if a token is located at index
/// <paramref name="i"/>
/// , otherwise
/// <see langword="false"/>
/// .
/// </returns>
/// <seealso cref="Get(int)"/>
protected internal virtual bool Sync(int i)
{
System.Diagnostics.Debug.Assert(i >= 0);
int n = i - tokens.Count + 1;
// how many more elements we need?
//System.out.println("sync("+i+") needs "+n);
if (n > 0)
{
int fetched = Fetch(n);
return fetched >= n;
}
return true;
}
/// <summary>
/// Add
/// <paramref name="n"/>
/// elements to buffer.
/// </summary>
/// <returns>The actual number of elements added to the buffer.</returns>
protected internal virtual int Fetch(int n)
{
if (fetchedEOF)
{
return 0;
}
for (int i = 0; i < n; i++)
{
IToken t = _tokenSource.NextToken();
if (t is IWritableToken)
{
((IWritableToken)t).TokenIndex = tokens.Count;
}
tokens.Add(t);
if (t.Type == TokenConstants.EOF)
{
fetchedEOF = true;
return i + 1;
}
}
return n;
}
public virtual IToken Get(int i)
{
if (i < 0 || i >= tokens.Count)
{
throw new ArgumentOutOfRangeException("token index " + i + " out of range 0.." + (tokens.Count - 1));
}
return tokens[i];
}
/// <summary>Get all tokens from start..stop inclusively.</summary>
/// <remarks>Get all tokens from start..stop inclusively.</remarks>
public virtual IList<IToken> Get(int start, int stop)
{
if (start < 0 || stop < 0)
{
return null;
}
LazyInit();
IList<IToken> subset = new List<IToken>();
if (stop >= tokens.Count)
{
stop = tokens.Count - 1;
}
for (int i = start; i <= stop; i++)
{
IToken t = tokens[i];
if (t.Type == TokenConstants.EOF)
{
break;
}
subset.Add(t);
}
return subset;
}
public virtual int LA(int i)
{
return LT(i).Type;
}
protected internal virtual IToken Lb(int k)
{
if ((p - k) < 0)
{
return null;
}
return tokens[p - k];
}
[return: NotNull]
public virtual IToken LT(int k)
{
LazyInit();
if (k == 0)
{
return null;
}
if (k < 0)
{
return Lb(-k);
}
int i = p + k - 1;
Sync(i);
if (i >= tokens.Count)
{
// return EOF token
// EOF must be last token
return tokens[tokens.Count - 1];
}
// if ( i>range ) range = i;
return tokens[i];
}
/// <summary>
/// Allowed derived classes to modify the behavior of operations which change
/// the current stream position by adjusting the target token index of a seek
/// operation.
/// </summary>
/// <remarks>
/// Allowed derived classes to modify the behavior of operations which change
/// the current stream position by adjusting the target token index of a seek
/// operation. The default implementation simply returns
/// <paramref name="i"/>
/// . If an
/// exception is thrown in this method, the current stream index should not be
/// changed.
/// <p>For example,
/// <see cref="CommonTokenStream"/>
/// overrides this method to ensure that
/// the seek target is always an on-channel token.</p>
/// </remarks>
/// <param name="i">The target token index.</param>
/// <returns>The adjusted target token index.</returns>
protected internal virtual int AdjustSeekIndex(int i)
{
return i;
}
protected internal void LazyInit()
{
if (p == -1)
{
Setup();
}
}
protected internal virtual void Setup()
{
Sync(0);
p = AdjustSeekIndex(0);
}
/// <summary>Reset this token stream by setting its token source.</summary>
/// <remarks>Reset this token stream by setting its token source.</remarks>
public virtual void SetTokenSource(ITokenSource tokenSource)
{
this._tokenSource = tokenSource;
tokens.Clear();
p = -1;
this.fetchedEOF = false;
}
public virtual IList<IToken> GetTokens()
{
return tokens;
}
public virtual IList<IToken> GetTokens(int start, int stop)
{
return GetTokens(start, stop, null);
}
/// <summary>
/// Given a start and stop index, return a
/// <c>List</c>
/// of all tokens in
/// the token type
/// <c>BitSet</c>
/// . Return
/// <see langword="null"/>
/// if no tokens were found. This
/// method looks at both on and off channel tokens.
/// </summary>
public virtual IList<IToken> GetTokens(int start, int stop, BitSet types)
{
LazyInit();
if (start < 0 || stop >= tokens.Count || stop < 0 || start >= tokens.Count)
{
throw new ArgumentOutOfRangeException("start " + start + " or stop " + stop + " not in 0.." + (tokens.Count - 1));
}
if (start > stop)
{
return null;
}
// list = tokens[start:stop]:{T t, t.getType() in types}
IList<IToken> filteredTokens = new List<IToken>();
for (int i = start; i <= stop; i++)
{
IToken t = tokens[i];
if (types == null || types.Get(t.Type))
{
filteredTokens.Add(t);
}
}
if (filteredTokens.Count == 0)
{
filteredTokens = null;
}
return filteredTokens;
}
public virtual IList<IToken> GetTokens(int start, int stop, int ttype)
{
BitSet s = new BitSet(ttype);
s.Set(ttype);
return GetTokens(start, stop, s);
}
/// <summary>Given a starting index, return the index of the next token on channel.</summary>
/// <remarks>
/// Given a starting index, return the index of the next token on channel.
/// Return
/// <paramref name="i"/>
/// if
/// <c>tokens[i]</c>
/// is on channel. Return the index of
/// the EOF token if there are no tokens on channel between
/// <paramref name="i"/>
/// and
/// EOF.
/// </remarks>
protected internal virtual int NextTokenOnChannel(int i, int channel)
{
Sync(i);
if (i >= Size)
{
return Size - 1;
}
IToken token = tokens[i];
while (token.Channel != channel)
{
if (token.Type == TokenConstants.EOF)
{
return i;
}
i++;
Sync(i);
token = tokens[i];
}
return i;
}
/// <summary>
/// Given a starting index, return the index of the previous token on
/// channel.
/// </summary>
/// <remarks>
/// Given a starting index, return the index of the previous token on
/// channel. Return
/// <paramref name="i"/>
/// if
/// <c>tokens[i]</c>
/// is on channel. Return -1
/// if there are no tokens on channel between
/// <paramref name="i"/>
/// and 0.
/// <p>
/// If
/// <paramref name="i"/>
/// specifies an index at or after the EOF token, the EOF token
/// index is returned. This is due to the fact that the EOF token is treated
/// as though it were on every channel.</p>
/// </remarks>
protected internal virtual int PreviousTokenOnChannel(int i, int channel)
{
Sync(i);
if (i >= Size)
{
// the EOF token is on every channel
return Size - 1;
}
while (i >= 0)
{
IToken token = tokens[i];
if (token.Type == TokenConstants.EOF || token.Channel == channel)
{
return i;
}
i--;
}
return i;
}
/// <summary>
/// Collect all tokens on specified channel to the right of
/// the current token up until we see a token on
/// <see cref="Lexer.DefaultTokenChannel"/>
/// or
/// EOF. If
/// <paramref name="channel"/>
/// is
/// <c>-1</c>
/// , find any non default channel token.
/// </summary>
public virtual IList<IToken> GetHiddenTokensToRight(int tokenIndex, int channel)
{
LazyInit();
if (tokenIndex < 0 || tokenIndex >= tokens.Count)
{
throw new ArgumentOutOfRangeException(tokenIndex + " not in 0.." + (tokens.Count - 1));
}
int nextOnChannel = NextTokenOnChannel(tokenIndex + 1, Lexer.DefaultTokenChannel);
int to;
int from = tokenIndex + 1;
// if none onchannel to right, nextOnChannel=-1 so set to = last token
if (nextOnChannel == -1)
{
to = Size - 1;
}
else
{
to = nextOnChannel;
}
return FilterForChannel(from, to, channel);
}
/// <summary>
/// Collect all hidden tokens (any off-default channel) to the right of
/// the current token up until we see a token on
/// <see cref="Lexer.DefaultTokenChannel"/>
/// or EOF.
/// </summary>
public virtual IList<IToken> GetHiddenTokensToRight(int tokenIndex)
{
return GetHiddenTokensToRight(tokenIndex, -1);
}
/// <summary>
/// Collect all tokens on specified channel to the left of
/// the current token up until we see a token on
/// <see cref="Lexer.DefaultTokenChannel"/>
/// .
/// If
/// <paramref name="channel"/>
/// is
/// <c>-1</c>
/// , find any non default channel token.
/// </summary>
public virtual IList<IToken> GetHiddenTokensToLeft(int tokenIndex, int channel)
{
LazyInit();
if (tokenIndex < 0 || tokenIndex >= tokens.Count)
{
throw new ArgumentOutOfRangeException(tokenIndex + " not in 0.." + (tokens.Count - 1));
}
if (tokenIndex == 0)
{
// obviously no tokens can appear before the first token
return null;
}
int prevOnChannel = PreviousTokenOnChannel(tokenIndex - 1, Lexer.DefaultTokenChannel);
if (prevOnChannel == tokenIndex - 1)
{
return null;
}
// if none onchannel to left, prevOnChannel=-1 then from=0
int from = prevOnChannel + 1;
int to = tokenIndex - 1;
return FilterForChannel(from, to, channel);
}
/// <summary>
/// Collect all hidden tokens (any off-default channel) to the left of
/// the current token up until we see a token on
/// <see cref="Lexer.DefaultTokenChannel"/>
/// .
/// </summary>
public virtual IList<IToken> GetHiddenTokensToLeft(int tokenIndex)
{
return GetHiddenTokensToLeft(tokenIndex, -1);
}
protected internal virtual IList<IToken> FilterForChannel(int from, int to, int channel)
{
IList<IToken> hidden = new List<IToken>();
for (int i = from; i <= to; i++)
{
IToken t = tokens[i];
if (channel == -1)
{
if (t.Channel != Lexer.DefaultTokenChannel)
{
hidden.Add(t);
}
}
else
{
if (t.Channel == channel)
{
hidden.Add(t);
}
}
}
if (hidden.Count == 0)
{
return null;
}
return hidden;
}
public virtual string SourceName
{
get
{
return _tokenSource.SourceName;
}
}
/// <summary>Get the text of all tokens in this buffer.</summary>
/// <remarks>Get the text of all tokens in this buffer.</remarks>
[return: NotNull]
public virtual string GetText()
{
Fill();
return GetText(Interval.Of(0, Size - 1));
}
[return: NotNull]
public virtual string GetText(Interval interval)
{
int start = interval.a;
int stop = interval.b;
if (start < 0 || stop < 0)
{
return string.Empty;
}
LazyInit();
if (stop >= tokens.Count)
{
stop = tokens.Count - 1;
}
StringBuilder buf = new StringBuilder();
for (int i = start; i <= stop; i++)
{
IToken t = tokens[i];
if (t.Type == TokenConstants.EOF)
{
break;
}
buf.Append(t.Text);
}
return buf.ToString();
}
[return: NotNull]
public virtual string GetText(RuleContext ctx)
{
return GetText(ctx.SourceInterval);
}
[return: NotNull]
public virtual string GetText(IToken start, IToken stop)
{
if (start != null && stop != null)
{
return GetText(Interval.Of(start.TokenIndex, stop.TokenIndex));
}
return string.Empty;
}
/// <summary>Get all tokens from lexer until EOF.</summary>
/// <remarks>Get all tokens from lexer until EOF.</remarks>
public virtual void Fill()
{
LazyInit();
int blockSize = 1000;
while (true)
{
int fetched = Fetch(blockSize);
if (fetched < blockSize)
{
return;
}
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Map/Fort/FortSummary.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Map.Fort {
/// <summary>Holder for reflection information generated from POGOProtos/Map/Fort/FortSummary.proto</summary>
public static partial class FortSummaryReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Map/Fort/FortSummary.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FortSummaryReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVQT0dPUHJvdG9zL01hcC9Gb3J0L0ZvcnRTdW1tYXJ5LnByb3RvEhNQT0dP",
"UHJvdG9zLk1hcC5Gb3J0Im8KC0ZvcnRTdW1tYXJ5EhcKD2ZvcnRfc3VtbWFy",
"eV9pZBgBIAEoCRIiChpsYXN0X21vZGlmaWVkX3RpbWVzdGFtcF9tcxgCIAEo",
"AxIQCghsYXRpdHVkZRgDIAEoARIRCglsb25naXR1ZGUYBCABKAFiBnByb3Rv",
"Mw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Map.Fort.FortSummary), global::POGOProtos.Map.Fort.FortSummary.Parser, new[]{ "FortSummaryId", "LastModifiedTimestampMs", "Latitude", "Longitude" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class FortSummary : pb::IMessage<FortSummary> {
private static readonly pb::MessageParser<FortSummary> _parser = new pb::MessageParser<FortSummary>(() => new FortSummary());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FortSummary> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Map.Fort.FortSummaryReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortSummary() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortSummary(FortSummary other) : this() {
fortSummaryId_ = other.fortSummaryId_;
lastModifiedTimestampMs_ = other.lastModifiedTimestampMs_;
latitude_ = other.latitude_;
longitude_ = other.longitude_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortSummary Clone() {
return new FortSummary(this);
}
/// <summary>Field number for the "fort_summary_id" field.</summary>
public const int FortSummaryIdFieldNumber = 1;
private string fortSummaryId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string FortSummaryId {
get { return fortSummaryId_; }
set {
fortSummaryId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "last_modified_timestamp_ms" field.</summary>
public const int LastModifiedTimestampMsFieldNumber = 2;
private long lastModifiedTimestampMs_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long LastModifiedTimestampMs {
get { return lastModifiedTimestampMs_; }
set {
lastModifiedTimestampMs_ = value;
}
}
/// <summary>Field number for the "latitude" field.</summary>
public const int LatitudeFieldNumber = 3;
private double latitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Latitude {
get { return latitude_; }
set {
latitude_ = value;
}
}
/// <summary>Field number for the "longitude" field.</summary>
public const int LongitudeFieldNumber = 4;
private double longitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Longitude {
get { return longitude_; }
set {
longitude_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FortSummary);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FortSummary other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (FortSummaryId != other.FortSummaryId) return false;
if (LastModifiedTimestampMs != other.LastModifiedTimestampMs) return false;
if (Latitude != other.Latitude) return false;
if (Longitude != other.Longitude) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (FortSummaryId.Length != 0) hash ^= FortSummaryId.GetHashCode();
if (LastModifiedTimestampMs != 0L) hash ^= LastModifiedTimestampMs.GetHashCode();
if (Latitude != 0D) hash ^= Latitude.GetHashCode();
if (Longitude != 0D) hash ^= Longitude.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (FortSummaryId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(FortSummaryId);
}
if (LastModifiedTimestampMs != 0L) {
output.WriteRawTag(16);
output.WriteInt64(LastModifiedTimestampMs);
}
if (Latitude != 0D) {
output.WriteRawTag(25);
output.WriteDouble(Latitude);
}
if (Longitude != 0D) {
output.WriteRawTag(33);
output.WriteDouble(Longitude);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (FortSummaryId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FortSummaryId);
}
if (LastModifiedTimestampMs != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(LastModifiedTimestampMs);
}
if (Latitude != 0D) {
size += 1 + 8;
}
if (Longitude != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FortSummary other) {
if (other == null) {
return;
}
if (other.FortSummaryId.Length != 0) {
FortSummaryId = other.FortSummaryId;
}
if (other.LastModifiedTimestampMs != 0L) {
LastModifiedTimestampMs = other.LastModifiedTimestampMs;
}
if (other.Latitude != 0D) {
Latitude = other.Latitude;
}
if (other.Longitude != 0D) {
Longitude = other.Longitude;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
FortSummaryId = input.ReadString();
break;
}
case 16: {
LastModifiedTimestampMs = input.ReadInt64();
break;
}
case 25: {
Latitude = input.ReadDouble();
break;
}
case 33: {
Longitude = input.ReadDouble();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#if MAGICONION_UNITASK_SUPPORT
using Cysharp.Threading.Tasks;
using Channel = Grpc.Core.Channel;
#endif
using Grpc.Core;
#if USE_GRPC_NET_CLIENT
using Grpc.Net.Client;
#endif
using MagicOnion.Client;
using MagicOnion.Unity;
using UnityEngine;
namespace MagicOnion
{
/// <summary>
/// gRPC Channel wrapper that managed by the channel provider.
/// </summary>
public sealed partial class GrpcChannelx : ChannelBase, IMagicOnionAwareGrpcChannel, IDisposable
#if UNITY_EDITOR || MAGICONION_ENABLE_CHANNEL_DIAGNOSTICS
, IGrpcChannelxDiagnosticsInfo
#endif
#if MAGICONION_UNITASK_SUPPORT
, IUniTaskAsyncDisposable
#endif
{
private readonly Action<GrpcChannelx> _onDispose;
private readonly Dictionary<IStreamingHubMarker, (Func<Task> DisposeAsync, ManagedStreamingHubInfo StreamingHubInfo)> _streamingHubs = new Dictionary<IStreamingHubMarker, (Func<Task>, ManagedStreamingHubInfo)>();
private readonly ChannelBase _channel;
private bool _disposed;
public Uri TargetUri { get; }
public int Id { get; }
#if UNITY_EDITOR || MAGICONION_ENABLE_CHANNEL_DIAGNOSTICS
private readonly string _stackTrace;
private readonly ChannelStats _channelStats;
private readonly GrpcChannelOptionsBag _channelOptions;
string IGrpcChannelxDiagnosticsInfo.StackTrace => _stackTrace;
ChannelStats IGrpcChannelxDiagnosticsInfo.Stats => _channelStats;
GrpcChannelOptionsBag IGrpcChannelxDiagnosticsInfo.ChannelOptions => _channelOptions;
ChannelBase IGrpcChannelxDiagnosticsInfo.UnderlyingChannel => _channel;
#endif
public GrpcChannelx(int id, Action<GrpcChannelx> onDispose, ChannelBase channel, Uri targetUri, GrpcChannelOptionsBag channelOptions)
: base(targetUri.ToString())
{
Id = id;
TargetUri = targetUri;
_onDispose = onDispose;
_channel = channel;
_disposed = false;
#if UNITY_EDITOR || MAGICONION_ENABLE_CHANNEL_DIAGNOSTICS
_stackTrace = new System.Diagnostics.StackTrace().ToString();
_channelStats = new ChannelStats();
_channelOptions = channelOptions;
#endif
}
/// <summary>
/// Create a channel to the specified target.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
[Obsolete("Use ForTarget instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static GrpcChannelx FromTarget(GrpcChannelTarget target)
=> GrpcChannelProvider.Default.CreateChannel(target);
/// <summary>
/// Create a channel to the specified target.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
[Obsolete("Use ForAddress instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static GrpcChannelx FromAddress(Uri target)
=> GrpcChannelProvider.Default.CreateChannel(new GrpcChannelTarget(target.Host, target.Port, target.Scheme == "http"));
/// <summary>
/// Create a channel to the specified target.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static GrpcChannelx ForTarget(GrpcChannelTarget target)
=> GrpcChannelProvider.Default.CreateChannel(target);
/// <summary>
/// Create a channel to the specified target.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static GrpcChannelx ForAddress(string target)
=> ForAddress(new Uri(target));
/// <summary>
/// Create a channel to the specified target.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static GrpcChannelx ForAddress(Uri target)
=> GrpcChannelProvider.Default.CreateChannel(new GrpcChannelTarget(target.Host, target.Port, target.Scheme == "http"));
/// <summary>
/// Create a <see cref="CallInvoker"/>.
/// </summary>
/// <returns></returns>
public override CallInvoker CreateCallInvoker()
{
ThrowIfDisposed();
#if UNITY_EDITOR || MAGICONION_ENABLE_CHANNEL_DIAGNOSTICS
return new ChannelStats.WrappedCallInvoker(((IGrpcChannelxDiagnosticsInfo)this).Stats, _channel.CreateCallInvoker());
#else
return _channel.CreateCallInvoker();
#endif
}
protected override async Task ShutdownAsyncCore()
{
#if MAGICONION_UNITASK_SUPPORT
await ShutdownInternalAsync();
#else
await ShutdownInternalAsync().ConfigureAwait(false);
#endif
}
/// <summary>
/// Connect to the target using gRPC channel. see <see cref="Grpc.Core.Channel.ConnectAsync"/>.
/// </summary>
/// <param name="deadline"></param>
/// <returns></returns>
[Obsolete]
#if MAGICONION_UNITASK_SUPPORT
public async UniTask ConnectAsync(DateTime? deadline = null)
#else
public async Task ConnectAsync(DateTime? deadline = null)
#endif
{
ThrowIfDisposed();
#if !USE_GRPC_NET_CLIENT_ONLY
if (_channel is Channel grpcCChannel)
{
await grpcCChannel.ConnectAsync(deadline);
}
#endif
}
/// <inheritdoc />
IReadOnlyCollection<ManagedStreamingHubInfo> IMagicOnionAwareGrpcChannel.GetAllManagedStreamingHubs()
{
lock (_streamingHubs)
{
return _streamingHubs.Values.Select(x => x.StreamingHubInfo).ToArray();
}
}
/// <inheritdoc />
void IMagicOnionAwareGrpcChannel.ManageStreamingHubClient(Type streamingHubType, IStreamingHubMarker streamingHub, Func<Task> disposeAsync, Task waitForDisconnect)
{
lock (_streamingHubs)
{
_streamingHubs.Add(streamingHub, (disposeAsync, new ManagedStreamingHubInfo(streamingHubType, streamingHub)));
// When the channel is disconnected, unregister it.
Forget(WaitForDisconnectAndDisposeAsync(streamingHub, waitForDisconnect));
}
}
#if MAGICONION_UNITASK_SUPPORT
private async UniTask WaitForDisconnectAndDisposeAsync(IStreamingHubMarker streamingHub, Task waitForDisconnect)
#else
private async Task WaitForDisconnectAndDisposeAsync(IStreamingHubMarker streamingHub, Task waitForDisconnect)
#endif
{
await waitForDisconnect;
DisposeStreamingHubClient(streamingHub);
}
private void DisposeStreamingHubClient(IStreamingHubMarker streamingHub)
{
lock (_streamingHubs)
{
if (_streamingHubs.TryGetValue(streamingHub, out var disposeAsyncAndStreamingHubInfo))
{
try
{
Forget(disposeAsyncAndStreamingHubInfo.DisposeAsync());
}
catch (Exception e)
{
Debug.LogException(e);
}
_streamingHubs.Remove(streamingHub);
}
}
async void Forget(Task t)
{
try
{
await t;
}
catch (Exception e)
{
Debug.LogException(e);
}
}
}
private void DisposeAllManagedStreamingHubs()
{
lock (_streamingHubs)
{
foreach (var streamingHub in _streamingHubs.Keys.ToArray() /* Snapshot */)
{
DisposeStreamingHubClient(streamingHub);
}
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
try
{
DisposeAllManagedStreamingHubs();
Forget(ShutdownInternalAsync());
}
finally
{
_onDispose(this);
}
}
#if MAGICONION_UNITASK_SUPPORT
public async UniTask DisposeAsync()
#else
public async Task DisposeAsync()
#endif
{
if (_disposed) return;
_disposed = true;
try
{
DisposeAllManagedStreamingHubs();
await ShutdownInternalAsync();
}
finally
{
_onDispose(this);
}
}
#if MAGICONION_UNITASK_SUPPORT
private async UniTask ShutdownInternalAsync()
#else
private async Task ShutdownInternalAsync()
#endif
{
await _channel.ShutdownAsync().ConfigureAwait(false);
}
private void ThrowIfDisposed()
{
if (_disposed) throw new ObjectDisposedException(nameof(GrpcChannelx));
}
#if MAGICONION_UNITASK_SUPPORT
private static async void Forget(UniTask t)
=> t.Forget();
#endif
private static async void Forget(Task t)
{
try
{
await t;
}
catch (Exception e)
{
Debug.LogException(e);
}
}
#if UNITY_EDITOR || MAGICONION_ENABLE_CHANNEL_DIAGNOSTICS
public class ChannelStats
{
private int _sentBytes = 0;
private int _receivedBytes = 0;
private int _indexSentBytes;
private int _indexReceivedBytes;
private DateTime _prevSentBytesAt;
private DateTime _prevReceivedBytesAt;
private readonly int[] _sentBytesHistory = new int[10];
private readonly int[] _receivedBytesHistory = new int[10];
public int SentBytes => _sentBytes;
public int ReceivedBytes => _receivedBytes;
public int SentBytesPerSecond
{
get
{
AddValue(ref _prevSentBytesAt, ref _indexSentBytes, _sentBytesHistory, DateTime.Now, 0);
return _sentBytesHistory.Sum();
}
}
public int ReceiveBytesPerSecond
{
get
{
AddValue(ref _prevReceivedBytesAt, ref _indexReceivedBytes, _receivedBytesHistory, DateTime.Now, 0);
return _receivedBytesHistory.Sum();
}
}
internal void AddSentBytes(int bytesLength)
{
Interlocked.Add(ref _sentBytes, bytesLength);
AddValue(ref _prevSentBytesAt, ref _indexSentBytes, _sentBytesHistory, DateTime.Now, bytesLength);
}
internal void AddReceivedBytes(int bytesLength)
{
Interlocked.Add(ref _receivedBytes, bytesLength);
AddValue(ref _prevReceivedBytesAt, ref _indexReceivedBytes, _receivedBytesHistory, DateTime.Now, bytesLength);
}
private void AddValue(ref DateTime prev, ref int index, int[] values, DateTime d, int value)
{
lock (values)
{
var elapsed = d - prev;
if (elapsed.TotalMilliseconds > 1000)
{
index = 0;
Array.Clear(values, 0, values.Length);
prev = d;
}
else if (elapsed.TotalMilliseconds > 100)
{
var advance = (int)(elapsed.TotalMilliseconds / 100);
for (var i = 0; i < advance; i++)
{
values[(++index % values.Length)] = 0;
}
prev = d;
}
values[index % values.Length] += value;
}
}
internal class WrappedCallInvoker : CallInvoker
{
private readonly CallInvoker _baseCallInvoker;
private readonly ChannelStats _channelStats;
public WrappedCallInvoker(ChannelStats channelStats, CallInvoker callInvoker)
{
_channelStats = channelStats;
_baseCallInvoker = callInvoker;
}
public override TResponse BlockingUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
{
//Debug.Log($"Unary(Blocking): {method.FullName}");
return _baseCallInvoker.BlockingUnaryCall(WrapMethod(method), host, options, request);
}
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
{
//Debug.Log($"Unary: {method.FullName}");
return _baseCallInvoker.AsyncUnaryCall(WrapMethod(method), host, options, request);
}
public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
{
//Debug.Log($"ServerStreaming: {method.FullName}");
return _baseCallInvoker.AsyncServerStreamingCall(WrapMethod(method), host, options, request);
}
public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options)
{
//Debug.Log($"ClientStreaming: {method.FullName}");
return _baseCallInvoker.AsyncClientStreamingCall(WrapMethod(method), host, options);
}
public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options)
{
//Debug.Log($"DuplexStreaming: {method.FullName}");
return _baseCallInvoker.AsyncDuplexStreamingCall(WrapMethod(method), host, options);
}
private Method<TRequest, TResponse> WrapMethod<TRequest, TResponse>(Method<TRequest, TResponse> method)
{
var wrappedMethod = new Method<TRequest, TResponse>(
method.Type,
method.ServiceName,
method.Name,
new Marshaller<TRequest>(x =>
{
var bytes = method.RequestMarshaller.Serializer(x);
_channelStats.AddSentBytes(bytes.Length);
return bytes;
}, x => method.RequestMarshaller.Deserializer(x)),
new Marshaller<TResponse>(x => method.ResponseMarshaller.Serializer(x), x =>
{
_channelStats.AddReceivedBytes(x.Length);
return method.ResponseMarshaller.Deserializer(x);
})
);
return wrappedMethod;
}
}
}
#endif
}
#if UNITY_EDITOR || MAGICONION_ENABLE_CHANNEL_DIAGNOSTICS
public interface IGrpcChannelxDiagnosticsInfo
{
string StackTrace { get; }
GrpcChannelx.ChannelStats Stats { get; }
GrpcChannelOptionsBag ChannelOptions { get; }
ChannelBase UnderlyingChannel { get; }
}
#endif
}
| |
using Akavache;
using Espera.Core.Audio;
using Espera.Core.Management;
using Espera.Network;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Rareform.Validation;
using ReactiveMarrow;
using ReactiveUI;
using Splat;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Espera.Core.Mobile
{
/// <summary>
/// Represents one mobile endpoint and handles the interaction.
/// </summary>
public class MobileClient : IDisposable, IEnableLogger
{
private readonly Subject<Unit> disconnected;
private readonly CompositeDisposable disposable;
private readonly TcpClient fileSocket;
private readonly SemaphoreSlim gate;
private readonly Library library;
private readonly Dictionary<RequestAction, Func<JToken, Task<ResponseInfo>>> messageActionMap;
private readonly TcpClient socket;
private readonly Subject<Unit> videoPlayerToggleRequest;
private Guid accessToken;
private IReadOnlyList<SoundCloudSong> lastSoundCloudRequest;
private IReadOnlyList<YoutubeSong> lastYoutubeRequest;
private IObservable<SongTransferMessage> songTransfers;
public MobileClient(TcpClient socket, TcpClient fileSocket, Library library)
{
if (socket == null)
Throw.ArgumentNullException(() => socket);
if (fileSocket == null)
Throw.ArgumentNullException(() => socket);
if (library == null)
Throw.ArgumentNullException(() => library);
this.socket = socket;
this.fileSocket = fileSocket;
this.library = library;
this.disposable = new CompositeDisposable();
this.gate = new SemaphoreSlim(1, 1);
this.disconnected = new Subject<Unit>();
this.lastSoundCloudRequest = new List<SoundCloudSong>();
this.lastYoutubeRequest = new List<YoutubeSong>();
this.videoPlayerToggleRequest = new Subject<Unit>();
this.messageActionMap = new Dictionary<RequestAction, Func<JToken, Task<ResponseInfo>>>
{
{RequestAction.GetConnectionInfo, this.GetConnectionInfo},
{RequestAction.ToggleYoutubePlayer, this.ToggleVideoPlayer},
{RequestAction.GetLibraryContent, this.GetLibraryContent},
{RequestAction.GetSoundCloudSongs, this.GetSoundCloudSongs},
{RequestAction.GetYoutubeSongs, this.GetYoutubeSongs},
{RequestAction.AddPlaylistSongs, this.AddPlaylistSongs},
{RequestAction.AddPlaylistSongsNow, this.AddPlaylistSongsNow},
{RequestAction.GetCurrentPlaylist, this.GetCurrentPlaylist},
{RequestAction.PlayPlaylistSong, this.PlayPlaylistSong},
{RequestAction.ContinueSong, this.ContinueSong},
{RequestAction.PauseSong, this.PauseSong},
{RequestAction.PlayNextSong, this.PlayNextSong},
{RequestAction.PlayPreviousSong, this.PlayPreviousSong},
{RequestAction.RemovePlaylistSong, this.PostRemovePlaylistSong},
{RequestAction.MovePlaylistSongUp, this.MovePlaylistSongUp},
{RequestAction.MovePlaylistSongDown, this.MovePlaylistSongDown},
{RequestAction.GetVolume, this.GetVolume},
{RequestAction.SetVolume, this.SetVolume},
{RequestAction.VoteForSong, this.VoteForSong},
{RequestAction.QueueRemoteSong, this.QueueRemoteSong},
{RequestAction.SetCurrentTime, this.SetCurrentTime}
};
}
public IObservable<Unit> Disconnected
{
get { return this.disconnected.AsObservable(); }
}
/// <summary>
/// Signals when the mobile client wants to toggle the visibility of the video player.
/// </summary>
public IObservable<Unit> VideoPlayerToggleRequest
{
get { return this.videoPlayerToggleRequest.AsObservable(); }
}
public void Dispose()
{
this.socket.Close();
this.gate.Dispose();
this.disposable.Dispose();
}
public void ListenAsync()
{
Observable.FromAsync(() => this.socket.GetStream().ReadNextMessageAsync())
.Repeat()
.LoggedCatch(this, null, "Message connection was closed by the remote device or the connection failed")
.TakeWhile(x => x != null)
// If we don't do this, the application will throw up whenever we are manipulating a
// collection that is surfaced to the UI Yes, this is astoundingly stupid
.ObserveOn(RxApp.MainThreadScheduler)
.SelectMany(async message =>
{
RequestInfo request;
try
{
request = message.Payload.ToObject<RequestInfo>();
}
catch (JsonException ex)
{
this.Log().ErrorException(String.Format("Mobile client with access token {0} sent a malformed request", this.accessToken), ex);
return Unit.Default;
}
var responseMessage = new NetworkMessage { MessageType = NetworkMessageType.Response };
Func<JToken, Task<ResponseInfo>> action;
if (this.messageActionMap.TryGetValue(request.RequestAction, out action))
{
bool isFatalRequest = false;
try
{
ResponseInfo response = await action(request.Parameters);
response.RequestId = request.RequestId;
responseMessage.Payload = await Task.Run(() => JObject.FromObject(response));
await this.SendMessage(responseMessage);
}
catch (Exception ex)
{
this.Log().ErrorException(String.Format("Mobile client with access token {0} sent a request that caused an exception", this.accessToken), ex);
if (Debugger.IsAttached)
{
Debugger.Break();
}
isFatalRequest = true;
}
if (isFatalRequest)
{
ResponseInfo response = CreateResponse(ResponseStatus.Fatal);
response.RequestId = request.RequestId;
responseMessage.Payload = JObject.FromObject(response);
// Client what are you doing? Client stahp!
await this.SendMessage(responseMessage);
}
return Unit.Default;
}
return Unit.Default;
})
.Finally(() => this.disconnected.OnNext(Unit.Default))
.Subscribe()
.DisposeWith(this.disposable);
var transfers = Observable.FromAsync(() => this.fileSocket.GetStream().ReadNextFileTransferMessageAsync())
.Repeat()
.LoggedCatch(this, null, "File transfer connection was closed by the remote device or the connection failed")
.TakeWhile(x => x != null)
.Publish();
transfers.Connect().DisposeWith(this.disposable);
this.songTransfers = transfers;
}
private static NetworkMessage CreatePushMessage(PushAction action, JObject content)
{
var message = new NetworkMessage
{
MessageType = NetworkMessageType.Push,
Payload = JObject.FromObject(new PushInfo
{
Content = content,
PushAction = action
})
};
return message;
}
private static ResponseInfo CreateResponse(ResponseStatus status, JObject content = null)
{
return CreateResponse(status, null, content);
}
private static ResponseInfo CreateResponse(ResponseStatus status, string message, JObject content = null)
{
return new ResponseInfo
{
Status = status,
Message = message,
Content = content,
};
}
private async Task<ResponseInfo> AddPlaylistSongs(JToken parameters)
{
IEnumerable<Song> songs;
ResponseInfo response;
bool areValid = this.TryValidateSongGuids(parameters["guids"].Select(x => x.ToString()), out songs, out response);
if (areValid)
{
AccessPermission permission = await this.library.RemoteAccessControl.ObserveAccessPermission(this.accessToken).FirstAsync();
if (permission == AccessPermission.Guest)
{
int? remainingVotes = await this.library.RemoteAccessControl.ObserveRemainingVotes(this.accessToken).FirstAsync();
if (remainingVotes == null)
{
return CreateResponse(ResponseStatus.NotSupported, "Voting isn't supported");
}
if (remainingVotes == 0)
{
return CreateResponse(ResponseStatus.Rejected, "Not enough votes left");
}
}
if (permission == AccessPermission.Admin)
{
this.library.AddSongsToPlaylist(songs, this.accessToken);
}
else
{
if (songs.Count() > 1)
{
return CreateResponse(ResponseStatus.Unauthorized, "Guests can't add more than one song");
}
this.library.AddGuestSongToPlaylist(songs.First(), this.accessToken);
}
return CreateResponse(ResponseStatus.Success);
}
return response;
}
private async Task<ResponseInfo> AddPlaylistSongsNow(JToken parameters)
{
IEnumerable<Song> songs;
ResponseInfo response;
bool areValid = this.TryValidateSongGuids(parameters["guids"].Select(x => x.ToString()), out songs, out response);
if (areValid)
{
try
{
await this.library.PlayInstantlyAsync(songs, this.accessToken);
}
catch (AccessException)
{
return CreateResponse(ResponseStatus.Unauthorized);
}
return CreateResponse(ResponseStatus.Success);
}
return response;
}
private async Task<ResponseInfo> ContinueSong(JToken content)
{
try
{
await this.library.ContinueSongAsync(this.accessToken);
}
catch (AccessException)
{
return CreateResponse(ResponseStatus.Unauthorized);
}
return CreateResponse(ResponseStatus.Success);
}
private async Task<ResponseInfo> GetConnectionInfo(JToken parameters)
{
Guid deviceId = Guid.Parse(parameters["deviceId"].ToString());
this.accessToken = this.library.RemoteAccessControl.RegisterRemoteAccessToken(deviceId);
this.Log().Info("Registering new mobile client with access token {0}", this.accessToken);
if (this.library.RemoteAccessControl.IsRemoteAccessReallyLocked)
{
var password = parameters["password"].Value<string>();
if (password != null)
{
try
{
this.library.RemoteAccessControl.UpgradeRemoteAccess(this.accessToken, password);
}
catch (WrongPasswordException)
{
return CreateResponse(ResponseStatus.WrongPassword);
}
}
}
AccessPermission accessPermission = await this.library.RemoteAccessControl.ObserveAccessPermission(this.accessToken).FirstAsync();
// This is stupid
NetworkAccessPermission permission = accessPermission == AccessPermission.Admin ? NetworkAccessPermission.Admin : NetworkAccessPermission.Guest;
int? remainingVotes = await this.library.RemoteAccessControl.ObserveRemainingVotes(this.accessToken).FirstAsync();
var guestSystemInfo = new GuestSystemInfo
{
IsEnabled = remainingVotes.HasValue,
};
if (remainingVotes.HasValue)
{
guestSystemInfo.RemainingVotes = remainingVotes.Value;
}
var connectionInfo = new ConnectionInfo
{
AccessPermission = permission,
ServerVersion = AppInfo.Version,
GuestSystemInfo = guestSystemInfo
};
this.SetupPushNotifications();
return CreateResponse(ResponseStatus.Success, null, JObject.FromObject(connectionInfo));
}
private async Task<ResponseInfo> GetCurrentPlaylist(JToken dontCare)
{
Playlist playlist = this.library.CurrentPlaylist;
AudioPlayerState playbackState = await this.library.PlaybackState.FirstAsync();
TimeSpan currentTime = await this.library.CurrentPlaybackTime.FirstAsync();
TimeSpan totalTime = await this.library.TotalTime.FirstAsync();
JObject content = MobileHelper.SerializePlaylist(playlist, playbackState, currentTime, totalTime);
return CreateResponse(ResponseStatus.Success, null, content);
}
private async Task<ResponseInfo> GetLibraryContent(JToken dontCare)
{
JObject content = await Task.Run(() => MobileHelper.SerializeSongs(this.library.Songs));
return CreateResponse(ResponseStatus.Success, null, content);
}
private async Task<ResponseInfo> GetSoundCloudSongs(JToken parameters)
{
var searchTerm = parameters["searchTerm"].ToObject<string>();
try
{
var requestCache = Locator.Current.GetService<IBlobCache>(BlobCacheKeys.RequestCacheContract);
var songFinder = new SoundCloudSongFinder(requestCache);
IReadOnlyList<SoundCloudSong> songs = await songFinder.GetSongsAsync(searchTerm);
// Cache the latest SoundCloud search request, so we can find the songs by GUID when
// we add one to the playlist later
this.lastSoundCloudRequest = songs;
JObject content = MobileHelper.SerializeSongs(songs);
return CreateResponse(ResponseStatus.Success, content);
}
catch (NetworkSongFinderException)
{
return CreateResponse(ResponseStatus.Failed, "Couldn't retrieve any SoundCloud songs");
}
}
private Task<ResponseInfo> GetVolume(JToken dontCare)
{
float volume = this.library.Volume;
var response = JObject.FromObject(new
{
volume
});
return Task.FromResult(CreateResponse(ResponseStatus.Success, response));
}
private async Task<ResponseInfo> GetYoutubeSongs(JToken parameters)
{
var searchTerm = parameters["searchTerm"].ToObject<string>();
try
{
var requestCache = Locator.Current.GetService<IBlobCache>(BlobCacheKeys.RequestCacheContract);
var songFinder = new YoutubeSongFinder(requestCache);
IReadOnlyList<YoutubeSong> songs = await songFinder.GetSongsAsync(searchTerm);
// Cache the latest YouTube search request, so we can find the songs by GUID when we
// add one to the playlist later
this.lastYoutubeRequest = songs;
JObject content = MobileHelper.SerializeSongs(songs);
return CreateResponse(ResponseStatus.Success, content);
}
catch (NetworkSongFinderException)
{
return CreateResponse(ResponseStatus.Failed, "Couldn't retrieve any YouTube songs");
};
}
private Task<ResponseInfo> MovePlaylistSongDown(JToken parameters)
{
Guid songGuid;
bool valid = Guid.TryParse(parameters["entryGuid"].ToString(), out songGuid);
if (!valid)
{
return Task.FromResult(CreateResponse(ResponseStatus.MalformedRequest, "Malformed GUID"));
}
PlaylistEntry entry = this.library.CurrentPlaylist.FirstOrDefault(x => x.Guid == songGuid);
if (entry == null)
{
return Task.FromResult(CreateResponse(ResponseStatus.NotFound, "Playlist entry not found"));
}
try
{
this.library.MovePlaylistSong(entry.Index, entry.Index + 1, this.accessToken);
}
catch (AccessException)
{
return Task.FromResult(CreateResponse(ResponseStatus.Unauthorized));
}
return Task.FromResult(CreateResponse(ResponseStatus.Success));
}
private Task<ResponseInfo> MovePlaylistSongUp(JToken parameters)
{
Guid songGuid;
bool valid = Guid.TryParse(parameters["entryGuid"].ToString(), out songGuid);
if (!valid)
{
return Task.FromResult(CreateResponse(ResponseStatus.MalformedRequest, "Malformed GUID"));
}
PlaylistEntry entry = this.library.CurrentPlaylist.FirstOrDefault(x => x.Guid == songGuid);
if (entry == null)
{
return Task.FromResult(CreateResponse(ResponseStatus.NotFound));
}
try
{
this.library.MovePlaylistSong(entry.Index, entry.Index - 1, this.accessToken);
}
catch (AccessException)
{
return Task.FromResult(CreateResponse(ResponseStatus.Unauthorized));
}
return Task.FromResult(CreateResponse(ResponseStatus.Success));
}
private async Task<ResponseInfo> PauseSong(JToken dontCare)
{
try
{
await this.library.PauseSongAsync(this.accessToken);
}
catch (AccessException)
{
return CreateResponse(ResponseStatus.Unauthorized);
}
return CreateResponse(ResponseStatus.Success);
}
private async Task<ResponseInfo> PlayNextSong(JToken dontCare)
{
try
{
await this.library.PlayNextSongAsync(this.accessToken);
}
catch (AccessException)
{
return CreateResponse(ResponseStatus.Unauthorized);
}
return CreateResponse(ResponseStatus.Success);
}
private async Task<ResponseInfo> PlayPlaylistSong(JToken parameters)
{
Guid songGuid;
bool valid = Guid.TryParse(parameters["entryGuid"].ToString(), out songGuid);
if (!valid)
{
return CreateResponse(ResponseStatus.MalformedRequest, "Malformed GUID");
}
PlaylistEntry entry = this.library.CurrentPlaylist.FirstOrDefault(x => x.Guid == songGuid);
if (entry == null)
{
return CreateResponse(ResponseStatus.NotFound, "Playlist entry not found");
}
try
{
await this.library.PlaySongAsync(entry.Index, this.accessToken);
}
catch (AccessException)
{
return CreateResponse(ResponseStatus.Unauthorized);
}
return CreateResponse(ResponseStatus.Success);
}
private async Task<ResponseInfo> PlayPreviousSong(JToken dontCare)
{
try
{
await this.library.PlayPreviousSongAsync(this.accessToken);
}
catch (AccessException)
{
return CreateResponse(ResponseStatus.Unauthorized);
}
return CreateResponse(ResponseStatus.Success);
}
private Task<ResponseInfo> PostRemovePlaylistSong(JToken parameters)
{
Guid songGuid = Guid.Parse(parameters["entryGuid"].ToString());
PlaylistEntry entry = this.library.CurrentPlaylist.FirstOrDefault(x => x.Guid == songGuid);
if (entry == null)
{
return Task.FromResult(CreateResponse(ResponseStatus.NotFound, "Guid not found"));
}
this.library.RemoveFromPlaylist(new[] { entry.Index }, this.accessToken);
return Task.FromResult(CreateResponse(ResponseStatus.Success));
}
private async Task PushAccessPermission(AccessPermission accessPermission)
{
var content = JObject.FromObject(new
{
accessPermission
});
NetworkMessage message = CreatePushMessage(PushAction.UpdateAccessPermission, content);
await this.SendMessage(message);
}
private Task PushCurrentPlaybackTime(TimeSpan currentPlaybackTime)
{
var content = JObject.FromObject(new
{
currentPlaybackTime
});
NetworkMessage message = CreatePushMessage(PushAction.UpdateCurrentPlaybackTime, content);
return this.SendMessage(message);
}
private Task PushGuestSystemInfo(int? remainingVotes)
{
var guestSystemInfo = new GuestSystemInfo
{
IsEnabled = remainingVotes.HasValue,
};
if (remainingVotes.HasValue)
{
guestSystemInfo.RemainingVotes = remainingVotes.Value;
}
NetworkMessage message = CreatePushMessage(PushAction.UpdateGuestSystemInfo, JObject.FromObject(guestSystemInfo));
return this.SendMessage(message);
}
private async Task PushPlaybackState(AudioPlayerState state)
{
var content = JObject.FromObject(new
{
state
});
NetworkMessage message = CreatePushMessage(PushAction.UpdatePlaybackState, content);
await this.SendMessage(message);
}
private async Task PushPlaylist(Playlist playlist, AudioPlayerState state)
{
JObject content = MobileHelper.SerializePlaylist(playlist, state,
await this.library.CurrentPlaybackTime.FirstAsync(),
await this.library.TotalTime.FirstAsync());
NetworkMessage message = CreatePushMessage(PushAction.UpdateCurrentPlaylist, content);
await this.SendMessage(message);
}
private async Task<ResponseInfo> QueueRemoteSong(JToken parameters)
{
AccessPermission permission = await this.library.RemoteAccessControl.ObserveAccessPermission(this.accessToken).FirstAsync();
if (permission == AccessPermission.Guest)
{
int? remainingVotes = await this.library.RemoteAccessControl.ObserveRemainingVotes(this.accessToken).FirstAsync();
if (remainingVotes == null)
{
return CreateResponse(ResponseStatus.NotSupported, "Voting isn't supported");
}
if (remainingVotes == 0)
{
return CreateResponse(ResponseStatus.Rejected, "Not enough votes left");
}
}
var transferInfo = parameters.ToObject<SongTransferInfo>();
IObservable<byte[]> data = this.songTransfers.FirstAsync(x => x.TransferId == transferInfo.TransferId).Select(x => x.Data);
var song = MobileSong.Create(transferInfo.Metadata, data);
if (permission == AccessPermission.Guest)
{
this.library.AddGuestSongToPlaylist(song, this.accessToken);
}
else
{
this.library.AddSongsToPlaylist(new[] { song }, this.accessToken);
}
return CreateResponse(ResponseStatus.Success);
}
private async Task SendMessage(NetworkMessage content)
{
byte[] message;
using (MeasureHelper.Measure())
{
message = await NetworkHelpers.PackMessageAsync(content);
}
await this.gate.WaitAsync();
try
{
await this.socket.GetStream().WriteAsync(message, 0, message.Length);
}
catch (Exception)
{
this.disconnected.OnNext(Unit.Default);
}
finally
{
this.gate.Release();
}
}
private Task<ResponseInfo> SetCurrentTime(JToken parameters)
{
var time = parameters["time"].ToObject<TimeSpan>();
try
{
this.library.SetCurrentTime(time, this.accessToken);
}
catch (AccessException)
{
return Task.FromResult(CreateResponse(ResponseStatus.Unauthorized));
}
return Task.FromResult(CreateResponse(ResponseStatus.Success));
}
private void SetupPushNotifications()
{
this.library.WhenAnyValue(x => x.CurrentPlaylist).Skip(1)
.Merge(this.library.WhenAnyValue(x => x.CurrentPlaylist)
.Select(x => x.Changed().Select(y => x))
.Switch())
.Merge(this.library.WhenAnyValue(x => x.CurrentPlaylist)
.Select(x => x.WhenAnyValue(y => y.CurrentSongIndex).Skip(1).Select(y => x))
.Switch())
.CombineLatest(this.library.PlaybackState, Tuple.Create)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(x => this.PushPlaylist(x.Item1, x.Item2))
.DisposeWith(this.disposable);
this.library.PlaybackState.Skip(1)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(x => this.PushPlaybackState(x))
.DisposeWith(this.disposable);
this.library.RemoteAccessControl.ObserveAccessPermission(this.accessToken)
.Skip(1)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(x => this.PushAccessPermission(x))
.DisposeWith(this.disposable);
this.library.RemoteAccessControl.ObserveRemainingVotes(this.accessToken)
.Skip(1)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(x => this.PushGuestSystemInfo(x))
.DisposeWith(this.disposable);
TimeSpan lastTime = TimeSpan.Zero;
// We can assume that, if the total time difference exceeds two seconds, the time change
// is from an external source (e.g the user clicked on the time slider)
this.library.CurrentPlaybackTime
.Select(x => Math.Abs(lastTime.TotalSeconds - x.TotalSeconds) >= 2 ? Tuple.Create(x, true) : Tuple.Create(x, false))
.Do(x => lastTime = x.Item1)
.Where(x => x.Item2)
.Select(x => x.Item1)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(x => this.PushCurrentPlaybackTime(x))
.DisposeWith(this.disposable);
}
private Task<ResponseInfo> SetVolume(JToken parameters)
{
var volume = parameters["volume"].ToObject<float>();
if (volume < 0 || volume > 1.0)
return Task.FromResult(CreateResponse(ResponseStatus.MalformedRequest, "Volume must be between 0 and 1"));
try
{
this.library.SetVolume(volume, this.accessToken);
}
catch (AccessException)
{
return Task.FromResult(CreateResponse(ResponseStatus.Unauthorized));
}
return Task.FromResult(CreateResponse(ResponseStatus.Success));
}
private Task<ResponseInfo> ToggleVideoPlayer(JToken arg)
{
this.videoPlayerToggleRequest.OnNext(Unit.Default);
return Task.FromResult(CreateResponse(ResponseStatus.Success));
}
private bool TryValidateSongGuids(IEnumerable<string> guidStrings, out IEnumerable<Song> foundSongs, out ResponseInfo responseInfo)
{
var guids = new List<Guid>();
foreach (string guidString in guidStrings)
{
Guid guid;
bool valid = Guid.TryParse(guidString, out guid);
if (valid)
{
guids.Add(guid);
}
else
{
responseInfo = CreateResponse(ResponseStatus.MalformedRequest, "One or more GUIDs are malformed");
foundSongs = null;
return false;
}
}
// Look if any song in our local library or any song of the last SoundCloud or YouTube
// requests has the requested Guid
Dictionary<Guid, Song> dic = this.library.Songs
.Concat(this.lastSoundCloudRequest.Cast<Song>())
.Concat(this.lastYoutubeRequest)
.ToDictionary(x => x.Guid);
List<Song> songs = guids.Select(x =>
{
Song song;
dic.TryGetValue(x, out song);
return song;
})
.Where(x => x != null)
.ToList();
if (guids.Count != songs.Count)
{
responseInfo = CreateResponse(ResponseStatus.NotFound, "One or more songs could not be found");
foundSongs = null;
return false;
}
responseInfo = null;
foundSongs = songs;
return true;
}
private async Task<ResponseInfo> VoteForSong(JToken parameters)
{
int? remainingVotes = await this.library.RemoteAccessControl.ObserveRemainingVotes(this.accessToken).FirstAsync();
if (remainingVotes == null)
{
return CreateResponse(ResponseStatus.NotSupported, "Voting isn't supported");
}
if (remainingVotes == 0)
{
return CreateResponse(ResponseStatus.Rejected, "Not enough votes left");
}
Guid songGuid;
bool valid = Guid.TryParse(parameters["entryGuid"].ToString(), out songGuid);
if (!valid)
{
return CreateResponse(ResponseStatus.MalformedRequest, "Malformed GUID");
}
Playlist playlist = this.library.CurrentPlaylist;
PlaylistEntry entry = playlist.FirstOrDefault(x => x.Guid == songGuid);
if (entry == null)
{
return CreateResponse(ResponseStatus.NotFound, "Playlist entry not found");
}
if (this.library.RemoteAccessControl.IsVoteRegistered(this.accessToken, entry))
{
return CreateResponse(ResponseStatus.Rejected, "Vote already registered");
}
if (playlist.CurrentSongIndex.HasValue && entry.Index <= playlist.CurrentSongIndex.Value)
{
return CreateResponse(ResponseStatus.Rejected, "Vote rejected");
}
try
{
this.library.VoteForPlaylistEntry(entry.Index, this.accessToken);
}
catch (AccessException)
{
return CreateResponse(ResponseStatus.Unauthorized, "Unauthorized");
}
return CreateResponse(ResponseStatus.Success);
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Site
///<para>SObject Name: SiteFeed</para>
///<para>Custom Object: False</para>
///</summary>
public class SfSiteFeed : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "SiteFeed"; }
}
///<summary>
/// Feed Item ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(false)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: Site
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfSite Parent { get; set; }
///<summary>
/// Feed Item Type
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Comment Count
/// <para>Name: CommentCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "commentCount")]
[Updateable(false), Createable(false)]
public int? CommentCount { get; set; }
///<summary>
/// Like Count
/// <para>Name: LikeCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "likeCount")]
[Updateable(false), Createable(false)]
public int? LikeCount { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "title")]
[Updateable(false), Createable(false)]
public string Title { get; set; }
///<summary>
/// Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
[Updateable(false), Createable(false)]
public string Body { get; set; }
///<summary>
/// Link Url
/// <para>Name: LinkUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "linkUrl")]
[Updateable(false), Createable(false)]
public string LinkUrl { get; set; }
///<summary>
/// Is Rich Text
/// <para>Name: IsRichText</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRichText")]
[Updateable(false), Createable(false)]
public bool? IsRichText { get; set; }
///<summary>
/// Related Record ID
/// <para>Name: RelatedRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedRecordId")]
[Updateable(false), Createable(false)]
public string RelatedRecordId { get; set; }
///<summary>
/// InsertedBy ID
/// <para>Name: InsertedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "insertedById")]
[Updateable(false), Createable(false)]
public string InsertedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: InsertedBy</para>
///</summary>
[JsonProperty(PropertyName = "insertedBy")]
[Updateable(false), Createable(false)]
public SfUser InsertedBy { get; set; }
///<summary>
/// Best Comment ID
/// <para>Name: BestCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestCommentId")]
[Updateable(false), Createable(false)]
public string BestCommentId { get; set; }
///<summary>
/// ReferenceTo: FeedComment
/// <para>RelationshipName: BestComment</para>
///</summary>
[JsonProperty(PropertyName = "bestComment")]
[Updateable(false), Createable(false)]
public SfFeedComment BestComment { get; set; }
}
}
| |
// 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 Microsoft.CodeAnalysis.CodeGeneration;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource
{
public partial class MetadataAsSourceTests : AbstractMetadataAsSourceTests
{
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestClass()
{
var metadataSource = "public class C {}";
var symbolName = "C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class [|C|]
{{
public C();
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class [|C|]
Public Sub New()
End Class");
}
[WorkItem(546241)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestInterface()
{
var metadataSource = "public interface I {}";
var symbolName = "I";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public interface [|I|]
{{
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Interface [|I|]
End Interface");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestConstructor()
{
var metadataSource = "public class C {}";
var symbolName = "C..ctor";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public [|C|]();
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Sub [|New|]()
End Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestMethod()
{
var metadataSource = "public class C { public void Foo() {} }";
var symbolName = "C.Foo";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public C();
public void [|Foo|]();
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Sub New()
Public Sub [|Foo|]()
End Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestField()
{
var metadataSource = "public class C { public string S; }";
var symbolName = "C.S";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public string [|S|];
public C();
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public [|S|] As String
Public Sub New()
End Class");
}
[WorkItem(546240)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestProperty()
{
var metadataSource = "public class C { public string S { get; protected set; } }";
var symbolName = "C.S";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public C();
public string [|S|] {{ get; protected set; }}
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Sub New()
Public Property [|S|] As String
End Class");
}
[WorkItem(546194)]
[WorkItem(546291)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestEvent()
{
var metadataSource = "using System; public class C { public event Action E; }";
var symbolName = "C.E";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System;
public class C
{{
public C();
public event Action [|E|];
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
Public Class C
Public Sub New()
Public Event [|E|] As Action
End Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestNestedType()
{
var metadataSource = "public class C { protected class D { } }";
var symbolName = "C+D";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public C();
protected class [|D|]
{{
public D();
}}
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Sub New()
Protected Class [|D|]
Public Sub New()
End Class
End Class");
}
[WorkItem(546195), WorkItem(546269)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestEnum()
{
var metadataSource = "public enum E { A, B, C }";
var symbolName = "E.C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public enum E
{{
A,
B,
[|C|]
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Enum E
A
B
[|C|]
End Enum");
}
[WorkItem(546273)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestEnumWithUnderlyingType()
{
var metadataSource = "public enum E : short { A = 0, B = 1, C = 2 }";
var symbolName = "E.C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public enum E : short
{{
A,
B,
[|C|]
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Enum E As Short
A
B
[|C|]
End Enum");
}
[WorkItem(650741)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestEnumWithOverflowingUnderlyingType()
{
var metadataSource = "public enum E : ulong { A = 9223372036854775808 }";
var symbolName = "E.A";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public enum E : ulong
{{
[|A|] = 9223372036854775808
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Enum E As ULong
[|A|] = 9223372036854775808UL
End Enum");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestEnumWithDifferentValues()
{
var metadataSource = "public enum E : short { A = 1, B = 2, C = 3 }";
var symbolName = "E.C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public enum E : short
{{
A = 1,
B = 2,
[|C|] = 3
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Enum E As Short
A = 1
B = 2
[|C|] = 3
End Enum");
}
[WorkItem(546198)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestTypeInNamespace()
{
var metadataSource = "namespace N { public class C {} }";
var symbolName = "N.C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
namespace N
{{
public class [|C|]
{{
public C();
}}
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Namespace N
Public Class [|C|]
Public Sub New()
End Class
End Namespace");
}
[WorkItem(546223)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestInlineConstant()
{
var metadataSource = @"public class C { public const string S = ""Hello mas""; }";
var symbolName = "C.S";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public const string [|S|] = ""Hello mas"";
public C();
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Const [|S|] As String = ""Hello mas""
Public Sub New()
End Class");
}
[WorkItem(546221)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestInlineTypeOf()
{
var metadataSource = @"
using System;
public class MyTypeAttribute : Attribute
{
public MyTypeAttribute(Type type) {}
}
[MyType(typeof(string))]
public class C {}";
var symbolName = "C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
[MyType(typeof(string))]
public class [|C|]
{{
public C();
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
<MyType(GetType(String))>
Public Class [|C|]
Public Sub New()
End Class");
}
[WorkItem(546231)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestNoDefaultConstructorInStructs()
{
var metadataSource = "public struct S {}";
var symbolName = "S";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public struct [|S|]
{{
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Structure [|S|]
End Structure");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestReferenceDefinedType()
{
var metadataSource = "public class C { public static C Create() { return new C(); } }";
var symbolName = "C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class [|C|]
{{
public C();
public static C Create();
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class [|C|]
Public Sub New()
Public Shared Function Create() As C
End Class");
}
[WorkItem(546227)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestGenericType()
{
var metadataSource = "public class G<SomeType> { public SomeType S; }";
var symbolName = "G`1";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class [|G|]<SomeType>
{{
public SomeType S;
public G();
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class [|G|](Of SomeType)
Public S As SomeType
Public Sub New()
End Class");
}
[WorkItem(546227)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestGenericDelegate()
{
var metadataSource = "public class C { public delegate void D<SomeType>(SomeType s); }";
var symbolName = "C+D`1";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public C();
public delegate void [|D|]<SomeType>(SomeType s);
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Sub New()
Public Delegate Sub [|D|](Of SomeType)(s As SomeType)
End Class");
}
[WorkItem(546200)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestAttribute()
{
var metadataSource = @"
using System;
namespace N
{
public class WorkingAttribute : Attribute
{
public WorkingAttribute(bool working) {}
}
}
[N.Working(true)]
public class C {}";
var symbolName = "C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using N;
[Working(true)]
public class [|C|]
{{
public C();
}}");
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports N
<Working(True)>
Public Class [|C|]
Public Sub New()
End Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestSymbolIdMatchesMetadata()
{
TestSymbolIdMatchesMetadata(LanguageNames.CSharp);
TestSymbolIdMatchesMetadata(LanguageNames.VisualBasic);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestNotReusedOnAssemblyDiffers()
{
TestNotReusedOnAssemblyDiffers(LanguageNames.CSharp);
TestNotReusedOnAssemblyDiffers(LanguageNames.VisualBasic);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestThrowsOnGenerateNamespace()
{
var namespaceSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol("Outerspace");
using (var context = new TestContext())
{
Assert.Throws<ArgumentException>(() =>
{
try
{
context.GenerateSource(namespaceSymbol);
}
catch (AggregateException ae)
{
throw ae.InnerException;
}
});
}
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestReuseGenerateMemberOfGeneratedType()
{
var metadataSource = "public class C { public bool Is; }";
using (var context = new TestContext(LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource)))
{
var a = context.GenerateSource("C");
var b = context.GenerateSource("C.Is");
context.VerifyDocumentReused(a, b);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestReuseRepeatGeneration()
{
using (var context = new TestContext())
{
var a = context.GenerateSource();
var b = context.GenerateSource();
context.VerifyDocumentReused(a, b);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestReuseGenerateFromDifferentProject()
{
using (var context = new TestContext())
{
var projectId = ProjectId.CreateNewId();
var project = context.CurrentSolution.AddProject(projectId, "ProjectB", "ProjectB", LanguageNames.CSharp).GetProject(projectId)
.WithMetadataReferences(context.DefaultProject.MetadataReferences)
.WithCompilationOptions(new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var a = context.GenerateSource(project: context.DefaultProject);
var b = context.GenerateSource(project: project);
context.VerifyDocumentReused(a, b);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestNotReusedGeneratingForDifferentLanguage()
{
using (var context = new TestContext(LanguageNames.CSharp))
{
var projectId = ProjectId.CreateNewId();
var project = context.CurrentSolution.AddProject(projectId, "ProjectB", "ProjectB", LanguageNames.VisualBasic).GetProject(projectId)
.WithMetadataReferences(context.DefaultProject.MetadataReferences)
.WithCompilationOptions(new VB.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var a = context.GenerateSource(project: context.DefaultProject);
var b = context.GenerateSource(project: project);
context.VerifyDocumentNotReused(a, b);
}
}
[WorkItem(546311)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void FormatMetadataAsSource()
{
using (var context = new TestContext(LanguageNames.CSharp))
{
var file = context.GenerateSource("System.Console", project: context.DefaultProject);
var document = context.GetDocument(file);
Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(document).Wait();
}
}
[WorkItem(530829)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void IndexedProperty()
{
var metadataSource = @"
Public Class C
Public Property IndexProp(ByVal p1 As Integer) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
var expected = $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public C();
public string [|get_IndexProp|](int p1);
public void set_IndexProp(int p1, string value);
}}";
var symbolName = "C.get_IndexProp";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, expected);
}
[WorkItem(566688)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void AttributeReferencingInternalNestedType()
{
var metadataSource = @"using System;
[My(typeof(D))]
public class C
{
public C() { }
internal class D { }
}
public class MyAttribute : Attribute
{
public MyAttribute(Type t) { }
}";
var expected = $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
[My(typeof(D))]
public class [|C|]
{{
public C();
}}";
var symbolName = "C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, expected);
}
[WorkItem(530978)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestAttributesOnMembers()
{
var metadataSource = @"using System;
[Obsolete]
public class C
{
[Obsolete]
[ThreadStatic]
public int field1;
[Obsolete]
public int prop1 { get; set; }
[Obsolete]
public int prop2 { get { return 10; } set {} }
[Obsolete]
public void method1() {}
[Obsolete]
public C() {}
[Obsolete]
~C() {}
[Obsolete]
public int this[int x] { get { return 10; } set {} }
[Obsolete]
public event Action event1;
[Obsolete]
public event Action event2 { add {} remove {}}
public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = """") {}
[Obsolete]
public static C operator + (C c1, C c2) { return new C(); }
}
";
var expectedCS = $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
[DefaultMember(""Item"")]
[Obsolete]
public class [|C|]
{{
[Obsolete]
[ThreadStatic]
public int field1;
[Obsolete]
public C();
[Obsolete]
~C();
[Obsolete]
public int this[int x] {{ get; set; }}
[Obsolete]
public int prop1 {{ get; set; }}
[Obsolete]
public int prop2 {{ get; set; }}
[Obsolete]
public event Action event1;
[Obsolete]
public event Action event2;
[Obsolete]
public void method1();
public void method2([CallerMemberName]string name = """");
[Obsolete]
public static C operator +(C c1, C c2);
}}
";
var symbolName = "C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, expectedCS);
var expectedVB = $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
<DefaultMember(""Item"")>
<Obsolete>
Public Class [|C|]
<Obsolete>
<ThreadStatic>
Public field1 As Integer
<Obsolete>
Public Sub New()
<Obsolete>
Default Public Property Item(x As Integer) As Integer
<Obsolete>
Public Property prop1 As Integer
<Obsolete>
Public Property prop2 As Integer
<Obsolete>
Public Event event1 As Action
<Obsolete>
Public Event event2 As Action
<Obsolete>
Public Sub method1()
Public Sub method2(<CallerMemberName> Optional name As String = """")
<Obsolete>
Protected Overrides Sub Finalize()
<Obsolete>
Public Shared Operator +(c1 As C, c2 As C) As C
End Class
";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, expectedVB);
}
[WorkItem(530923)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestEmptyLineBetweenMembers()
{
var metadataSource = @"using System;
public class C
{
public int field1;
public int prop1 { get; set; }
public int field2;
public int prop2 { get { return 10; } set {} }
public void method1() {}
public C() {}
public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = """") {}
~C() {}
public int this[int x] { get { return 10; } set {} }
public event Action event1;
public static C operator + (C c1, C c2) { return new C(); }
public event Action event2 { add {} remove {}}
public static C operator - (C c1, C c2) { return new C(); }
}
";
var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
[DefaultMember(""Item"")]
public class [|C|]
{{
public int field1;
public int field2;
public C();
~C();
public int this[int x] {{ get; set; }}
public int prop1 {{ get; set; }}
public int prop2 {{ get; set; }}
public event Action event1;
public event Action event2;
public void method1();
public void method2([CallerMemberName]string name = """");
public static C operator +(C c1, C c2);
public static C operator -(C c1, C c2);
}}
";
var symbolName = "C";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, expectedCS, compareTokens: false);
var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
<DefaultMember(""Item"")>
Public Class [|C|]
Public field1 As Integer
Public field2 As Integer
Public Sub New()
Default Public Property Item(x As Integer) As Integer
Public Property prop1 As Integer
Public Property prop2 As Integer
Public Event event1 As Action
Public Event event2 As Action
Public Sub method1()
Public Sub method2(<CallerMemberName> Optional name As String = """")
Protected Overrides Sub Finalize()
Public Shared Operator +(c1 As C, c2 As C) As C
Public Shared Operator -(c1 As C, c2 As C) As C
End Class";
GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, expectedVB, compareTokens: false);
}
[WorkItem(728644)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestEmptyLineBetweenMembers2()
{
var source = @"
using System;
/// <summary>T:IFoo</summary>
public interface IFoo
{
/// <summary>P:IFoo.Prop1</summary>
Uri Prop1 { get; set; }
/// <summary>M:IFoo.Method1</summary>
Uri Method1();
}
";
var symbolName = "IFoo";
var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System;
//
// {FeaturesResources.Summary}
// T:IFoo
public interface [|IFoo|]
{{
//
// {FeaturesResources.Summary}
// P:IFoo.Prop1
Uri Prop1 {{ get; set; }}
//
// {FeaturesResources.Summary}
// M:IFoo.Method1
Uri Method1();
}}
";
GenerateAndVerifySource(source, symbolName, LanguageNames.CSharp, expectedCS, compareTokens: false, includeXmlDocComments: true);
var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
'
' {FeaturesResources.Summary}
' T:IFoo
Public Interface [|IFoo|]
'
' {FeaturesResources.Summary}
' P:IFoo.Prop1
Property Prop1 As Uri
'
' {FeaturesResources.Summary}
' M:IFoo.Method1
Function Method1() As Uri
End Interface
";
GenerateAndVerifySource(source, symbolName, LanguageNames.VisualBasic, expectedVB, compareTokens: false, includeXmlDocComments: true);
}
[WorkItem(679114), WorkItem(715013)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestDefaultValueEnum()
{
var source = @"
using System.IO;
public class Test
{
public void foo(FileOptions options = 0) {}
}
";
var symbolName = "Test";
var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System.IO;
public class [|Test|]
{{
public Test();
public void foo(FileOptions options = FileOptions.None);
}}
";
GenerateAndVerifySource(source, symbolName, LanguageNames.CSharp, expectedCS);
var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System.IO
Public Class [|Test|]
Public Sub New()
Public Sub foo(Optional options As FileOptions = FileOptions.None)
End Class";
GenerateAndVerifySource(source, symbolName, LanguageNames.VisualBasic, expectedVB);
}
[WorkItem(651261)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestNullAttribute()
{
var source = @"
using System;
[Test(null)]
public class TestAttribute : Attribute
{
public TestAttribute(int[] i)
{
}
}";
var symbolName = "TestAttribute";
var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System;
[Test(null)]
public class [|TestAttribute|] : Attribute
{{
public TestAttribute(int[] i);
}}
";
GenerateAndVerifySource(source, symbolName, LanguageNames.CSharp, expectedCS);
var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
<Test(Nothing)>
Public Class [|TestAttribute|]
Inherits Attribute
Public Sub New(i() As Integer)
End Class";
GenerateAndVerifySource(source, symbolName, LanguageNames.VisualBasic, expectedVB);
}
[WorkItem(897006)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestNavigationViaReducedExtensionMethodCS()
{
var metadata = @"using System;
public static class ObjectExtensions
{
public static void M(this object o, int x) { }
}";
var sourceWithSymbolReference = @"
class C
{
void M()
{
new object().[|M|](5);
}
}";
var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public static class ObjectExtensions
{{
public static void [|M|](this object o, int x);
}}
";
using (var context = new TestContext(
LanguageNames.CSharp,
SpecializedCollections.SingletonEnumerable(metadata),
includeXmlDocComments: false,
sourceWithSymbolReference: sourceWithSymbolReference))
{
var navigationSymbol = context.GetNavigationSymbol();
var metadataAsSourceFile = context.GenerateSource(navigationSymbol);
context.VerifyResult(metadataAsSourceFile, expected);
}
}
[WorkItem(897006)]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestNavigationViaReducedExtensionMethodVB()
{
var metadata = @"Imports System.Runtime.CompilerServices
Namespace NS
Public Module StringExtensions
<Extension()>
Public Sub M(ByVal o As String, x As Integer)
End Sub
End Module
End Namespace";
var sourceWithSymbolReference = @"
Imports NS.StringExtensions
Public Module C
Sub M()
Dim s = ""Yay""
s.[|M|](1)
End Sub
End Module";
var expected = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System.Runtime.CompilerServices
Namespace NS
<Extension>
Public Module StringExtensions
<Extension> Public Sub [|M|](o As String, x As Integer)
End Module
End Namespace";
using (var context = new TestContext(
LanguageNames.VisualBasic,
SpecializedCollections.SingletonEnumerable(metadata),
includeXmlDocComments: false,
sourceWithSymbolReference: sourceWithSymbolReference))
{
var navigationSymbol = context.GetNavigationSymbol();
var metadataAsSourceFile = context.GenerateSource(navigationSymbol);
context.VerifyResult(metadataAsSourceFile, expected);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
namespace UnityTest
{
[Serializable]
public class AssertionComponent : MonoBehaviour, IAssertionComponentConfigurator
{
[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 m_CheckOnFrame;
private string m_CreatedInFilePath = "";
private int m_CreatedInFileLine = -1;
public ActionBase Action
{
get { return m_ActionBase; }
set
{
m_ActionBase = value;
m_ActionBase.go = gameObject;
}
}
public Object GetFailureReferenceObject()
{
if (!string.IsNullOrEmpty(m_CreatedInFilePath))
{
return Resources.LoadAssetAtPath(m_CreatedInFilePath, typeof(Object));
}
return this;
}
public string GetCreationLocation()
{
if (!string.IsNullOrEmpty(m_CreatedInFilePath))
{
var idx = m_CreatedInFilePath.LastIndexOf("\\") + 1;
return string.Format("{0}, line {1} ({2})", m_CreatedInFilePath.Substring(idx), m_CreatedInFileLine, m_CreatedInFilePath);
}
return "";
}
public void Awake()
{
if (!Debug.isDebugBuild)
Destroy(this);
OnComponentCopy();
}
public void OnValidate()
{
if (Application.isEditor)
OnComponentCopy();
}
private void OnComponentCopy()
{
if (m_ActionBase == null) return;
var oldActionList = Resources.FindObjectsOfTypeAll(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 (!oldActionList.Any()) return;
if (oldActionList.Count() > 1)
Debug.LogWarning("More than one refence to comparer found. This shouldn't happen");
var oldAction = oldActionList.First() as AssertionComponent;
m_ActionBase = oldAction.m_ActionBase.CreateCopy(oldAction.gameObject, gameObject);
}
public void Start()
{
CheckAssertionFor(CheckMethod.Start);
if (IsCheckMethodSelected(CheckMethod.AfterPeriodOfTime))
{
StartCoroutine("CheckPeriodically");
}
if (IsCheckMethodSelected(CheckMethod.Update))
{
m_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 > m_CheckOnFrame)
{
if (repeatCheckFrame)
m_CheckOnFrame += repeatEveryFrame;
else
m_CheckOnFrame = Int32.MaxValue;
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);
}
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);
}
private void CheckAssertionFor(CheckMethod checkMethod)
{
if (IsCheckMethodSelected(checkMethod))
{
Assertions.CheckAssertions(this);
}
}
public bool IsCheckMethodSelected(CheckMethod method)
{
return method == (checkMethods & method);
}
#region Assertion Component create methods
public static T Create<T>(CheckMethod checkOnMethods, GameObject gameObject, string propertyPath) where T : ActionBase
{
IAssertionComponentConfigurator configurator;
return Create<T>(out configurator, checkOnMethods, gameObject, propertyPath);
}
public static T Create<T>(out IAssertionComponentConfigurator configurator, CheckMethod checkOnMethods, GameObject gameObject, string propertyPath) where T : ActionBase
{
return CreateAssertionComponent<T>(out configurator, checkOnMethods, gameObject, propertyPath);
}
public static T Create<T>(CheckMethod checkOnMethods, GameObject gameObject, string propertyPath, GameObject gameObject2, string propertyPath2) where T : ComparerBase
{
IAssertionComponentConfigurator configurator;
return Create<T>(out configurator, checkOnMethods, gameObject, propertyPath, gameObject2, propertyPath2);
}
public static T Create<T>(out IAssertionComponentConfigurator configurator, CheckMethod checkOnMethods, GameObject gameObject, string propertyPath, GameObject gameObject2, string propertyPath2) where T : ComparerBase
{
var comparer = CreateAssertionComponent<T>(out configurator, checkOnMethods, gameObject, propertyPath);
comparer.compareToType = ComparerBase.CompareToType.CompareToObject;
comparer.other = gameObject2;
comparer.otherPropertyPath = propertyPath2;
return comparer;
}
public static T Create<T>(CheckMethod checkOnMethods, GameObject gameObject, string propertyPath, object constValue) where T : ComparerBase
{
IAssertionComponentConfigurator configurator;
return Create<T>(out configurator, checkOnMethods, gameObject, propertyPath, constValue);
}
public static T Create<T>(out IAssertionComponentConfigurator configurator, CheckMethod checkOnMethods, GameObject gameObject, string propertyPath, object constValue) where T : ComparerBase
{
var comparer = CreateAssertionComponent<T>(out configurator, checkOnMethods, gameObject, propertyPath);
if (constValue == null)
{
comparer.compareToType = ComparerBase.CompareToType.CompareToNull;
return comparer;
}
comparer.compareToType = ComparerBase.CompareToType.CompareToConstantValue;
comparer.ConstValue = constValue;
return comparer;
}
private static T CreateAssertionComponent<T>(out IAssertionComponentConfigurator configurator, CheckMethod checkOnMethods, GameObject gameObject, string propertyPath) where T : ActionBase
{
var ac = gameObject.AddComponent<AssertionComponent>();
ac.checkMethods = checkOnMethods;
var comparer = ScriptableObject.CreateInstance<T>();
ac.Action = comparer;
ac.Action.go = gameObject;
ac.Action.thisPropertyPath = propertyPath;
configurator = ac;
#if !UNITY_METRO
var stackTrace = new StackTrace(true);
var thisFileName = stackTrace.GetFrame(0).GetFileName();
for (int i = 1; i < stackTrace.FrameCount; i++)
{
var stackFrame = stackTrace.GetFrame(i);
if (stackFrame.GetFileName() != thisFileName)
{
string filePath = stackFrame.GetFileName().Substring(Application.dataPath.Length - "Assets".Length);
ac.m_CreatedInFilePath = filePath;
ac.m_CreatedInFileLine = stackFrame.GetFileLineNumber();
break;
}
}
#endif // if !UNITY_METRO
return comparer;
}
#endregion
#region AssertionComponentConfigurator
public int UpdateCheckStartOnFrame { set { checkAfterFrames = value; } }
public int UpdateCheckRepeatFrequency { set { repeatEveryFrame = value; } }
public bool UpdateCheckRepeat { set { repeatCheckFrame = value; } }
public float TimeCheckStartAfter { set { checkAfterTime = value; } }
public float TimeCheckRepeatFrequency { set { repeatEveryTime = value; } }
public bool TimeCheckRepeat { set { repeatCheckTime = value; } }
public AssertionComponent Component { get { return this; } }
#endregion
}
public interface IAssertionComponentConfigurator
{
/// <summary>
/// If the assertion is evaluated in Update, after how many frame should the evaluation start. Deafult is 1 (first frame)
/// </summary>
int UpdateCheckStartOnFrame { set; }
/// <summary>
/// If the assertion is evaluated in Update and UpdateCheckRepeat is true, how many frame should pass between evaluations
/// </summary>
int UpdateCheckRepeatFrequency { set; }
/// <summary>
/// If the assertion is evaluated in Update, should the evaluation be repeated after UpdateCheckRepeatFrequency frames
/// </summary>
bool UpdateCheckRepeat { set; }
/// <summary>
/// If the assertion is evaluated after a period of time, after how many seconds the first evaluation should be done
/// </summary>
float TimeCheckStartAfter { set; }
/// <summary>
/// If the assertion is evaluated after a period of time and TimeCheckRepeat is true, after how many seconds should the next evaluation happen
/// </summary>
float TimeCheckRepeatFrequency { set; }
/// <summary>
/// If the assertion is evaluated after a period, should the evaluation happen again after TimeCheckRepeatFrequency seconds
/// </summary>
bool TimeCheckRepeat { set; }
AssertionComponent Component { get; }
}
}
| |
// 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.Threading.Tasks;
using Models;
/// <summary>
/// Extension methods for HttpSuccess.
/// </summary>
public static partial class HttpSuccessExtensions
{
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Head200(this IHttpSuccess operations)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Head200Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Head200Async(this IHttpSuccess operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Head200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static bool? Get200(this IHttpSuccess operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Get200Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<bool?> Get200Async(this IHttpSuccess operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.Get200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put boolean value true returning 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Put200(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Put200Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put boolean value true returning 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Put200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Put200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Patch true Boolean value in request returning 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Patch200(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Patch200Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch true Boolean value in request returning 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Patch200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Patch200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Post bollean value true in request that returns a 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Post200(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Post200Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Post bollean value true in request that returns a 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Post200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Post200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete simple boolean value true returns 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Delete200(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Delete200Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete simple boolean value true returns 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Delete200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Delete200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put true Boolean value in request returns 201
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Put201(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Put201Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put true Boolean value in request returns 201
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Put201Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Put201WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Post true Boolean value in request returns 201 (Created)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Post201(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Post201Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Post true Boolean value in request returns 201 (Created)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Post201Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Post201WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Put202(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Put202Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Put202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Put202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Patch true Boolean value in request returns 202
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Patch202(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Patch202Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch true Boolean value in request returns 202
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Patch202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Patch202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Post true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Post202(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Post202Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Post true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Post202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Post202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete true Boolean value in request returns 202 (accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Delete202(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Delete202Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete true Boolean value in request returns 202 (accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Delete202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Delete202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Head204(this IHttpSuccess operations)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Head204Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Head204Async(this IHttpSuccess operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Head204WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Put204(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Put204Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Put204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Put204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Patch true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Patch204(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Patch204Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Patch204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Patch204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Post true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Post204(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Post204Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Post true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Post204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Post204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Delete204(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Delete204Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Delete204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Delete204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 404 status code
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Head404(this IHttpSuccess operations)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpSuccess)s).Head404Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 404 status code
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task Head404Async(this IHttpSuccess operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.Head404WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
/*
* 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 OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Threading;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
{
public class UrlData
{
public UUID hostID;
public UUID itemID;
public IScriptModule engine;
public string url;
public UUID urlcode;
public List<UUID> requests;
}
public class RequestData
{
public UUID requestId;
public AsyncHttpRequest polledRequest;
public Dictionary<string, string> headers;
public string body;
public int responseCode;
public string responseBody;
public string contentType = "text/plain";
public bool requestDone;
public int startTime;
public string uri;
}
public class UrlModule : ISharedRegionModule, IUrlModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Dictionary<string, UrlData> m_UrlMap = new Dictionary<string, UrlData>();
private readonly Dictionary<UUID, RequestData> m_RequestMap = new Dictionary<UUID, RequestData>();
private const int m_TotalUrls = 15000;
private const int m_DefaultTimeout = 25 * 1000; // 25 sec timeout
private uint https_port = 0;
private IHttpServer m_HttpServer = null;
private IHttpServer m_HttpsServer = null;
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "UrlModule"; }
}
public void Initialize(IConfigSource config)
{
bool ssl_enabled = config.Configs["Network"].GetBoolean("http_listener_ssl", false);
if (ssl_enabled)
https_port = (uint)config.Configs["Network"].GetInt("http_listener_sslport", ((int)ConfigSettings.DefaultRegionHttpPort + 1));
}
public void PostInitialize()
{
}
public void AddRegion(Scene scene)
{
if (m_HttpServer == null)
{
// There can only be one
m_HttpServer = MainServer.Instance;
// We can use the https if it is enabled
if (https_port > 0)
{
m_HttpsServer = MainServer.GetHttpServer(https_port);
}
}
scene.RegisterModuleInterface<IUrlModule>(this);
scene.EventManager.OnScriptReset += OnScriptReset;
}
public void RegionLoaded(Scene scene)
{
/*
IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>();
foreach (IScriptModule scriptModule in scriptModules)
{
scriptModule.OnScriptRemoved += ScriptRemoved;
scriptModule.OnObjectRemoved += ObjectRemoved;
}
*/
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID)
{
UUID urlcode = UUID.Random();
string url = String.Empty;
lock (m_UrlMap)
{
if (m_UrlMap.Count >= m_TotalUrls)
{
engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", String.Empty });
return urlcode;
}
url = m_HttpServer.ServerURI + "/lslhttp/" + urlcode.ToString() + "/";
UrlData urlData = new UrlData
{
hostID = host.UUID,
itemID = itemID,
engine = engine,
url = url,
urlcode = urlcode,
requests = new List<UUID>()
};
m_UrlMap[url] = urlData;
}
string uri = "/lslhttp/" + urlcode.ToString() + "/";
m_HttpServer.AddStreamHandler(new AsyncRequestHandler("POST", uri, AsyncHttpRequest, "HTTP-IN-POST", "Http In Request Handler (Asynch)"));
m_HttpServer.AddStreamHandler(new AsyncRequestHandler("GET", uri, AsyncHttpRequest, "HTTP-IN-GET", "Http In Request Handler (Asynch)"));
m_HttpServer.AddStreamHandler(new AsyncRequestHandler("PUT", uri, AsyncHttpRequest, "HTTP-IN-PUT", "Http In Request Handler (Asynch)"));
m_HttpServer.AddStreamHandler(new AsyncRequestHandler("DELETE", uri, AsyncHttpRequest, "HTTP-IN-DELETE", "Http In Request Handler (Asynch)"));
engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url });
return urlcode;
}
public UUID RequestSecureURL(IScriptModule engine, SceneObjectPart host, UUID itemID)
{
UUID urlcode = UUID.Random();
string url = String.Empty;
if (m_HttpsServer == null)
{
engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", String.Empty });
return urlcode;
}
lock (m_UrlMap)
{
if (m_UrlMap.Count >= m_TotalUrls)
{
engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", String.Empty });
return urlcode;
}
url = m_HttpsServer.ServerURI + "/lslhttps/" + urlcode.ToString() + "/";
UrlData urlData = new UrlData
{
hostID = host.UUID,
itemID = itemID,
engine = engine,
url = url,
urlcode = urlcode,
requests = new List<UUID>()
};
m_UrlMap[url] = urlData;
}
string uri = "/lslhttps/" + urlcode.ToString() + "/";
m_HttpServer.AddStreamHandler(new AsyncRequestHandler("POST", uri, AsyncHttpRequest, "HTTP-IN-POST", "Http In Request Handler (Asynch)"));
m_HttpServer.AddStreamHandler(new AsyncRequestHandler("GET", uri, AsyncHttpRequest, "HTTP-IN-GET", "Http In Request Handler (Asynch)"));
m_HttpServer.AddStreamHandler(new AsyncRequestHandler("PUT", uri, AsyncHttpRequest, "HTTP-IN-PUT", "Http In Request Handler (Asynch)"));
m_HttpServer.AddStreamHandler(new AsyncRequestHandler("DELETE", uri, AsyncHttpRequest, "HTTP-IN-DELETE", "Http In Request Handler (Asynch)"));
engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url });
return urlcode;
}
public void ReleaseURL(string url)
{
UrlData data;
lock (m_UrlMap)
{
if (!m_UrlMap.TryGetValue(url, out data))
return;
// Remove the URL so we dont accept any new requests
RemoveUrl(data);
m_UrlMap.Remove(url);
}
List<RequestData> requests = new List<RequestData>();
// Clean up existing requests
lock (m_RequestMap)
{
foreach (UUID requestId in data.requests)
{
RequestData req;
if (m_RequestMap.TryGetValue(requestId, out req))
requests.Add(req);
}
foreach (RequestData request in requests)
{
m_RequestMap.Remove(request.requestId);
}
}
foreach (RequestData request in requests)
{
// Signal this request. A 404 will be returned
request.polledRequest.SendResponse(ProcessEvents(request.polledRequest, false));
}
}
public void HttpContentType(UUID requestId, string content_type)
{
RequestData data;
lock (m_RequestMap)
{
if (!m_RequestMap.TryGetValue(requestId, out data))
return;
data.contentType = content_type;
}
}
public void HttpResponse(UUID requestId, int status, string body)
{
RequestData data = null;
lock (m_RequestMap)
{
if (!m_RequestMap.TryGetValue(requestId, out data))
return;
}
if (data != null)
{
data.responseCode = status;
data.responseBody = body;
data.requestDone = true;
data.polledRequest.SendResponse(ProcessEvents(data.polledRequest, false));
}
}
public string GetHttpHeader(UUID requestId, string header)
{
RequestData data;
lock (m_RequestMap)
{
if (!m_RequestMap.TryGetValue(requestId, out data))
return String.Empty;
string value;
if (!data.headers.TryGetValue(header, out value))
return (String.Empty);
else
return value;
}
}
public int GetFreeUrls()
{
return m_TotalUrls - m_UrlMap.Count;
}
private void OnScriptReset(uint localID, UUID itemID)
{
ScriptRemoved(itemID);
}
public void ScriptRemoved(UUID itemID)
{
List<UrlData> removeURLs = new List<UrlData>();
lock (m_UrlMap)
{
foreach (UrlData url in m_UrlMap.Values)
{
if (url.itemID == itemID)
{
RemoveUrl(url);
removeURLs.Add(url);
}
}
foreach (UrlData data in removeURLs)
{
m_UrlMap.Remove(data.url);
}
}
List<RequestData> requests = new List<RequestData>();
lock (m_RequestMap)
{
foreach (UrlData url in removeURLs)
{
foreach (UUID id in url.requests)
{
RequestData req;
if (m_RequestMap.TryGetValue(id, out req))
{
m_RequestMap.Remove(id);
requests.Add(req);
}
}
}
}
foreach (RequestData request in requests)
{
// Pulse this request. A 404 will be returned
request.polledRequest.SendResponse(ProcessEvents(request.polledRequest, false));
}
}
public void ObjectRemoved(UUID objectID)
{
List<UrlData> removeURLs = new List<UrlData>();
lock (m_UrlMap)
{
foreach (UrlData url in m_UrlMap.Values)
{
if (url.hostID == objectID)
{
RemoveUrl(url);
removeURLs.Add(url);
}
}
foreach (UrlData data in removeURLs)
{
m_UrlMap.Remove(data.url);
}
}
List<RequestData> requests = new List<RequestData>();
lock (m_RequestMap)
{
foreach (UrlData url in removeURLs)
{
foreach (UUID id in url.requests)
{
RequestData req;
if (m_RequestMap.TryGetValue(id, out req))
{
requests.Add(req);
m_RequestMap.Remove(id);
}
}
}
}
foreach (RequestData request in requests)
{
// Pulse this request. A 404 will be returned
request.polledRequest.SendResponse(ProcessEvents(request.polledRequest, false));
}
}
private void RemoveUrl(UrlData data)
{
string url = data.url;
bool is_ssl = url.Contains("lslhttps");
string protocol = (is_ssl ? "/lslhttps/" : "/lslhttp/");
m_HttpServer.RemoveStreamHandler("POST", protocol + data.urlcode.ToString() + "/");
m_HttpServer.RemoveStreamHandler("GET", protocol + data.urlcode.ToString() + "/");
}
private string URLFromURI(string uri)
{
bool is_ssl = uri.Contains("lslhttps");
int pos1 = uri.IndexOf("/");// /lslhttp
int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/
int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/
string uri_tmp = uri.Substring(0, pos3 + 1);
if (!is_ssl)
return (m_HttpServer.ServerURI + uri_tmp);
else
return (m_HttpsServer.ServerURI + uri_tmp);
}
#region PolledService Interface
public void AsyncHttpRequest(IHttpServer server, string path, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
UUID urlcode;
if (UUID.TryParse(path, out urlcode))
return;
AsyncHttpRequest asyncRequest =
new AsyncHttpRequest(server, httpRequest, httpResponse, urlcode, TimeoutHandler, m_DefaultTimeout);
UUID requestID = asyncRequest.RequestID;
Hashtable request = asyncRequest.RequestData;
string uri = request["uri"].ToString();
try
{
Hashtable headers = (Hashtable)request["headers"];
//HTTP server code doesn't provide us with QueryStrings
string queryString = String.Empty;
int pos1 = uri.IndexOf("/");// /lslhttp
int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/
int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/
string pathInfo = uri.Substring(pos3);
string url = URLFromURI(uri);
UrlData urlData = null;
lock (m_UrlMap)
{
m_UrlMap.TryGetValue(url, out urlData);
// Returning NULL sends a 404 from the base server
if (urlData == null)
asyncRequest.SendResponse(server.SendHTML404(httpResponse));
}
//for llGetHttpHeader support we need to store original URI here
//to make x-path-info / x-query-string / x-script-url / x-remote-ip headers
//as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader
RequestData requestData =
new RequestData
{
requestId = asyncRequest.RequestID,
polledRequest = asyncRequest,
requestDone = false,
startTime = Environment.TickCount,
uri = uri
};
if (requestData.headers == null)
requestData.headers = new Dictionary<string, string>();
// Copy in the headers, convert keys to lower case: See.
// http://wiki.secondlife.com/wiki/LlGetHTTPHeader
foreach (DictionaryEntry header in headers)
{
string key = (string)header.Key;
string value = (string)header.Value;
requestData.headers.Add(key.ToLower(), value);
}
foreach (DictionaryEntry de in request)
{
if (de.Key.ToString() == "querystringkeys")
{
String[] keys = (String[])de.Value;
foreach (String key in keys)
{
if ((key != null) && request.ContainsKey(key))
{
string val = (String)request[key];
queryString = queryString + key + "=" + val + "&";
}
}
if (queryString.Length > 1)
queryString = queryString.Substring(0, queryString.Length - 1);
}
}
// Grab the raw unprocessed original query string, if any.
int rawQueryPos = httpRequest.Url.Query.IndexOf('?');
string rawQueryStr = (rawQueryPos < 0) ? httpRequest.Url.Query : httpRequest.Url.Query.Substring(rawQueryPos + 1);
//if this machine is behind DNAT/port forwarding, currently this is being
//set to address of port forwarding router
requestData.headers["x-remote-ip"] = httpRequest.RemoteIPEndPoint.ToString();
requestData.headers["x-path-info"] = pathInfo;
requestData.headers["x-query-string"] = rawQueryStr; // raw original (SL-compatible)
requestData.headers["x-query-string-compat"] = queryString; // processed (old Halcyon scripts)
requestData.headers["x-script-url"] = urlData.url;
lock (m_RequestMap)
{
m_RequestMap.Add(requestID, requestData);
}
lock (m_UrlMap)
{
urlData.requests.Add(requestID);
}
urlData.engine.PostScriptEvent(urlData.itemID, "http_request", new Object[] { requestID.ToString(), request["http-method"].ToString(), request["body"].ToString() });
}
catch (Exception we)
{
m_log.Warn("[HttpRequestHandler]: http-in request failed");
m_log.Warn(we.Message);
m_log.Warn(we.StackTrace);
asyncRequest.SendResponse(server.SendHTML500(httpResponse));
}
}
private void TimeoutHandler(AsyncHttpRequest pRequest)
{
pRequest.SendResponse(ProcessEvents(pRequest, true));
}
private Hashtable ProcessEvents(AsyncHttpRequest pRequest, bool timedOut)
{
UUID requestID = pRequest.RequestID;
UrlData urlData = null;
RequestData requestData = null;
Hashtable response = new Hashtable();
response["content_type"] = "text/plain";
lock (m_RequestMap)
{
if (m_RequestMap.TryGetValue(requestID, out requestData))
m_RequestMap.Remove(requestID);
}
if (requestData != null)
{
string url = URLFromURI(requestData.uri);
lock (m_UrlMap)
{
if (m_UrlMap.TryGetValue(url, out urlData))
urlData.requests.Remove(requestID);
}
}
if ((requestData == null) || (urlData == null))
{
response["int_response_code"] = 404;
response["str_response_string"] = "Request not found";
return response;
}
if ((timedOut == true) ||
((requestData != null) && (requestData.requestDone == false)))
{
response["int_response_code"] = 500;
response["str_response_string"] = "Script timeout";
}
else
{
//put response
response["int_response_code"] = requestData.responseCode;
response["str_response_string"] = requestData.responseBody;
response["content_type"] = requestData.contentType;
}
return response;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Xml;
using UnityEngine;
namespace DarkMultiPlayer
{
public class Settings
{
//Settings
public string playerName;
public string playerPublicKey;
public string playerPrivateKey;
public int cacheSize;
public int disclaimerAccepted;
public List<ServerEntry> servers;
public Color playerColor;
public KeyCode screenshotKey;
public KeyCode chatKey;
public string selectedFlag;
public bool compressionEnabled;
public bool revertEnabled;
public DMPToolbarType toolbarType;
private const string DEFAULT_PLAYER_NAME = "Player";
private const string OLD_SETTINGS_FILE = "servers.xml";
private const string SETTINGS_FILE = "settings.cfg";
private const string PUBLIC_KEY_FILE = "publickey.txt";
private const string PRIVATE_KEY_FILE = "privatekey.txt";
private const int DEFAULT_CACHE_SIZE = 100;
private string dataLocation;
private string oldSettingsFile;
private string settingsFile;
private string backupOldSettingsFile;
private string backupSettingsFile;
private string publicKeyFile;
private string privateKeyFile;
private string backupPublicKeyFile;
private string backupPrivateKeyFile;
public Settings()
{
string darkMultiPlayerDataDirectory = Client.dmpClient.dmpDataDir;
if (!Directory.Exists(darkMultiPlayerDataDirectory))
{
Directory.CreateDirectory(darkMultiPlayerDataDirectory);
}
string darkMultiPlayerSavesDirectory = Path.Combine(Path.Combine(Client.dmpClient.kspRootPath, "saves"), "DarkMultiPlayer");
if (!Directory.Exists(darkMultiPlayerSavesDirectory))
{
Directory.CreateDirectory(darkMultiPlayerSavesDirectory);
}
dataLocation = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Data");
oldSettingsFile = Path.Combine(dataLocation, OLD_SETTINGS_FILE);
settingsFile = Path.Combine(dataLocation, SETTINGS_FILE);
backupOldSettingsFile = Path.Combine(darkMultiPlayerSavesDirectory, OLD_SETTINGS_FILE);
backupSettingsFile = Path.Combine(darkMultiPlayerSavesDirectory, SETTINGS_FILE);
publicKeyFile = Path.Combine(dataLocation, PUBLIC_KEY_FILE);
backupPublicKeyFile = Path.Combine(darkMultiPlayerSavesDirectory, PUBLIC_KEY_FILE);
privateKeyFile = Path.Combine(dataLocation, PRIVATE_KEY_FILE);
backupPrivateKeyFile = Path.Combine(darkMultiPlayerSavesDirectory, PRIVATE_KEY_FILE);
LoadSettings();
}
public void LoadOldSettings()
{
//Read XML settings
try
{
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(backupOldSettingsFile) && !File.Exists(oldSettingsFile))
{
DarkLog.Debug("[Settings]: Restoring old player settings file!");
File.Move(backupOldSettingsFile, oldSettingsFile);
}
xmlDoc.Load(oldSettingsFile);
playerName = xmlDoc.SelectSingleNode("/settings/global/@username").Value;
cacheSize = int.Parse(xmlDoc.SelectSingleNode("/settings/global/@cache-size").Value);
disclaimerAccepted = Int32.Parse(xmlDoc.SelectSingleNode("/settings/global/@disclaimer").Value);
string floatArrayString = xmlDoc.SelectSingleNode("/settings/global/@player-color").Value;
string[] floatArrayStringSplit = floatArrayString.Split(',');
float redColor = float.Parse(floatArrayStringSplit[0].Trim());
float greenColor = float.Parse(floatArrayStringSplit[1].Trim());
float blueColor = float.Parse(floatArrayStringSplit[2].Trim());
//Bounds checking - Gotta check up on those players :)
if (redColor < 0f)
{
redColor = 0f;
}
if (redColor > 1f)
{
redColor = 1f;
}
if (greenColor < 0f)
{
greenColor = 0f;
}
if (greenColor > 1f)
{
greenColor = 1f;
}
if (blueColor < 0f)
{
blueColor = 0f;
}
if (blueColor > 1f)
{
blueColor = 1f;
}
playerColor = new Color(redColor, greenColor, blueColor, 1f);
chatKey = (KeyCode)Int32.Parse(xmlDoc.SelectSingleNode("/settings/global/@chat-key").Value);
screenshotKey = (KeyCode)Int32.Parse(xmlDoc.SelectSingleNode("/settings/global/@screenshot-key").Value);
selectedFlag = xmlDoc.SelectSingleNode("/settings/global/@selected-flag").Value;
compressionEnabled = Boolean.Parse(xmlDoc.SelectSingleNode("/settings/global/@compression").Value);
revertEnabled = Boolean.Parse(xmlDoc.SelectSingleNode("/settings/global/@revert").Value);
toolbarType = (DMPToolbarType)Int32.Parse(xmlDoc.SelectSingleNode("/settings/global/@toolbar").Value);
XmlNodeList serverNodeList = xmlDoc.GetElementsByTagName("server");
servers = new List<ServerEntry>();
foreach (XmlNode xmlNode in serverNodeList)
{
ServerEntry newServer = new ServerEntry();
newServer.name = xmlNode.Attributes["name"].Value;
newServer.address = xmlNode.Attributes["address"].Value;
Int32.TryParse(xmlNode.Attributes["port"].Value, out newServer.port);
servers.Add(newServer);
}
SaveSettings();
}
catch (Exception e)
{
DarkLog.Debug("Error loading old settings: " + e);
}
}
private void GenerateNewKeypair()
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024))
{
try
{
playerPublicKey = rsa.ToXmlString(false);
playerPrivateKey = rsa.ToXmlString(true);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
finally
{
//Don't save the key in the machine store.
rsa.PersistKeyInCsp = false;
}
}
File.WriteAllText(publicKeyFile, playerPublicKey);
File.WriteAllText(privateKeyFile, playerPrivateKey);
}
public void LoadSettings()
{
try
{
if (File.Exists(backupOldSettingsFile) || File.Exists(oldSettingsFile))
{
DarkLog.Debug("[Settings]: Loading old settings");
LoadOldSettings();
SaveSettings();
File.Delete(backupOldSettingsFile);
File.Delete(oldSettingsFile);
}
bool saveAfterLoad = false;
ConfigNode mainNode = new ConfigNode();
if (File.Exists(backupSettingsFile) && !File.Exists(settingsFile))
{
DarkLog.Debug("[Settings]: Restoring backup file");
File.Copy(backupSettingsFile, settingsFile);
}
if (!File.Exists(settingsFile))
{
mainNode = GetDefaultSettings();
playerName = DEFAULT_PLAYER_NAME;
mainNode.Save(settingsFile);
}
if (!File.Exists(backupSettingsFile))
{
DarkLog.Debug("[Settings]: Backing up settings");
File.Copy(settingsFile, backupSettingsFile);
}
mainNode = ConfigNode.Load(settingsFile);
ConfigNode settingsNode = mainNode.GetNode("SETTINGS");
ConfigNode playerNode = settingsNode.GetNode("PLAYER");
ConfigNode bindingsNode = settingsNode.GetNode("KEYBINDINGS");
playerName = playerNode.GetValue("name");
if (!int.TryParse(settingsNode.GetValue("cacheSize"), out cacheSize))
{
DarkLog.Debug("[Settings]: Adding cache size to settings file");
cacheSize = DEFAULT_CACHE_SIZE;
saveAfterLoad = true;
}
if (!int.TryParse(settingsNode.GetValue("disclaimer"), out disclaimerAccepted))
{
DarkLog.Debug("[Settings]: Adding disclaimer to settings file");
disclaimerAccepted = 0;
saveAfterLoad = true;
}
if (!playerNode.TryGetValue("color", ref playerColor))
{
DarkLog.Debug("[Settings]: Adding color to settings file");
playerColor = PlayerColorWorker.GenerateRandomColor();
saveAfterLoad = true;
}
int chatKey = (int)KeyCode.BackQuote, screenshotKey = (int)KeyCode.F8;
if (!int.TryParse(bindingsNode.GetValue("chat"), out chatKey))
{
DarkLog.Debug("[Settings]: Adding chat key to settings file");
this.chatKey = KeyCode.BackQuote;
saveAfterLoad = true;
}
else
{
this.chatKey = (KeyCode)chatKey;
}
if (!int.TryParse(bindingsNode.GetValue("screenshot"), out screenshotKey))
{
DarkLog.Debug("[Settings]: Adding screenshot key to settings file");
this.screenshotKey = KeyCode.F8;
saveAfterLoad = true;
}
else
{
this.screenshotKey = (KeyCode)screenshotKey;
}
if (!playerNode.TryGetValue("flag", ref selectedFlag))
{
DarkLog.Debug("[Settings]: Adding selected flag to settings file");
selectedFlag = "Squad/Flags/default";
saveAfterLoad = true;
}
if (!settingsNode.TryGetValue("compression", ref compressionEnabled))
{
DarkLog.Debug("[Settings]: Adding compression flag to settings file");
compressionEnabled = true;
saveAfterLoad = true;
}
if (!settingsNode.TryGetValue("revert", ref revertEnabled))
{
DarkLog.Debug("[Settings]: Adding revert flag to settings file");
revertEnabled = true;
saveAfterLoad = true;
}
int toolbarType;
if (!int.TryParse(settingsNode.GetValue("toolbar"), out toolbarType))
{
DarkLog.Debug("[Settings]: Adding toolbar flag to settings file");
this.toolbarType = DMPToolbarType.BLIZZY_IF_INSTALLED;
saveAfterLoad = true;
}
else
{
this.toolbarType = (DMPToolbarType)toolbarType;
}
ConfigNode serversNode = settingsNode.GetNode("SERVERS");
servers = new List<ServerEntry>();
if (serversNode.HasNode("SERVER"))
{
foreach (ConfigNode serverNode in serversNode.GetNodes("SERVER"))
{
ServerEntry newServer = new ServerEntry();
newServer.name = serverNode.GetValue("name");
newServer.address = serverNode.GetValue("address");
serverNode.TryGetValue("port", ref newServer.port);
servers.Add(newServer);
}
}
if (saveAfterLoad) SaveSettings();
}
catch (Exception e)
{
DarkLog.Debug("Error while loading settings:");
DarkLog.Debug(e.ToString());
}
//Read player token
try
{
//Restore backup if needed
if (File.Exists(backupPublicKeyFile) && File.Exists(backupPrivateKeyFile) && (!File.Exists(publicKeyFile) || !File.Exists(privateKeyFile)))
{
DarkLog.Debug("[Settings]: Restoring backed up keypair!");
File.Copy(backupPublicKeyFile, publicKeyFile, true);
File.Copy(backupPrivateKeyFile, privateKeyFile, true);
}
//Load or create token file
if (File.Exists(privateKeyFile) && File.Exists(publicKeyFile))
{
playerPublicKey = File.ReadAllText(publicKeyFile);
playerPrivateKey = File.ReadAllText(privateKeyFile);
}
else
{
DarkLog.Debug("[Settings]: Creating new keypair!");
GenerateNewKeypair();
}
//Save backup token file if needed
if (!File.Exists(backupPublicKeyFile) || !File.Exists(backupPrivateKeyFile))
{
DarkLog.Debug("[Settings]: Backing up keypair");
File.Copy(publicKeyFile, backupPublicKeyFile, true);
File.Copy(privateKeyFile, backupPrivateKeyFile, true);
}
}
catch
{
DarkLog.Debug("Error processing keypair, creating new keypair");
GenerateNewKeypair();
DarkLog.Debug("[Settings]: Backing up keypair");
File.Copy(publicKeyFile, backupPublicKeyFile, true);
File.Copy(privateKeyFile, backupPrivateKeyFile, true);
}
}
public void SaveSettings()
{
ConfigNode mainNode = new ConfigNode();
ConfigNode settingsNode = mainNode.AddNode("SETTINGS");
ConfigNode playerNode = settingsNode.AddNode("PLAYER");
playerNode.SetValue("name", playerName, true);
playerNode.SetValue("color", playerColor, true);
playerNode.SetValue("flag", selectedFlag, true);
ConfigNode bindingsNode = settingsNode.AddNode("KEYBINDINGS");
bindingsNode.SetValue("chat", (int)chatKey, true);
bindingsNode.SetValue("screenshot", (int)screenshotKey, true);
settingsNode.SetValue("cacheSize", cacheSize, true);
settingsNode.SetValue("disclaimer", disclaimerAccepted, true);
settingsNode.SetValue("compression", compressionEnabled, true);
settingsNode.SetValue("revert", revertEnabled, true);
settingsNode.SetValue("toolbar", (int)toolbarType, true);
ConfigNode serversNode = settingsNode.AddNode("SERVERS");
serversNode.ClearNodes();
foreach (ServerEntry server in servers)
{
ConfigNode serverNode = serversNode.AddNode("SERVER");
serverNode.AddValue("name", server.name);
serverNode.AddValue("address", server.address);
serverNode.AddValue("port", server.port);
}
mainNode.Save(settingsFile);
File.Copy(settingsFile, backupSettingsFile, true);
}
public ConfigNode GetDefaultSettings()
{
ConfigNode mainNode = new ConfigNode();
ConfigNode settingsNode = new ConfigNode("SETTINGS");
settingsNode.AddValue("cacheSize", DEFAULT_CACHE_SIZE);
ConfigNode playerNode = new ConfigNode("PLAYER");
playerNode.AddValue("name", DEFAULT_PLAYER_NAME);
ConfigNode bindingsNode = new ConfigNode("KEYBINDINGS");
ConfigNode serversNode = new ConfigNode("SERVERS");
settingsNode.AddNode(playerNode);
settingsNode.AddNode(bindingsNode);
settingsNode.AddNode(serversNode);
mainNode.AddNode(settingsNode);
return mainNode;
}
private string newXMLString()
{
return String.Format("<?xml version=\"1.0\"?><settings><global username=\"{0}\" cache-size=\"{1}\"/><servers></servers></settings>", DEFAULT_PLAYER_NAME, DEFAULT_CACHE_SIZE);
}
}
public class ServerEntry
{
public string name;
public string address;
public int port;
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Enable this macro to shift object pointers from the beginning of the header to the beginning of the payload.
#define CANONICAL_OBJECT_POINTERS
namespace Microsoft.Zelig.LLVM
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using Importer = Microsoft.Zelig.MetaData.Importer;
using Normalized = Microsoft.Zelig.MetaData.Normalized;
using IR = Microsoft.Zelig.CodeGeneration.IR;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
using Llvm.NET.Values;
using System.Diagnostics;
using Llvm.NET.DebugInfo;
public partial class LLVMModuleManager
{
private ISectionNameProvider m_SectionNameProvider;
private readonly Debugging.DebugInfo m_dummyDebugInfo;
private _Module m_module;
private readonly string m_imageName;
private readonly IR.TypeSystemForCodeTransformation m_typeSystem;
private GrowOnlyHashTable <TS.TypeRepresentation, _Type> m_typeRepresentationsToType;
private GrowOnlyHashTable <TS.MethodRepresentation, Debugging.DebugInfo> m_debugInfoForMethods;
private GrowOnlyHashTable <IR.DataManager.DataDescriptor, Constant> m_globalInitializedValues;
private bool m_typeSystemAlreadyConverted;
private bool m_turnOffCompilationAndValidation;
//TypeSystem might not be completely initialized at this point.
public LLVMModuleManager( IR.TypeSystemForCodeTransformation typeSystem, string imageName )
{
m_imageName = imageName;
m_typeSystem = typeSystem;
m_debugInfoForMethods = HashTableFactory.New<TS.MethodRepresentation, Debugging.DebugInfo>( );
m_typeRepresentationsToType = HashTableFactory.New<TS.TypeRepresentation, _Type>( );
m_globalInitializedValues = HashTableFactory.New<IR.DataManager.DataDescriptor, Constant>();
m_typeSystemAlreadyConverted = false;
m_turnOffCompilationAndValidation = false;
m_module = new _Module( m_imageName, m_typeSystem );
m_dummyDebugInfo = new Debugging.DebugInfo( m_imageName, 0, 0, 0, 0 );
// Initialize to safe default value, will be changed later before the manager is used
m_SectionNameProvider = new EmptySectionNameProvider( m_typeSystem );
}
public ISectionNameProvider SectionNameProvider
{
get
{
return m_SectionNameProvider;
}
set
{
m_SectionNameProvider = value;
}
}
public void Compile()
{
CompleteMissingDataDescriptors();
//
// Synthesize the code for all exported methods as a simple C-style function using the name
// of the method without full qualification
//
foreach(TS.MethodRepresentation md in m_typeSystem.ExportedMethods)
{
_Function handler = GetOrInsertFunction( md );
m_module.CreateAlias(handler.LlvmFunction, md.Name);
}
if(!m_turnOffCompilationAndValidation)
{
TS.MethodRepresentation bootstrapResetMR = m_typeSystem.GetWellKnownMethod( "Bootstrap_Initialization" );
_Function bootstrapReset = GetOrInsertFunction( bootstrapResetMR );
if(m_typeSystem.PlatformAbstraction.PlatformFamily == TargetModel.Win32.InstructionSetVersion.Platform_Family__Win32 )
{
m_module.CreateAlias(bootstrapReset.LlvmFunction, "LLILUM_main");
}
else
{
m_module.CreateAlias(bootstrapReset.LlvmFunction, "main");
}
m_module.Compile();
}
}
public void DumpToFile( string filename, OutputFormat format )
{
m_module.DumpToFile( filename, format );
}
public void TurnOffCompilationAndValidation( )
{
m_turnOffCompilationAndValidation = true;
}
public DISubProgram GetScopeFor( TS.MethodRepresentation md )
{
return GetOrInsertFunction(md)?.LlvmFunction?.DISubProgram;
}
public _Function GetOrInsertFunction( TS.MethodRepresentation md )
{
_Function function = m_module.GetOrInsertFunction( md );
function.LlvmFunction.Section = m_SectionNameProvider.GetSectionNameFor( md );
return function;
}
public static string GetFullMethodName( TS.MethodRepresentation method )
{
if( method.Flags.HasFlag( TS.MethodRepresentation.Attributes.PinvokeImpl ) )
{
return method.Name;
}
return $"{method.OwnerType.FullName}::{method.Name}#{method.m_identity}";
}
private void CompleteMissingDataDescriptors( )
{
bool stillMissing = true;
while( stillMissing )
{
stillMissing = false;
foreach( var dd in m_globalInitializedValues.Keys )
{
// Force creation of any missing global data descriptor by accessing its value.
if( m_globalInitializedValues[ dd ].IsAnUninitializedGlobal( ) )
{
stillMissing = true;
GlobalValueFromDataDescriptor( dd, setInitializer: true );
break;
}
}
}
m_module.FinalizeGlobals();
}
private Constant GetUCVStruct( _Type type, bool anon, params Constant[ ] vals )
{
var fields = new List<Constant>( );
foreach( var val in vals )
{
fields.Add( val );
}
return m_module.GetUCVStruct( type, fields, anon );
}
private object GetDirectFromArrayDescriptor( IR.DataManager.ArrayDescriptor ad, uint pos )
{
return ad.Values != null ? ad.Values[ pos ] : ad.Source.GetValue( pos );
}
private Constant GetUCVArray( IR.DataManager.ArrayDescriptor ad )
{
uint arrayLength = ( uint )( ( ad.Values == null ) ? ad.Source.Length : ad.Values.Length );
var fields = new List<Constant>( );
TS.TypeRepresentation elTR = ( ( TS.ArrayReferenceTypeRepresentation )ad.Context ).ContainedType;
//
// Special case for common scalar arrays.
//
if( ad.Values == null )
{
for( uint i = 0; i < arrayLength; i++ )
{
object fdVal = GetDirectFromArrayDescriptor( ad, i );
fields.Add( GetScalarTypeUCV( elTR, fdVal ) );
}
}
else
{
for( uint i = 0; i < arrayLength; i++ )
{
object val = GetDirectFromArrayDescriptor( ad, i );
if( val == null )
{
fields.Add(m_module.GetNullValue(GetOrInsertType(elTR)));
}
else if( val is IR.DataManager.DataDescriptor )
{
IR.DataManager.DataDescriptor valDD = ( IR.DataManager.DataDescriptor )val;
if( valDD.Nesting != null )
{
fields.Add( UCVFromDataDescriptor( valDD ) );
}
else
{
fields.Add(GlobalValueFromDataDescriptor(valDD, false));
}
}
else if( ad.Context.ContainedType is TS.ScalarTypeRepresentation )
{
fields.Add( GetScalarTypeUCV( elTR, val ) );
}
else
{
throw TypeConsistencyErrorException.Create( "Don't know how to write {0}", val );
}
}
}
return m_module.GetUCVArray( GetOrInsertType( elTR ), fields );
}
private Constant GetScalarTypeUCV( TS.TypeRepresentation tr, object value )
{
_Type type = GetOrInsertType( tr );
return m_module.GetUCVScalar( type, value );
}
private bool TypeChangesAfterCreation( IR.DataManager.DataDescriptor dd )
{
return dd is IR.DataManager.ArrayDescriptor || dd.Context == m_typeSystem.WellKnownTypes.System_String;
}
public Constant GlobalValueFromDataDescriptor(IR.DataManager.DataDescriptor dd, bool setInitializer)
{
// If the type changes after creation it's a string or array type, so force initialization.
if (TypeChangesAfterCreation(dd))
{
setInitializer = true;
}
Constant global;
if (m_globalInitializedValues.TryGetValue(dd, out global))
{
// If we already have an initialized global, or an uninitialized one that we're still not initializing,
// return the cached one. Uninitialized globals will be replaced below.
if (!global.IsAnUninitializedGlobal() || !setInitializer)
{
return global;
}
}
if (setInitializer)
{
// Get the object header if this type needs one.
Constant header = null;
#if CANONICAL_OBJECT_POINTERS
if (!(dd.Context is TS.ValueTypeRepresentation))
{
header = GetUCVObjectHeader(dd);
}
#endif // CANONICAL_OBJECT_POINTERS
_Type type = GetOrInsertInlineType(dd.Context);
Constant value = UCVFromDataDescriptor(dd);
string name = type.Name;
string sectionName = m_SectionNameProvider.GetSectionNameFor(dd);
// Rename vtable constants so they can be easily read in the output.
// FUTURE: This should probably be set more generally at a higher level, likely in DataManager.
if (dd.Context == m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_VTable)
{
var objDescriptor = (IR.DataManager.ObjectDescriptor)dd;
var vtable = objDescriptor.Source as TS.VTable;
string sourceName = vtable?.TypeInfo?.FullName;
if (sourceName != null)
{
name = sourceName + ".VTable";
}
}
global = m_module.GetGlobalFromUCV(type, header, value, !dd.IsMutable, name, sectionName);
}
else
{
global = m_module.GetUninitializedGlobal(GetOrInsertInlineType(dd.Context));
}
// If we had an uninitialized placeholder, replace it with the new copy.
Constant cachedGlobal;
if (m_globalInitializedValues.TryGetValue(dd, out cachedGlobal))
{
cachedGlobal.MergeToAndRemove(global);
}
m_globalInitializedValues[dd] = global;
return global;
}
private Constant GetUCVObjectHeader( IR.DataManager.DataDescriptor dd )
{
TS.WellKnownFields wkf = m_typeSystem.WellKnownFields;
TS.WellKnownTypes wkt = m_typeSystem.WellKnownTypes;
var fields = new List<Constant>( );
Runtime.ObjectHeader.GarbageCollectorFlags flags;
if( dd.IsMutable )
{
flags = Runtime.ObjectHeader.GarbageCollectorFlags.UnreclaimableObject;
}
else
{
flags = Runtime.ObjectHeader.GarbageCollectorFlags.ReadOnlyObject;
}
var descriptor = (IR.DataManager.DataDescriptor)dd.Owner.GetObjectDescriptor(dd.Context.VirtualTable);
Constant virtualTable = GlobalValueFromDataDescriptor(descriptor, false);
fields.Add(GetScalarTypeUCV(wkf.ObjectHeader_MultiUseWord.FieldType, (ulong)flags));
fields.Add(virtualTable);
_Type headerType = GetOrInsertType( wkt.Microsoft_Zelig_Runtime_ObjectHeader );
return m_module.GetUCVStruct( headerType.UnderlyingType, fields, false );
}
private Constant UCVFromDataDescriptor(IR.DataManager.DataDescriptor dd)
{
return UCVFromDataDescriptor(dd, dd.Context);
}
private Constant UCVFromDataDescriptor(
IR.DataManager.DataDescriptor dd,
TS.TypeRepresentation currentType)
{
TS.WellKnownFields wkf = m_typeSystem.WellKnownFields;
TS.WellKnownTypes wkt = m_typeSystem.WellKnownTypes;
TS.WellKnownMethods wkm = m_typeSystem.WellKnownMethods;
if( dd is IR.DataManager.ObjectDescriptor )
{
IR.DataManager.ObjectDescriptor od = ( IR.DataManager.ObjectDescriptor )dd;
var fields = new List<Constant>( );
#if CANONICAL_OBJECT_POINTERS
// Recursively add parent class fields for reference types.
if( !( currentType is TS.ValueTypeRepresentation ) && ( currentType != wkt.System_Object ) )
#else // CANONICAL_OBJECT_POINTERS
// Special case: System.Object always gets an object header.
if( currentType == wkt.System_Object )
{
Constant ucv = GetUCVObjectHeader( dd );
_Type objectType = GetOrInsertType( wkt.System_Object );
return GetUCVStruct( objectType.UnderlyingType, false, ucv );
}
if( !( currentType is TS.ValueTypeRepresentation ) )
#endif // CANONICAL_OBJECT_POINTERS
{
fields.Add( UCVFromDataDescriptor( dd, currentType.Extends ) );
}
for( uint i = 0; i < currentType.Size - ( currentType.Extends == null ? 0 : currentType.Extends.Size ); i++ )
{
var fd = currentType.FindFieldAtOffset( ( int )( i + ( currentType.Extends == null ? 0 : currentType.Extends.Size ) ) );
if( fd != null )
{
i += fd.FieldType.SizeOfHoldingVariable - 1;
if( !od.Values.ContainsKey( fd ) )
{
fields.Add(m_module.GetNullValue(GetOrInsertType(fd.FieldType)));
continue;
}
var fdVal = od.Values[ fd ];
if( fd == wkf.CodePointer_Target )
{
//
// Special case for code pointers: substitute with actual code pointers.
//
IntPtr id = ( IntPtr )fdVal;
object ptr = od.Owner.GetCodePointerFromUniqueID( id );
if( ptr is TS.MethodRepresentation )
{
TS.MethodRepresentation md = ( TS.MethodRepresentation )ptr;
Constant ucv = GetOrInsertFunction(md).LlvmFunction;
ucv = GetUCVStruct( GetOrInsertType( fd.FieldType ), false, ucv );
fields.Add( ucv );
}
else if( ptr is IR.ExceptionHandlerBasicBlock )
{
IR.ExceptionHandlerBasicBlock ehBB = ( IR.ExceptionHandlerBasicBlock )ptr;
//
// temporary place-holder
//
Constant ucv = GetOrInsertFunction(wkm.TypeSystemManager_Throw).LlvmFunction;
ucv = GetUCVStruct( GetOrInsertType( fd.FieldType ), false, ucv );
fields.Add( ucv );
}
else
{
throw new Exception( "I'm not sure what kind of code pointer is this:" + ptr );
}
}
else if( fdVal == null )
{
fields.Add(m_module.GetNullValue(GetOrInsertType(fd.FieldType)));
}
else if( fdVal is IR.DataManager.DataDescriptor )
{
IR.DataManager.DataDescriptor valDD = ( IR.DataManager.DataDescriptor )fdVal;
if( valDD.Nesting != null )
{
fields.Add( UCVFromDataDescriptor( valDD ) );
}
else
{
fields.Add(GlobalValueFromDataDescriptor(valDD, false));
}
}
else if( fd.FieldType is TS.ScalarTypeRepresentation )
{
fields.Add( GetScalarTypeUCV( fd.FieldType, fdVal ) );
}
else
{
throw TypeConsistencyErrorException.Create( "Don't know how to write {0}", fdVal );
}
}
else
{
fields.Add( GetScalarTypeUCV( wkt.System_Byte, 0xAB ) );
}
}
if( currentType == wkt.System_String )
{
var chars = new List<Constant>( );
foreach( char c in ( ( string )od.Source ).ToCharArray( ) )
{
chars.Add( GetScalarTypeUCV( wkf.StringImpl_FirstChar.FieldType, c ) );
}
fields.Add( m_module.GetUCVArray( GetOrInsertType( wkf.StringImpl_FirstChar.FieldType ), chars ) );
}
return m_module.GetUCVStruct( GetOrInsertInlineType( currentType ), fields, currentType == wkt.System_String );
}
else if( dd is IR.DataManager.ArrayDescriptor )
{
IR.DataManager.ArrayDescriptor ad = ( IR.DataManager.ArrayDescriptor )dd;
int length = ad.Source?.Length ?? ad.Length;
#if CANONICAL_OBJECT_POINTERS
Constant obj = GetUCVStruct( GetOrInsertInlineType( wkt.System_Object ), false );
#else // CANONICAL_OBJECT_POINTERS
Constant header = GetUCVObjectHeader( dd );
Constant obj = GetUCVStruct( GetOrInsertInlineType( wkt.System_Object ), false, header );
#endif // CANONICAL_OBJECT_POINTERS
Constant arrayLength = GetScalarTypeUCV( wkf.ArrayImpl_m_numElements.FieldType, length );
Constant arrayFields = GetUCVStruct( GetOrInsertInlineType( wkt.System_Array ), false, obj, arrayLength );
return GetUCVStruct( GetOrInsertInlineType( dd.Context ), true, arrayFields, GetUCVArray( ad ) );
}
else
{
throw new System.InvalidOperationException( "DataDescriptor type not supported:" + dd );
}
}
public _Module Module
{
get
{
return m_module;
}
}
public GrowOnlyHashTable<TS.MethodRepresentation, Debugging.DebugInfo> DebugInfoForMethods
{
get
{
return m_debugInfoForMethods;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Client.Cache
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Client.Cache;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Client.Cache.Query;
using Apache.Ignite.Core.Impl.Common;
using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter;
/// <summary>
/// Client cache implementation.
/// </summary>
internal sealed class CacheClient<TK, TV> : ICacheClient<TK, TV>, ICacheInternal
{
/** Scan query filter platform code: .NET filter. */
private const byte FilterPlatformDotnet = 2;
/** Cache name. */
private readonly string _name;
/** Cache id. */
private readonly int _id;
/** Ignite. */
private readonly IgniteClient _ignite;
/** Marshaller. */
private readonly Marshaller _marsh;
/** Keep binary flag. */
private readonly bool _keepBinary;
/// <summary>
/// Initializes a new instance of the <see cref="CacheClient{TK, TV}" /> class.
/// </summary>
/// <param name="ignite">Ignite.</param>
/// <param name="name">Cache name.</param>
/// <param name="keepBinary">Binary mode flag.</param>
public CacheClient(IgniteClient ignite, string name, bool keepBinary = false)
{
Debug.Assert(ignite != null);
Debug.Assert(name != null);
_name = name;
_ignite = ignite;
_marsh = _ignite.Marshaller;
_id = BinaryUtils.GetCacheId(name);
_keepBinary = keepBinary;
}
/** <inheritDoc /> */
public string Name
{
get { return _name; }
}
/** <inheritDoc /> */
public TV this[TK key]
{
get { return Get(key); }
set { Put(key, value); }
}
/** <inheritDoc /> */
public TV Get(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOp(ClientOp.CacheGet, w => w.WriteObject(key), UnmarshalNotNull<TV>);
}
/** <inheritDoc /> */
public Task<TV> GetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAsync(ClientOp.CacheGet, w => w.WriteObject(key), UnmarshalNotNull<TV>);
}
/** <inheritDoc /> */
public bool TryGet(TK key, out TV value)
{
IgniteArgumentCheck.NotNull(key, "key");
var res = DoOutInOp(ClientOp.CacheGet, w => w.WriteObject(key), UnmarshalCacheResult<TV>);
value = res.Value;
return res.Success;
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> TryGetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAsync(ClientOp.CacheGet, w => w.WriteObject(key), UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOp(ClientOp.CacheGetAll, w => w.WriteEnumerable(keys), s => ReadCacheEntries(s));
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpAsync(ClientOp.CacheGetAll, w => w.WriteEnumerable(keys), s => ReadCacheEntries(s));
}
/** <inheritDoc /> */
public void Put(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
DoOutOp(ClientOp.CachePut, w => WriteKeyVal(w, key, val));
}
/** <inheritDoc /> */
public Task PutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOpAsync(ClientOp.CachePut, w => WriteKeyVal(w, key, val));
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOp(ClientOp.CacheContainsKey, w => w.WriteObjectDetached(key), r => r.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ContainsKeyAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAsync(ClientOp.CacheContainsKey, w => w.WriteObjectDetached(key), r => r.ReadBool());
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOp(ClientOp.CacheContainsKeys, w => w.WriteEnumerable(keys), r => r.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpAsync(ClientOp.CacheContainsKeys, w => w.WriteEnumerable(keys), r => r.ReadBool());
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(ScanQuery<TK, TV> scanQuery)
{
IgniteArgumentCheck.NotNull(scanQuery, "scanQuery");
// Filter is a binary object for all platforms.
// For .NET it is a CacheEntryFilterHolder with a predefined id (BinaryTypeId.CacheEntryPredicateHolder).
return DoOutInOp(ClientOp.QueryScan, w => WriteScanQuery(w, scanQuery),
s => new ClientQueryCursor<TK, TV>(
_ignite, s.ReadLong(), _keepBinary, s, ClientOp.QueryScanCursorGetPage));
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(SqlQuery sqlQuery)
{
IgniteArgumentCheck.NotNull(sqlQuery, "sqlQuery");
IgniteArgumentCheck.NotNull(sqlQuery.Sql, "sqlQuery.Sql");
IgniteArgumentCheck.NotNull(sqlQuery.QueryType, "sqlQuery.QueryType");
return DoOutInOp(ClientOp.QuerySql, w => WriteSqlQuery(w, sqlQuery),
s => new ClientQueryCursor<TK, TV>(
_ignite, s.ReadLong(), _keepBinary, s, ClientOp.QuerySqlCursorGetPage));
}
/** <inheritDoc /> */
public IFieldsQueryCursor Query(SqlFieldsQuery sqlFieldsQuery)
{
IgniteArgumentCheck.NotNull(sqlFieldsQuery, "sqlFieldsQuery");
IgniteArgumentCheck.NotNull(sqlFieldsQuery.Sql, "sqlFieldsQuery.Sql");
return DoOutInOp(ClientOp.QuerySqlFields,
w => WriteSqlFieldsQuery(w, sqlFieldsQuery),
s => GetFieldsCursor(s));
}
/** <inheritDoc /> */
public IQueryCursor<T> Query<T>(SqlFieldsQuery sqlFieldsQuery, Func<IBinaryRawReader, int, T> readerFunc)
{
return DoOutInOp(ClientOp.QuerySqlFields,
w => WriteSqlFieldsQuery(w, sqlFieldsQuery, false),
s => GetFieldsCursorNoColumnNames(s, readerFunc));
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPut(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOp(ClientOp.CacheGetAndPut, w => WriteKeyVal(w, key, val), UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAsync(ClientOp.CacheGetAndPut, w => WriteKeyVal(w, key, val), UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndReplace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOp(ClientOp.CacheGetAndReplace, w => WriteKeyVal(w, key, val), UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAsync(ClientOp.CacheGetAndReplace, w => WriteKeyVal(w, key, val), UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndRemove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOp(ClientOp.CacheGetAndRemove, w => w.WriteObjectDetached(key),
UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndRemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAsync(ClientOp.CacheGetAndRemove, w => w.WriteObjectDetached(key),
UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public bool PutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOp(ClientOp.CachePutIfAbsent, w => WriteKeyVal(w, key, val), s => s.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> PutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAsync(ClientOp.CachePutIfAbsent, w => WriteKeyVal(w, key, val), s => s.ReadBool());
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOp(ClientOp.CacheGetAndPutIfAbsent, w => WriteKeyVal(w, key, val),
UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAsync(ClientOp.CacheGetAndPutIfAbsent, w => WriteKeyVal(w, key, val),
UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOp(ClientOp.CacheReplace, w => WriteKeyVal(w, key, val), s => s.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAsync(ClientOp.CacheReplace, w => WriteKeyVal(w, key, val), s => s.ReadBool());
}
/** <inheritDoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
return DoOutInOp(ClientOp.CacheReplaceIfEquals, w =>
{
w.WriteObjectDetached(key);
w.WriteObjectDetached(oldVal);
w.WriteObjectDetached(newVal);
}, s => s.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
return DoOutInOpAsync(ClientOp.CacheReplaceIfEquals, w =>
{
w.WriteObjectDetached(key);
w.WriteObjectDetached(oldVal);
w.WriteObjectDetached(newVal);
}, s => s.ReadBool());
}
/** <inheritDoc /> */
public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
DoOutOp(ClientOp.CachePutAll, w => w.WriteDictionary(vals));
}
/** <inheritDoc /> */
public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
return DoOutOpAsync(ClientOp.CachePutAll, w => w.WriteDictionary(vals));
}
/** <inheritDoc /> */
public void Clear()
{
DoOutOp(ClientOp.CacheClear);
}
/** <inheritDoc /> */
public Task ClearAsync()
{
return DoOutOpAsync(ClientOp.CacheClear);
}
/** <inheritDoc /> */
public void Clear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOp(ClientOp.CacheClearKey, w => w.WriteObjectDetached(key));
}
/** <inheritDoc /> */
public Task ClearAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(ClientOp.CacheClearKey, w => w.WriteObjectDetached(key));
}
/** <inheritDoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(ClientOp.CacheClearKeys, w => w.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public Task ClearAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(ClientOp.CacheClearKeys, w => w.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public bool Remove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOp(ClientOp.CacheRemoveKey, w => w.WriteObjectDetached(key), r => r.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAsync(ClientOp.CacheRemoveKey, w => w.WriteObjectDetached(key), r => r.ReadBool());
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOp(ClientOp.CacheRemoveIfEquals, w => WriteKeyVal(w, key, val), r => r.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAsync(ClientOp.CacheRemoveIfEquals, w => WriteKeyVal(w, key, val), r => r.ReadBool());
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(ClientOp.CacheRemoveKeys, w => w.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public Task RemoveAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(ClientOp.CacheRemoveKeys, w => w.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public void RemoveAll()
{
DoOutOp(ClientOp.CacheRemoveAll);
}
/** <inheritDoc /> */
public Task RemoveAllAsync()
{
return DoOutOpAsync(ClientOp.CacheRemoveAll);
}
/** <inheritDoc /> */
public long GetSize(params CachePeekMode[] modes)
{
return DoOutInOp(ClientOp.CacheGetSize, w => WritePeekModes(modes, w), s => s.ReadLong());
}
/** <inheritDoc /> */
public Task<long> GetSizeAsync(params CachePeekMode[] modes)
{
return DoOutInOpAsync(ClientOp.CacheGetSize, w => WritePeekModes(modes, w), s => s.ReadLong());
}
/** <inheritDoc /> */
public CacheClientConfiguration GetConfiguration()
{
return DoOutInOp(ClientOp.CacheGetConfiguration, null,
s => new CacheClientConfiguration(s, _ignite.ServerVersion));
}
/** <inheritDoc /> */
CacheConfiguration ICacheInternal.GetConfiguration()
{
return GetConfiguration().ToCacheConfiguration();
}
/** <inheritDoc /> */
public ICacheClient<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_keepBinary)
{
var result = this as ICacheClient<TK1, TV1>;
if (result == null)
{
throw new InvalidOperationException(
"Can't change type of binary cache. WithKeepBinary has been called on an instance of " +
"binary cache with incompatible generic arguments.");
}
return result;
}
return new CacheClient<TK1, TV1>(_ignite, _name, true);
}
/** <inheritDoc /> */
[ExcludeFromCodeCoverage]
public T DoOutInOpExtension<T>(int extensionId, int opCode, Action<IBinaryRawWriter> writeAction,
Func<IBinaryRawReader, T> readFunc)
{
// Should not be called, there are no usages for thin client.
throw IgniteClient.GetClientNotSupportedException();
}
/// <summary>
/// Does the out op.
/// </summary>
private void DoOutOp(ClientOp opId, Action<BinaryWriter> writeAction = null)
{
DoOutInOp<object>(opId, writeAction, null);
}
/// <summary>
/// Does the out op.
/// </summary>
private Task DoOutOpAsync(ClientOp opId, Action<BinaryWriter> writeAction = null)
{
return DoOutInOpAsync<object>(opId, writeAction, null);
}
/// <summary>
/// Does the out in op.
/// </summary>
private T DoOutInOp<T>(ClientOp opId, Action<BinaryWriter> writeAction,
Func<IBinaryStream, T> readFunc)
{
return _ignite.Socket.DoOutInOp(opId, stream => WriteRequest(writeAction, stream),
readFunc, HandleError<T>);
}
/// <summary>
/// Does the out in op.
/// </summary>
private Task<T> DoOutInOpAsync<T>(ClientOp opId, Action<BinaryWriter> writeAction,
Func<IBinaryStream, T> readFunc)
{
return _ignite.Socket.DoOutInOpAsync(opId, stream => WriteRequest(writeAction, stream),
readFunc, HandleError<T>);
}
/// <summary>
/// Writes the request.
/// </summary>
private void WriteRequest(Action<BinaryWriter> writeAction, IBinaryStream stream)
{
stream.WriteInt(_id);
stream.WriteByte(0); // Flags (skipStore, etc).
if (writeAction != null)
{
var writer = _marsh.StartMarshal(stream);
writeAction(writer);
_marsh.FinishMarshal(writer);
}
}
/// <summary>
/// Unmarshals the value, throwing an exception for nulls.
/// </summary>
private T UnmarshalNotNull<T>(IBinaryStream stream)
{
var hdr = stream.ReadByte();
if (hdr == BinaryUtils.HdrNull)
{
throw GetKeyNotFoundException();
}
stream.Seek(-1, SeekOrigin.Current);
return _marsh.Unmarshal<T>(stream, _keepBinary);
}
/// <summary>
/// Unmarshals the value, wrapping in a cache result.
/// </summary>
private CacheResult<T> UnmarshalCacheResult<T>(IBinaryStream stream)
{
var hdr = stream.ReadByte();
if (hdr == BinaryUtils.HdrNull)
{
return new CacheResult<T>();
}
stream.Seek(-1, SeekOrigin.Current);
return new CacheResult<T>(_marsh.Unmarshal<T>(stream, _keepBinary));
}
/// <summary>
/// Writes the scan query.
/// </summary>
private void WriteScanQuery(BinaryWriter writer, ScanQuery<TK, TV> qry)
{
Debug.Assert(qry != null);
if (qry.Filter == null)
{
writer.WriteByte(BinaryUtils.HdrNull);
}
else
{
var holder = new CacheEntryFilterHolder(qry.Filter, (key, val) => qry.Filter.Invoke(
new CacheEntry<TK, TV>((TK)key, (TV)val)), writer.Marshaller, _keepBinary);
writer.WriteObject(holder);
writer.WriteByte(FilterPlatformDotnet);
}
writer.WriteInt(qry.PageSize);
writer.WriteInt(qry.Partition ?? -1);
writer.WriteBoolean(qry.Local);
}
/// <summary>
/// Writes the SQL query.
/// </summary>
private static void WriteSqlQuery(IBinaryRawWriter writer, SqlQuery qry)
{
Debug.Assert(qry != null);
writer.WriteString(qry.QueryType);
writer.WriteString(qry.Sql);
QueryBase.WriteQueryArgs(writer, qry.Arguments);
writer.WriteBoolean(qry.EnableDistributedJoins);
writer.WriteBoolean(qry.Local);
#pragma warning disable 618
writer.WriteBoolean(qry.ReplicatedOnly);
#pragma warning restore 618
writer.WriteInt(qry.PageSize);
writer.WriteTimeSpanAsLong(qry.Timeout);
}
/// <summary>
/// Writes the SQL fields query.
/// </summary>
private static void WriteSqlFieldsQuery(IBinaryRawWriter writer, SqlFieldsQuery qry,
bool includeColumns = true)
{
Debug.Assert(qry != null);
writer.WriteString(qry.Schema);
writer.WriteInt(qry.PageSize);
writer.WriteInt(-1); // maxRows: unlimited
writer.WriteString(qry.Sql);
QueryBase.WriteQueryArgs(writer, qry.Arguments);
// .NET client does not discern between different statements for now.
// We cound have ExecuteNonQuery method, which uses StatementType.Update, for example.
writer.WriteByte((byte)StatementType.Any);
writer.WriteBoolean(qry.EnableDistributedJoins);
writer.WriteBoolean(qry.Local);
#pragma warning disable 618
writer.WriteBoolean(qry.ReplicatedOnly);
#pragma warning restore 618
writer.WriteBoolean(qry.EnforceJoinOrder);
writer.WriteBoolean(qry.Colocated);
writer.WriteBoolean(qry.Lazy);
writer.WriteTimeSpanAsLong(qry.Timeout);
writer.WriteBoolean(includeColumns);
}
/// <summary>
/// Gets the fields cursor.
/// </summary>
private ClientFieldsQueryCursor GetFieldsCursor(IBinaryStream s)
{
var cursorId = s.ReadLong();
var columnNames = ClientFieldsQueryCursor.ReadColumns(_marsh.StartUnmarshal(s));
return new ClientFieldsQueryCursor(_ignite, cursorId, _keepBinary, s,
ClientOp.QuerySqlFieldsCursorGetPage, columnNames);
}
/// <summary>
/// Gets the fields cursor.
/// </summary>
private ClientQueryCursorBase<T> GetFieldsCursorNoColumnNames<T>(IBinaryStream s,
Func<IBinaryRawReader, int, T> readerFunc)
{
var cursorId = s.ReadLong();
var columnCount = s.ReadInt();
return new ClientQueryCursorBase<T>(_ignite, cursorId, _keepBinary, s,
ClientOp.QuerySqlFieldsCursorGetPage, r => readerFunc(r, columnCount));
}
/// <summary>
/// Handles the error.
/// </summary>
private T HandleError<T>(ClientStatusCode status, string msg)
{
switch (status)
{
case ClientStatusCode.CacheDoesNotExist:
throw new IgniteClientException("Cache doesn't exist: " + Name, null, status);
default:
throw new IgniteClientException(msg, null, status);
}
}
/// <summary>
/// Gets the key not found exception.
/// </summary>
private static KeyNotFoundException GetKeyNotFoundException()
{
return new KeyNotFoundException("The given key was not present in the cache.");
}
/// <summary>
/// Writes the peek modes.
/// </summary>
private static void WritePeekModes(ICollection<CachePeekMode> modes, IBinaryRawWriter w)
{
if (modes == null)
{
w.WriteInt(0);
}
else
{
w.WriteInt(modes.Count);
foreach (var m in modes)
{
// Convert bit flag to ordinal.
byte val = 0;
var flagVal = (int)m;
while ((flagVal = flagVal >> 1) > 0)
{
val++;
}
w.WriteByte(val);
}
}
}
/// <summary>
/// Reads the cache entries.
/// </summary>
private ICollection<ICacheEntry<TK, TV>> ReadCacheEntries(IBinaryStream stream)
{
var reader = _marsh.StartUnmarshal(stream, _keepBinary);
var cnt = reader.ReadInt();
var res = new List<ICacheEntry<TK, TV>>(cnt);
for (var i = 0; i < cnt; i++)
{
res.Add(new CacheEntry<TK, TV>(reader.ReadObject<TK>(), reader.ReadObject<TV>()));
}
return res;
}
/// <summary>
/// Writes key and value.
/// </summary>
private static void WriteKeyVal(BinaryWriter w, TK key, TV val)
{
w.WriteObjectDetached(key);
w.WriteObjectDetached(val);
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public sealed partial class ImplementInternalMethods
{
//
// Helper Methods
//
private void ImplementDelegateMethods( MethodRepresentation md )
{
if(TypeSystemForCodeTransformation.GetCodeForMethod( md ) == null)
{
ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_typeSystem.CreateControlFlowGraphState( md );
WellKnownTypes wkt = m_typeSystem.WellKnownTypes;
WellKnownMethods wkm = m_typeSystem.WellKnownMethods;
WellKnownFields wkf = m_typeSystem.WellKnownFields;
if(md is ConstructorMethodRepresentation)
{
var bb = cfg.CreateFirstNormalBasicBlock();
md.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline;
md.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline;
//
// Create proper flow control for exit basic block.
//
cfg.AddReturnOperator();
//
// Call the base method.
//
MethodRepresentation mdParent = wkm.MulticastDelegateImpl_MulticastDelegateImpl;
Expression[] rhs = new Expression[cfg.Arguments.Length];
for(int i = 0; i < cfg.Arguments.Length; i++)
{
rhs[i] = cfg.Arguments[i];
}
bb.AddOperator( InstanceCallOperator.New( null, CallOperator.CallKind.OverriddenNoCheck, mdParent, rhs, true ) );
}
else if(md.Name == "Invoke")
{
var bb = cfg.CreateFirstNormalBasicBlock();
BasicBlock bbExit;
Expression[] rhs;
VariableExpression exReturnValue;
//
// Create proper flow control for exit basic block.
//
ReturnControlOperator opRet;
if(cfg.ReturnValue != null)
{
opRet = ReturnControlOperator.New( cfg.ReturnValue );
//--//
exReturnValue = cfg.AllocateLocal( cfg.ReturnValue.Type, null );
Operator op = cfg.GenerateVariableInitialization( null, exReturnValue );
cfg.GetInjectionPoint( BasicBlock.Qualifier.PrologueEnd ).AddOperator( op );
//--//
bbExit = cfg.CreateLastNormalBasicBlock();
bbExit.AddOperator( SingleAssignmentOperator.New( null, cfg.ReturnValue, exReturnValue ) );
}
else
{
opRet = ReturnControlOperator.New();
//--//
exReturnValue = null;
//--//
bbExit = cfg.NormalizedExitBasicBlock;
}
cfg.ExitBasicBlock.AddOperator( opRet );
//
// This is the code we need to implement:
//
// DelegateImpl[] invocationList = m_invocationList;
//
// if(invocationList == null)
// {
// res = Invoke( ... );
// }
// else
// {
// int len = invocationList.Length;
//
// for(int i = 0; i < len; i++)
// {
// res = invocationList[i].Invoke( ... );
// }
// }
//
//
FieldRepresentation fdInvocationList = wkf.MulticastDelegateImpl_m_invocationList;
FieldRepresentation fdTarget = wkf.DelegateImpl_m_target;
FieldRepresentation fdCodePtr = wkf.DelegateImpl_m_codePtr;
VariableExpression exInvocationList = cfg.AllocateTemporary( fdInvocationList.FieldType , null );
VariableExpression exInvocation = cfg.AllocateTemporary( fdInvocationList.FieldType.ContainedType, null );
VariableExpression exTarget = cfg.AllocateTemporary( fdTarget .FieldType , null );
VariableExpression exCodePtr = cfg.AllocateTemporary( fdCodePtr .FieldType , null );
VariableExpression exLen = cfg.AllocateTemporary( wkt.System_Int32 , null );
VariableExpression exPos = cfg.AllocateTemporary( wkt.System_Int32 , null );
VariableExpression exThis = cfg.Arguments[0];
//--//
//
// DelegateImpl[] invocationList = m_invocationList;
//
// if(invocationList == null)
// {
// <NullBranch>
// }
// else
// {
// <NotNullBranch>
// }
//
NormalBasicBlock bbNull = new NormalBasicBlock( cfg );
NormalBasicBlock bbNotNull = new NormalBasicBlock( cfg );
bb.AddOperator( LoadInstanceFieldOperator.New( null, fdInvocationList, exInvocationList, exThis, true ) );
bb.FlowControl = BinaryConditionalControlOperator.New( null, exInvocationList, bbNull, bbNotNull );
//--//
//
// <NullBranch>
//
// {
// object target = m_target;
// CodePtr codePtr = m_codePtr;
//
// <returnValue> = IndirectCall<codePtr>( target, <arguments> );
// }
//
bbNull.AddOperator( LoadInstanceFieldOperator.New( null, fdTarget , exTarget , exThis, true ) );
bbNull.AddOperator( LoadInstanceFieldOperator.New( null, fdCodePtr, exCodePtr, exThis, true ) );
rhs = new Expression[cfg.Arguments.Length + 1];
rhs[0] = exCodePtr;
rhs[1] = exTarget;
for(int i = 1; i < cfg.Arguments.Length; i++)
{
rhs[i+1] = cfg.Arguments[i];
}
bbNull.AddOperator( IndirectCallOperator.New( null, md, VariableExpression.ToArray( exReturnValue ), rhs, false ) );
bbNull.AddOperator( UnconditionalControlOperator.New( null, bbExit ) );
//
// <NotNullBranch>
//
// {
// int len = invocationList.Length;
//
// for(int pos = 0; pos < len; pos++)
// {
// DelegateImpl invocation = invocationList[i];
//
// res = invocation.Invoke( ... );
// }
// }
NormalBasicBlock bbNotNullCheck = new NormalBasicBlock( cfg );
NormalBasicBlock bbNotNullInner = new NormalBasicBlock( cfg );
bbNotNull.AddOperator( ArrayLengthOperator .New( null, exLen, exInvocationList ) );
bbNotNull.AddOperator( SingleAssignmentOperator .New( null, exPos, m_typeSystem.CreateConstant( (int)0 ) ) );
bbNotNull.AddOperator( UnconditionalControlOperator.New( null, bbNotNullCheck ) );
//--//
bbNotNullCheck.AddOperator( CompareConditionalControlOperator.New( null, CompareAndSetOperator.ActionCondition.LT, true, exPos, exLen, bbExit, bbNotNullInner ) );
//--//
bbNotNullInner.AddOperator( LoadElementOperator .New( null, exInvocation, exInvocationList, exPos, null, true ) );
bbNotNullInner.AddOperator( LoadInstanceFieldOperator.New( null, fdTarget , exTarget , exInvocation, true ) );
bbNotNullInner.AddOperator( LoadInstanceFieldOperator.New( null, fdCodePtr, exCodePtr, exInvocation, true ) );
rhs = new Expression[cfg.Arguments.Length + 1];
rhs[0] = exCodePtr;
rhs[1] = exTarget;
for(int i = 1; i < cfg.Arguments.Length; i++)
{
rhs[i+1] = cfg.Arguments[i];
}
bbNotNullInner.AddOperator( IndirectCallOperator.New( null, md, VariableExpression.ToArray( exReturnValue ), rhs, false ) );
bbNotNullInner.AddOperator( BinaryOperator.New( null, BinaryOperator.ALU.ADD, true, false, exPos, exPos, m_typeSystem.CreateConstant( (int)1 ) ) );
bbNotNullInner.AddOperator( UnconditionalControlOperator.New( null, bbNotNullCheck ) );
}
else
{
var bb = cfg.CreateFirstNormalBasicBlock();
MethodRepresentation mdThrow = wkm.ThreadImpl_ThrowNotImplementedException;
Expression[] rhs = m_typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdThrow );
bb.AddOperator( StaticCallOperator.New( null, CallOperator.CallKind.Direct, mdThrow, rhs ) );
cfg.ExitBasicBlock.AddOperator( DeadControlOperator.New( null ) );
}
}
}
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
public abstract class DockPaneStripBase : Control
{
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
protected internal class Tab : IDisposable
{
private IDockContent m_content;
public Tab(IDockContent content)
{
m_content = content;
}
~Tab()
{
Dispose(false);
}
public IDockContent Content
{
get { return m_content; }
}
public Form ContentForm
{
get { return m_content as Form; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
protected sealed class TabCollection : IEnumerable<Tab>
{
#region IEnumerable Members
IEnumerator<Tab> IEnumerable<Tab>.GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
#endregion
internal TabCollection(DockPane pane)
{
m_dockPane = pane;
}
private DockPane m_dockPane;
public DockPane DockPane
{
get { return m_dockPane; }
}
public int Count
{
get { return DockPane.DisplayingContents.Count; }
}
public Tab this[int index]
{
get
{
IDockContent content = DockPane.DisplayingContents[index];
if (content == null)
throw (new ArgumentOutOfRangeException("index"));
return content.DockHandler.GetTab(DockPane.TabStripControl);
}
}
public bool Contains(Tab tab)
{
return (IndexOf(tab) != -1);
}
public bool Contains(IDockContent content)
{
return (IndexOf(content) != -1);
}
public int IndexOf(Tab tab)
{
if (tab == null)
return -1;
return DockPane.DisplayingContents.IndexOf(tab.Content);
}
public int IndexOf(IDockContent content)
{
return DockPane.DisplayingContents.IndexOf(content);
}
}
protected DockPaneStripBase(DockPane pane)
{
m_dockPane = pane;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.Selectable, false);
AllowDrop = true;
}
private DockPane m_dockPane;
protected DockPane DockPane
{
get { return m_dockPane; }
}
protected DockPane.AppearanceStyle Appearance
{
get { return DockPane.Appearance; }
}
private TabCollection m_tabs = null;
protected TabCollection Tabs
{
get
{
if (m_tabs == null)
m_tabs = new TabCollection(DockPane);
return m_tabs;
}
}
internal void RefreshChanges()
{
OnRefreshChanges();
}
protected virtual void OnRefreshChanges()
{
}
protected internal abstract int MeasureHeight();
protected internal abstract void EnsureTabVisible(IDockContent content);
protected int HitTest()
{
return HitTest(PointToClient(Control.MousePosition));
}
protected internal abstract int HitTest(Point point);
protected internal abstract GraphicsPath GetOutline(int index);
protected internal virtual Tab CreateTab(IDockContent content)
{
return new Tab(content);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
int index = HitTest();
if (index != -1)
{
IDockContent content = Tabs[index].Content;
if (DockPane.ActiveContent != content)
DockPane.ActiveContent = content;
}
if (e.Button == MouseButtons.Left)
{
if (DockPane.DockPanel.AllowEndUserDocking && DockPane.AllowDockDragAndDrop && DockPane.ActiveContent.DockHandler.AllowEndUserDocking)
DockPane.DockPanel.BeginDrag(DockPane.ActiveContent.DockHandler);
}
}
protected bool HasTabPageContextMenu
{
get { return DockPane.HasTabPageContextMenu; }
}
protected void ShowTabPageContextMenu(Point position)
{
DockPane.ShowTabPageContextMenu(this, position);
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button == MouseButtons.Right)
ShowTabPageContextMenu(new Point(e.X, e.Y));
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)Win32.Msgs.WM_LBUTTONDBLCLK)
{
base.WndProc(ref m);
int index = HitTest();
if (DockPane.DockPanel.AllowEndUserDocking && index != -1)
{
IDockContent content = Tabs[index].Content;
if (content.DockHandler.CheckDockState(!content.DockHandler.IsFloat) != DockState.Unknown)
content.DockHandler.IsFloat = !content.DockHandler.IsFloat;
}
return;
}
base.WndProc(ref m);
return;
}
protected override void OnDragOver(DragEventArgs drgevent)
{
base.OnDragOver(drgevent);
int index = HitTest();
if (index != -1)
{
IDockContent content = Tabs[index].Content;
if (DockPane.ActiveContent != content)
DockPane.ActiveContent = content;
}
}
}
}
| |
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using Messir.Windows.Forms;
namespace Bloom.Workspace
{
/// <summary>
/// Represents a renderer class for TabStrip control
/// </summary>
internal class TabStripRenderer : ToolStripRenderer
{
private const int selOffset = 2;
private ToolStripRenderer _currentRenderer = null;
private ToolStripRenderMode _renderMode = ToolStripRenderMode.Custom;
private bool _mirrored = false;
private bool _useVisualStyles = Application.RenderWithVisualStyles;
/// <summary>
/// Gets or sets render mode for this renderer
/// </summary>
public ToolStripRenderMode RenderMode
{
get { return _renderMode; }
set
{
_renderMode = value;
switch (_renderMode)
{
case ToolStripRenderMode.Professional:
_currentRenderer = new ToolStripProfessionalRenderer();
break;
case ToolStripRenderMode.System:
_currentRenderer = new ToolStripSystemRenderer();
break;
default:
_currentRenderer = null;
break;
}
}
}
/// <summary>
/// Gets or sets whether to mirror background
/// </summary>
/// <remarks>Use false for left and top positions, true for right and bottom</remarks>
public bool Mirrored
{
get { return _mirrored; }
set { _mirrored = value; }
}
/// <summary>
/// Returns if visual styles should be applied for drawing
/// </summary>
public bool UseVisualStyles
{
get { return _useVisualStyles; }
set
{
if (value && !Application.RenderWithVisualStyles)
return;
_useVisualStyles = value;
}
}
protected override void Initialize(ToolStrip ts)
{
base.Initialize(ts);
}
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e)
{
return;
Color c = SystemColors.AppWorkspace;
if (UseVisualStyles)
{
VisualStyleRenderer rndr = new VisualStyleRenderer(VisualStyleElement.Tab.Pane.Normal);
c = rndr.GetColor(ColorProperty.BorderColorHint);
}
using (Pen p = new Pen(c))
using (Pen p2 = new Pen(e.BackColor))
{
Rectangle r = e.ToolStrip.Bounds;
int x1 = (Mirrored) ? 0 : r.Width - 1 - e.ToolStrip.Padding.Horizontal;
int y1 = (Mirrored) ? 0 : r.Height - 1;
if (e.ToolStrip.Orientation == Orientation.Horizontal)
e.Graphics.DrawLine(p, 0, y1, r.Width, y1);
else
{
e.Graphics.DrawLine(p, x1, 0, x1, r.Height);
if (!Mirrored)
for (int i = x1 + 1; i < r.Width; i++)
e.Graphics.DrawLine(p2, i, 0, i, r.Height);
}
foreach (ToolStripItem x in e.ToolStrip.Items)
{
if (x.IsOnOverflow) continue;
TabStripButton btn = x as TabStripButton;
if (btn == null) continue;
Rectangle rc = btn.Bounds;
int x2 = (Mirrored) ? rc.Left : rc.Right;
int y2 = (Mirrored) ? rc.Top : rc.Bottom - 1;
int addXY = (Mirrored) ? 0 : 1;
if (e.ToolStrip.Orientation == Orientation.Horizontal)
{
e.Graphics.DrawLine(p, rc.Left, y2, rc.Right, y2);
if (btn.Checked) e.Graphics.DrawLine(p2, rc.Left + 2 - addXY, y2, rc.Right - 2 - addXY, y2);
}
else
{
e.Graphics.DrawLine(p, x2, rc.Top, x2, rc.Bottom);
if (btn.Checked) e.Graphics.DrawLine(p2, x2, rc.Top + 2 - addXY, x2, rc.Bottom - 2 - addXY);
}
}
}
}
protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e)
{
if (_currentRenderer != null)
{
_currentRenderer.DrawToolStripBackground(e);
return;
}
if (SIL.PlatformUtilities.Platform.IsWindows)
{
base.OnRenderToolStripBackground(e);
return;
}
// there is no handler for this event in mono, so we need to handle it here.
var b = new SolidBrush(e.ToolStrip.BackColor);
e.Graphics.FillRectangle(b, e.AffectedBounds);
}
protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e)
{
Graphics g = e.Graphics;
TabStrip tabs = e.ToolStrip as TabStrip;
TabStripButton tab = e.Item as TabStripButton;
if (tabs == null || tab == null)
{
if (_currentRenderer != null)
_currentRenderer.DrawButtonBackground(e);
else
base.OnRenderButtonBackground(e);
return;
}
bool selected = tab.Checked;
bool hovered = tab.Selected;
int top = 0;
int left = 0;
int width = tab.Bounds.Width - 1;
int height = tab.Bounds.Height - 1;
Rectangle drawBorder;
//
// if (UseVisualStyles)
// {
// if (tabs.Orientation == Orientation.Horizontal)
// {
// if (!selected)
// {
// top = selOffset;
// height -= (selOffset - 1);
// }
// else
// top = 1;
// drawBorder = new Rectangle(0, 0, width, height);
// }
// else
// {
// if (!selected)
// {
// left = selOffset;
// width -= (selOffset - 1);
// }
// else
// left = 1;
// drawBorder = new Rectangle(0, 0, height, width);
// }
// using (Bitmap b = new Bitmap(drawBorder.Width, drawBorder.Height))
// {
// VisualStyleElement el = VisualStyleElement.Tab.TabItem.Normal;
// if (selected)
// el = VisualStyleElement.Tab.TabItem.Pressed;
// if (hovered)
// el = VisualStyleElement.Tab.TabItem.Hot;
// if (!tab.Enabled)
// el = VisualStyleElement.Tab.TabItem.Disabled;
//
// if (!selected || hovered) drawBorder.Width++; else drawBorder.Height++;
//
// using (Graphics gr = Graphics.FromImage(b))
// {
// VisualStyleRenderer rndr = new VisualStyleRenderer(el);
// rndr.DrawBackground(gr, drawBorder);
//
// if (tabs.Orientation == Orientation.Vertical)
// {
// if (Mirrored)
// b.RotateFlip(RotateFlipType.Rotate270FlipXY);
// else
// b.RotateFlip(RotateFlipType.Rotate270FlipNone);
// }
// else
// {
// if (Mirrored)
// b.RotateFlip(RotateFlipType.RotateNoneFlipY);
// }
// if (Mirrored)
// {
// left = tab.Bounds.Width - b.Width - left;
// top = tab.Bounds.Height - b.Height - top;
// }
// g.DrawImage(b, left, top);
// }
// }
// }
// else
{
if (tabs.Orientation == Orientation.Horizontal)
{
if (!selected)
{
top = selOffset;
height -= (selOffset - 1);
}
else
top = 1;
if (Mirrored)
{
left = 1;
top = 0;
}
else
top++;
width--;
}
// else
// {
// if (!selected)
// {
// left = selOffset;
// width--;
// }
// else
// left = 1;
// if (Mirrored)
// {
// left = 0;
// top = 1;
// }
// }
height--;
drawBorder = new Rectangle(left, top, width, height);
using (GraphicsPath gp = new GraphicsPath())
{
// if (Mirrored && tabs.Orientation == Orientation.Horizontal)
// {
// gp.AddLine(drawBorder.Left, drawBorder.Top, drawBorder.Left, drawBorder.Bottom - 2);
// gp.AddArc(drawBorder.Left, drawBorder.Bottom - 3, 2, 2, 90, 90);
// gp.AddLine(drawBorder.Left + 2, drawBorder.Bottom, drawBorder.Right - 2, drawBorder.Bottom);
// gp.AddArc(drawBorder.Right - 2, drawBorder.Bottom - 3, 2, 2, 0, 90);
// gp.AddLine(drawBorder.Right, drawBorder.Bottom - 2, drawBorder.Right, drawBorder.Top);
// }
//else
if (!Mirrored && tabs.Orientation == Orientation.Horizontal)
{
gp.AddLine(drawBorder.Left, drawBorder.Bottom, drawBorder.Left, drawBorder.Top + 2);
gp.AddArc(drawBorder.Left, drawBorder.Top + 1, 2, 2, 180, 90);
gp.AddLine(drawBorder.Left + 2, drawBorder.Top, drawBorder.Right - 2, drawBorder.Top);
gp.AddArc(drawBorder.Right - 2, drawBorder.Top + 1, 2, 2, 270, 90);
gp.AddLine(drawBorder.Right, drawBorder.Top + 2, drawBorder.Right, drawBorder.Bottom);
}
// else if (Mirrored && tabs.Orientation == Orientation.Vertical)
// {
// gp.AddLine(drawBorder.Left, drawBorder.Top, drawBorder.Right - 2, drawBorder.Top);
// gp.AddArc(drawBorder.Right - 2, drawBorder.Top + 1, 2, 2, 270, 90);
// gp.AddLine(drawBorder.Right, drawBorder.Top + 2, drawBorder.Right, drawBorder.Bottom - 2);
// gp.AddArc(drawBorder.Right - 2, drawBorder.Bottom - 3, 2, 2, 0, 90);
// gp.AddLine(drawBorder.Right - 2, drawBorder.Bottom, drawBorder.Left, drawBorder.Bottom);
// }
// else
// {
// gp.AddLine(drawBorder.Right, drawBorder.Top, drawBorder.Left + 2, drawBorder.Top);
// gp.AddArc(drawBorder.Left, drawBorder.Top + 1, 2, 2, 180, 90);
// gp.AddLine(drawBorder.Left, drawBorder.Top + 2, drawBorder.Left, drawBorder.Bottom - 2);
// gp.AddArc(drawBorder.Left, drawBorder.Bottom - 3, 2, 2, 90, 90);
// gp.AddLine(drawBorder.Left + 2, drawBorder.Bottom, drawBorder.Right, drawBorder.Bottom);
// }
if (selected || hovered)
{
Color fill = (hovered) ? Palette.TextAgainstDarkBackground : Color.FromArgb(64, 64, 64);
if (_renderMode == ToolStripRenderMode.Professional)
{
fill = (hovered) ? ProfessionalColors.ButtonCheckedGradientBegin : ProfessionalColors.ButtonCheckedGradientEnd;
using (LinearGradientBrush br = new LinearGradientBrush(tab.ContentRectangle, fill, ProfessionalColors.ButtonCheckedGradientMiddle, LinearGradientMode.Vertical))
g.FillPath(br, gp);
}
else
using (SolidBrush br = new SolidBrush(fill))
g.FillPath(br, gp);
}
else
{
using (SolidBrush br = new SolidBrush(e.Item.BackColor))
g.FillPath(br, gp);
}
// using (Pen p = new Pen((selected) ? ControlPaint.Dark(SystemColors.AppWorkspace) : SystemColors.AppWorkspace))
// g.DrawPath(p, gp);
g.DrawPath(Pens.Black, gp);
}
}
}
protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e)
{
TabStripButton btn = e.Item as TabStripButton;
var rect = e.ImageRectangle;
if (btn != null)
{
// adjust the image position up for Linux
if (SIL.PlatformUtilities.Platform.IsLinux)
{
if (e.ToolStrip.Orientation == Orientation.Horizontal)
rect.Offset(0, -4);
}
else
{
var delta = ((Mirrored) ? -1 : 1) * ((btn.Checked) ? 1 : selOffset);
if (e.ToolStrip.Orientation == Orientation.Horizontal)
rect.Offset((Mirrored) ? 2 : 1, delta + ((Mirrored) ? 1 : 0));
else
rect.Offset(delta + 2, 0);
}
}
ToolStripItemImageRenderEventArgs x =
new ToolStripItemImageRenderEventArgs(e.Graphics, e.Item, e.Image, rect);
if (_currentRenderer != null)
_currentRenderer.DrawItemImage(x);
else
base.OnRenderItemImage(x);
}
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
// set the font before calculating the size because bold text is being cut off in Linux.
TabStripButton btn = e.Item as TabStripButton;
if ((btn != null) && btn.Checked)
e.TextFont = btn.SelectedFont;
e.SizeTextRectangleToText();
// adjust the text position up for Linux
var rect = e.TextRectangle;
if (SIL.PlatformUtilities.Platform.IsLinux)
rect.Offset(0, -2);
else
rect.Offset(0, 8); // hatton for bloom lower is better
if (btn != null)
{
var delta = ((Mirrored) ? -1 : 1) * ((btn.Checked) ? 1 : selOffset);
if (e.ToolStrip.Orientation == Orientation.Horizontal)
rect.Offset((Mirrored) ? 2 : 1, delta + ((Mirrored) ? 1 : -1));
else
rect.Offset(delta + 2, 0);
if (btn.Selected)
e.TextColor = btn.HotTextColor;
else if (btn.Checked)
e.TextColor = btn.SelectedTextColor;
}
e.TextRectangle = rect;
if (_currentRenderer != null)
_currentRenderer.DrawItemText(e);
else
base.OnRenderItemText(e);
}
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawArrow(e);
else
base.OnRenderArrow(e);
}
protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawDropDownButtonBackground(e);
else
base.OnRenderDropDownButtonBackground(e);
}
protected override void OnRenderGrip(ToolStripGripRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawGrip(e);
else
base.OnRenderGrip(e);
}
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawImageMargin(e);
else
base.OnRenderImageMargin(e);
}
protected override void OnRenderItemBackground(ToolStripItemRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawItemBackground(e);
else
{
//base.OnRenderItemBackground(e);
e.Graphics.FillRectangle(Brushes.BlueViolet, e.Item.ContentRectangle);
}
}
protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawItemCheck(e);
else
base.OnRenderItemCheck(e);
}
protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawLabelBackground(e);
else
base.OnRenderLabelBackground(e);
}
protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawMenuItemBackground(e);
else
base.OnRenderMenuItemBackground(e);
}
protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawOverflowButtonBackground(e);
else
base.OnRenderOverflowButtonBackground(e);
}
protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawSeparator(e);
else
base.OnRenderSeparator(e);
}
protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawSplitButton(e);
else
base.OnRenderSplitButtonBackground(e);
}
protected override void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawStatusStripSizingGrip(e);
else
base.OnRenderStatusStripSizingGrip(e);
}
protected override void OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawToolStripContentPanelBackground(e);
else
base.OnRenderToolStripContentPanelBackground(e);
}
protected override void OnRenderToolStripPanelBackground(ToolStripPanelRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawToolStripPanelBackground(e);
else
base.OnRenderToolStripPanelBackground(e);
}
protected override void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e)
{
if (_currentRenderer != null)
_currentRenderer.DrawToolStripStatusLabelBackground(e);
else
base.OnRenderToolStripStatusLabelBackground(e);
}
}
}
| |
// 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.Tasks;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.Text;
using Moq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests
{
public class InteractiveWindowTests : IDisposable
{
#region Helpers
private InteractiveWindowTestHost _testHost;
private List<InteractiveWindow.State> _states;
public InteractiveWindowTests()
{
_states = new List<InteractiveWindow.State>();
_testHost = new InteractiveWindowTestHost(_states.Add);
}
public void Dispose()
{
_testHost.Dispose();
}
public IInteractiveWindow Window
{
get
{
return _testHost.Window;
}
}
public static IEnumerable<IInteractiveWindowCommand> MockCommands(params string[] commandNames)
{
foreach (var name in commandNames)
{
var mock = new Mock<IInteractiveWindowCommand>();
mock.Setup(m => m.Names).Returns(new[] { name });
yield return mock.Object;
}
}
public static ITextSnapshot MockSnapshot(string content)
{
var snapshotMock = new Mock<ITextSnapshot>();
snapshotMock.Setup(m => m[It.IsAny<int>()]).Returns<int>(index => content[index]);
snapshotMock.Setup(m => m.Length).Returns(content.Length);
snapshotMock.Setup(m => m.GetText()).Returns(content);
snapshotMock.Setup(m => m.GetText(It.IsAny<int>(), It.IsAny<int>())).Returns<int, int>((start, length) => content.Substring(start, length));
snapshotMock.Setup(m => m.GetText(It.IsAny<Span>())).Returns<Span>(span => content.Substring(span.Start, span.Length));
return snapshotMock.Object;
}
#endregion
[Fact]
public void InteractiveWindow__CommandParsing()
{
var commandList = MockCommands("foo", "bar", "bz", "command1").ToArray();
var commands = new Commands.Commands(null, "%", commandList);
AssertEx.Equal(commands.GetCommands(), commandList);
var cmdBar = commandList[1];
Assert.Equal("bar", cmdBar.Names.First());
Assert.Equal("%", commands.CommandPrefix);
commands.CommandPrefix = "#";
Assert.Equal("#", commands.CommandPrefix);
//// 111111
//// 0123456789012345
var s1 = MockSnapshot("#bar arg1 arg2 ");
SnapshotSpan prefixSpan, commandSpan, argsSpan;
IInteractiveWindowCommand cmd;
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 0)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 1)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 2)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(2, commandSpan.End);
Assert.Equal(2, argsSpan.Start);
Assert.Equal(2, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 3)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(3, commandSpan.End);
Assert.Equal(3, argsSpan.Start);
Assert.Equal(3, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 4)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(4, argsSpan.Start);
Assert.Equal(4, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 5)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(5, argsSpan.Start);
Assert.Equal(5, argsSpan.End);
cmd = commands.TryParseCommand(s1.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(5, argsSpan.Start);
Assert.Equal(14, argsSpan.End);
////
//// 0123456789
var s2 = MockSnapshot(" #bar ");
cmd = commands.TryParseCommand(s2.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(2, prefixSpan.Start);
Assert.Equal(3, prefixSpan.End);
Assert.Equal(3, commandSpan.Start);
Assert.Equal(6, commandSpan.End);
Assert.Equal(9, argsSpan.Start);
Assert.Equal(9, argsSpan.End);
//// 111111
//// 0123456789012345
var s3 = MockSnapshot(" # bar args");
cmd = commands.TryParseCommand(s3.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(2, prefixSpan.Start);
Assert.Equal(3, prefixSpan.End);
Assert.Equal(6, commandSpan.Start);
Assert.Equal(9, commandSpan.End);
Assert.Equal(11, argsSpan.Start);
Assert.Equal(15, argsSpan.End);
}
[Fact]
public void InteractiveWindow_GetCommands()
{
var interactiveCommands = new InteractiveCommandsFactory(null, null).CreateInteractiveCommands(
Window,
"#",
_testHost.ExportProvider.GetExports<IInteractiveWindowCommand>().Select(x => x.Value).ToArray());
var commands = interactiveCommands.GetCommands();
Assert.NotEmpty(commands);
Assert.Equal(2, commands.Where(n => n.Names.First() == "cls").Count());
Assert.Equal(2, commands.Where(n => n.Names.Last() == "clear").Count());
Assert.NotNull(commands.Where(n => n.Names.First() == "help").SingleOrDefault());
Assert.NotNull(commands.Where(n => n.Names.First() == "reset").SingleOrDefault());
}
[WorkItem(3970, "https://github.com/dotnet/roslyn/issues/3970")]
[Fact]
public void ResetStateTransitions()
{
Window.Operations.ResetAsync().PumpingWait();
Assert.Equal(_states, new[]
{
InteractiveWindow.State.Initializing,
InteractiveWindow.State.WaitingForInput,
InteractiveWindow.State.Resetting,
});
}
[Fact]
public void DoubleInitialize()
{
try
{
Window.InitializeAsync().PumpingWait();
Assert.True(false);
}
catch (AggregateException e)
{
Assert.IsType<InvalidOperationException>(e.InnerExceptions.Single());
}
}
[Fact]
public void AccessPropertiesOnUIThread()
{
foreach (var property in typeof(IInteractiveWindow).GetProperties())
{
Assert.Null(property.SetMethod);
property.GetMethod.Invoke(Window, Array.Empty<object>());
}
Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties());
}
[Fact]
public void AccessPropertiesOnNonUIThread()
{
foreach (var property in typeof(IInteractiveWindow).GetProperties())
{
Assert.Null(property.SetMethod);
Task.Run(() => property.GetMethod.Invoke(Window, Array.Empty<object>())).PumpingWait();
}
Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties());
}
/// <remarks>
/// Confirm that we are, in fact, running on a non-UI thread.
/// </remarks>
[Fact]
public void NonUIThread()
{
Task.Run(() => Assert.False(((InteractiveWindow)Window).OnUIThread())).PumpingWait();
}
[Fact]
public void CallCloseOnNonUIThread()
{
Task.Run(() => Window.Close()).PumpingWait();
}
[Fact]
public void CallInsertCodeOnNonUIThread()
{
// TODO (https://github.com/dotnet/roslyn/issues/3984): InsertCode is a no-op unless standard input is being collected.
Task.Run(() => Window.InsertCode("1")).PumpingWait();
}
[Fact]
public void CallSubmitAsyncOnNonUIThread()
{
Task.Run(() => Window.SubmitAsync(Array.Empty<string>()).GetAwaiter().GetResult()).PumpingWait();
}
[Fact]
public void CallWriteOnNonUIThread()
{
Task.Run(() => Window.WriteLine("1")).PumpingWait();
Task.Run(() => Window.Write("1")).PumpingWait();
Task.Run(() => Window.WriteErrorLine("1")).PumpingWait();
Task.Run(() => Window.WriteError("1")).PumpingWait();
}
[Fact]
public void CallFlushOutputOnNonUIThread()
{
Window.Write("1"); // Something to flush.
Task.Run(() => Window.FlushOutput()).PumpingWait();
}
[Fact]
public void CallAddInputOnNonUIThread()
{
Task.Run(() => Window.AddInput("1")).PumpingWait();
}
/// <remarks>
/// Call is blocking, so we can't write a simple non-failing test.
/// </remarks>
[Fact]
public void CallReadStandardInputOnUIThread()
{
Assert.Throws<InvalidOperationException>(() => Window.ReadStandardInput());
}
[Fact]
public void CallBackspaceOnNonUIThread()
{
Window.InsertCode("1"); // Something to backspace.
Task.Run(() => Window.Operations.Backspace()).PumpingWait();
}
[Fact]
public void CallBreakLineOnNonUIThread()
{
Task.Run(() => Window.Operations.BreakLine()).PumpingWait();
}
[Fact]
public void CallClearHistoryOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
Task.Run(() => Window.Operations.ClearHistory()).PumpingWait();
}
[Fact]
public void CallClearViewOnNonUIThread()
{
Window.InsertCode("1"); // Something to clear.
Task.Run(() => Window.Operations.ClearView()).PumpingWait();
}
[Fact]
public void CallHistoryNextOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
Task.Run(() => Window.Operations.HistoryNext()).PumpingWait();
}
[Fact]
public void CallHistoryPreviousOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
Task.Run(() => Window.Operations.HistoryPrevious()).PumpingWait();
}
[Fact]
public void CallHistorySearchNextOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
Task.Run(() => Window.Operations.HistorySearchNext()).PumpingWait();
}
[Fact]
public void CallHistorySearchPreviousOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
Task.Run(() => Window.Operations.HistorySearchPrevious()).PumpingWait();
}
[Fact]
public void CallHomeOnNonUIThread()
{
Window.Operations.BreakLine(); // Distinguish Home from End.
Task.Run(() => Window.Operations.Home(true)).PumpingWait();
}
[Fact]
public void CallEndOnNonUIThread()
{
Window.Operations.BreakLine(); // Distinguish Home from End.
Task.Run(() => Window.Operations.End(true)).PumpingWait();
}
[Fact]
public void CallSelectAllOnNonUIThread()
{
Window.InsertCode("1"); // Something to select.
Task.Run(() => Window.Operations.SelectAll()).PumpingWait();
}
[Fact]
public void CallPasteOnNonUIThread()
{
Task.Run(() => Window.Operations.Paste()).PumpingWait();
}
[Fact]
public void CallCutOnNonUIThread()
{
Task.Run(() => Window.Operations.Cut()).PumpingWait();
}
[Fact]
public void CallDeleteOnNonUIThread()
{
Task.Run(() => Window.Operations.Delete()).PumpingWait();
}
[Fact]
public void CallReturnOnNonUIThread()
{
Task.Run(() => Window.Operations.Return()).PumpingWait();
}
[Fact]
public void CallTrySubmitStandardInputOnNonUIThread()
{
Task.Run(() => Window.Operations.TrySubmitStandardInput()).PumpingWait();
}
[Fact]
public void CallResetAsyncOnNonUIThread()
{
Task.Run(() => Window.Operations.ResetAsync()).PumpingWait();
}
[Fact]
public void CallExecuteInputOnNonUIThread()
{
Task.Run(() => Window.Operations.ExecuteInput()).PumpingWait();
}
[Fact]
public void CallCancelOnNonUIThread()
{
Task.Run(() => Window.Operations.Cancel()).PumpingWait();
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[Fact]
public void TestIndentation1()
{
TestIndentation(indentSize: 1);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[Fact]
public void TestIndentation2()
{
TestIndentation(indentSize: 2);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[Fact]
public void TestIndentation3()
{
TestIndentation(indentSize: 3);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[Fact]
public void TestIndentation4()
{
TestIndentation(indentSize: 4);
}
private void TestIndentation(int indentSize)
{
const int promptWidth = 2;
_testHost.ExportProvider.GetExport<TestSmartIndentProvider>().Value.SmartIndent = new TestSmartIndent(
promptWidth,
promptWidth + indentSize,
promptWidth
);
AssertCaretVirtualPosition(0, promptWidth);
Window.InsertCode("{");
AssertCaretVirtualPosition(0, promptWidth + 1);
Window.Operations.BreakLine();
AssertCaretVirtualPosition(1, promptWidth + indentSize);
Window.InsertCode("Console.WriteLine();");
Window.Operations.BreakLine();
AssertCaretVirtualPosition(2, promptWidth);
Window.InsertCode("}");
AssertCaretVirtualPosition(2, promptWidth + 1);
}
private void AssertCaretVirtualPosition(int expectedLine, int expectedColumn)
{
ITextSnapshotLine actualLine;
int actualColumn;
Window.TextView.Caret.Position.VirtualBufferPosition.GetLineAndColumn(out actualLine, out actualColumn);
Assert.Equal(expectedLine, actualLine.LineNumber);
Assert.Equal(expectedColumn, actualColumn);
}
}
}
| |
using System;
using DbShell.Driver.Common.CommonDataLayer;
using DbShell.Driver.Common.Structure;
namespace DbShell.Driver.Common.Utility
{
public class ArrayDataRecord : ICdlRecord, ICdlRecordWriter
{
protected object[] _values;
TableInfo _structure;
int _curReadField = -1;
int _curWriteField = -1;
CdlValueHolder _workingHolder = new CdlValueHolder();
bool _loadedValue;
public ArrayDataRecord(TableInfo structure, object[] values)
{
_values = values;
_structure = structure;
}
public ArrayDataRecord(TableInfo structure)
{
_structure = structure;
_values = new object[structure.Columns.Count];
}
public ArrayDataRecord(ICdlRecord record)
{
_values = new object[record.FieldCount];
_structure = record.Structure;
record.GetValues(_values);
}
public ArrayDataRecord(ICdlRecord record, int[] colindexes, TableInfo changedStructure)
{
if (colindexes.Length != changedStructure.Columns.Count) throw new InternalError("DBSH-00050 ArrayDataRecord(): colnames.count != colindexes.count");
_values = new object[colindexes.Length];
for (int i = 0; i < colindexes.Length; i++)
{
if (colindexes[i] >= 0)
{
_values[i] = record.GetValue(colindexes[i]);
}
}
_structure = changedStructure;
}
#region ICdlRecord Members
public TableInfo Structure
{
get { return _structure; }
}
public int FieldCount
{
get { return _values.Length; }
}
public object[] Values
{
get { return _values; }
}
public int GetOrdinal(string colName)
{
return _structure.GetColumnIndex(colName);
}
public string GetName(int i)
{
return _structure.Columns[i].Name;
}
public void ReadValue(int i)
{
_curReadField = i;
_loadedValue = false;
}
#endregion
private void Changed()
{
_loadedValue = false;
}
private CdlValueHolder WantValue()
{
if (!_loadedValue)
{
_workingHolder.ReadFrom(_values[_curReadField]);
_loadedValue = true;
}
return _workingHolder;
}
#region ICdlValueReader Members
public TypeStorage GetFieldType()
{
var val = WantValue();
return val.GetFieldType();
}
public bool GetBoolean()
{
var val = WantValue();
return val.GetBoolean();
}
public byte GetByte()
{
var val = WantValue();
return val.GetByte();
}
public sbyte GetSByte()
{
var val = WantValue();
return val.GetSByte();
}
public byte[] GetByteArray()
{
var val = WantValue();
return val.GetByteArray();
}
public DateTime GetDateTime()
{
var val = WantValue();
return val.GetDateTime();
}
public DateTimeEx GetDateTimeEx()
{
var val = WantValue();
return val.GetDateTimeEx();
}
public DateEx GetDateEx()
{
var val = WantValue();
return val.GetDateEx();
}
public TimeEx GetTimeEx()
{
var val = WantValue();
return val.GetTimeEx();
}
public decimal GetDecimal()
{
var val = WantValue();
return val.GetDecimal();
}
public double GetDouble()
{
var val = WantValue();
return val.GetDouble();
}
public float GetFloat()
{
var val = WantValue();
return val.GetFloat();
}
public Guid GetGuid()
{
var val = WantValue();
return val.GetGuid();
}
public short GetInt16()
{
var val = WantValue();
return val.GetInt16();
}
public int GetInt32()
{
var val = WantValue();
return val.GetInt32();
}
public long GetInt64()
{
var val = WantValue();
return val.GetInt64();
}
public ushort GetUInt16()
{
var val = WantValue();
return val.GetUInt16();
}
public uint GetUInt32()
{
var val = WantValue();
return val.GetUInt32();
}
public ulong GetUInt64()
{
var val = WantValue();
return val.GetUInt64();
}
public string GetString()
{
var val = WantValue();
return val.GetString();
}
//public Array GetArray()
//{
// var val = WantValue();
// return val.GetArray();
//}
public object GetValue()
{
return _values[_curReadField];
}
public int GetValues(object[] data)
{
int cnt = Math.Min(data.Length, _values.Length);
for (int i = 0; i < cnt; i++)
{
data[i] = _values[i];
}
return cnt;
}
#endregion
#region ICdlRecordWriter Members
public void SeekValue(int i)
{
_curWriteField = i;
}
#endregion
#region ICdlValueWriter Members
public void SetBoolean(bool value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetByte(byte value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetSByte(sbyte value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetByteArray(byte[] value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetDateTime(DateTime value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetDateTimeEx(DateTimeEx value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetDateEx(DateEx value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetTimeEx(TimeEx value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetDecimal(decimal value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetDouble(double value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetFloat(float value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetGuid(Guid value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetInt16(short value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetInt32(int value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetInt64(long value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetUInt16(ushort value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetUInt32(uint value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetUInt64(ulong value)
{
_values[_curWriteField] = value;
Changed();
}
public void SetString(string value)
{
_values[_curWriteField] = value;
Changed();
}
//public void SetArray(Array value)
//{
// _values[_curWriteField] = value;
// Changed();
//}
public void SetNull()
{
_values[_curWriteField] = null;
Changed();
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
namespace NPOI.HSSF.UserModel
{
using System;
using System.Drawing;
using System.Text;
using System.IO;
using NPOI.DDF;
using NPOI.Util;
using NPOI.SS.UserModel;
using NPOI.HSSF.Model;
using NPOI.HSSF.Record;
/// <summary>
/// Represents a escher picture. Eg. A GIF, JPEG etc...
/// @author Glen Stampoultzis
/// @author Yegor Kozlov (yegor at apache.org)
/// </summary>
public class HSSFPicture : HSSFSimpleShape, IPicture
{
/**
* width of 1px in columns with default width in Units of 1/256 of a Char width
*/
private const float PX_DEFAULT = 32.00f;
/**
* width of 1px in columns with overridden width in Units of 1/256 of a Char width
*/
private const float PX_MODIFIED = 36.56f;
/**
* Height of 1px of a row
*/
private const int PX_ROW = 15;
//int pictureIndex;
//HSSFPatriarch patriarch;
private static POILogger logger = POILogFactory.GetLogger(typeof(HSSFPicture));
public HSSFPicture(EscherContainerRecord spContainer, ObjRecord objRecord)
: base(spContainer, objRecord)
{
}
/// <summary>
/// Constructs a picture object.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="anchor">The anchor.</param>
public HSSFPicture(HSSFShape parent, HSSFAnchor anchor)
: base(parent, anchor)
{
base.ShapeType = (OBJECT_TYPE_PICTURE);
CommonObjectDataSubRecord cod = (CommonObjectDataSubRecord)GetObjRecord().SubRecords[0];
cod.ObjectType = CommonObjectType.Picture;
}
protected override EscherContainerRecord CreateSpContainer()
{
EscherContainerRecord spContainer = base.CreateSpContainer();
EscherOptRecord opt = (EscherOptRecord)spContainer.GetChildById(EscherOptRecord.RECORD_ID);
opt.RemoveEscherProperty(EscherProperties.LINESTYLE__LINEDASHING);
opt.RemoveEscherProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH);
spContainer.RemoveChildRecord(spContainer.GetChildById(EscherTextboxRecord.RECORD_ID));
return spContainer;
}
/// <summary>
/// Gets or sets the index of the picture.
/// </summary>
/// <value>The index of the picture.</value>
public int PictureIndex
{
get
{
EscherSimpleProperty property = (EscherSimpleProperty)GetOptRecord().Lookup(EscherProperties.BLIP__BLIPTODISPLAY);
if (null == property)
{
return -1;
}
return property.PropertyValue;
}
set
{
SetPropertyValue(new EscherSimpleProperty(EscherProperties.BLIP__BLIPTODISPLAY, false, true, value));
}
}
/// <summary>
/// Reset the image to the original size.
/// </summary>
public void Resize(double scale)
{
HSSFClientAnchor anchor = (HSSFClientAnchor)Anchor;
anchor.AnchorType = 2;
IClientAnchor pref = GetPreferredSize(scale);
int row2 = anchor.Row1 + (pref.Row2 - pref.Row1);
int col2 = anchor.Col1 + (pref.Col2 - pref.Col1);
anchor.Col2 = col2;
anchor.Dx1 = 0;
anchor.Dx2 = pref.Dx2;
anchor.Row2 = row2;
anchor.Dy1 = 0;
anchor.Dy2 = pref.Dy2;
}
/// <summary>
/// Reset the image to the original size.
/// </summary>
public void Resize()
{
Resize(1.0);
}
/// <summary>
/// Calculate the preferred size for this picture.
/// </summary>
/// <param name="scale">the amount by which image dimensions are multiplied relative to the original size.</param>
/// <returns>HSSFClientAnchor with the preferred size for this image</returns>
public HSSFClientAnchor GetPreferredSize(double scale)
{
HSSFClientAnchor anchor = (HSSFClientAnchor)Anchor;
Size size = GetImageDimension();
double scaledWidth = size.Width * scale;
double scaledHeight = size.Height * scale;
float w = 0;
//space in the leftmost cell
w += GetColumnWidthInPixels(anchor.Col1) * (1 - (float)anchor.Dx1 / 1024);
short col2 = (short)(anchor.Col1 + 1);
int dx2 = 0;
while (w < scaledWidth)
{
w += GetColumnWidthInPixels(col2++);
}
if (w > scaledWidth)
{
//calculate dx2, offset in the rightmost cell
col2--;
double cw = GetColumnWidthInPixels(col2);
double delta = w - scaledWidth;
dx2 = (int)((cw - delta) / cw * 1024);
}
anchor.Col2 = col2;
anchor.Dx2 = dx2;
float h = 0;
h += (1 - (float)anchor.Dy1 / 256) * GetRowHeightInPixels(anchor.Row1);
int row2 = anchor.Row1 + 1;
int dy2 = 0;
while (h < scaledHeight)
{
h += GetRowHeightInPixels(row2++);
}
if (h > scaledHeight)
{
row2--;
double ch = GetRowHeightInPixels(row2);
double delta = h - scaledHeight;
dy2 = (int)((ch - delta) / ch * 256);
}
anchor.Row2 = row2;
anchor.Dy2 = dy2;
return anchor;
}
/// <summary>
/// Calculate the preferred size for this picture.
/// </summary>
/// <returns>HSSFClientAnchor with the preferred size for this image</returns>
public NPOI.SS.UserModel.IClientAnchor GetPreferredSize()
{
return GetPreferredSize(1.0);
}
/// <summary>
/// Gets the column width in pixels.
/// </summary>
/// <param name="column">The column.</param>
/// <returns></returns>
private float GetColumnWidthInPixels(int column)
{
int cw = _patriarch.Sheet.GetColumnWidth(column);
float px = GetPixelWidth(column);
return cw / px;
}
/// <summary>
/// Gets the row height in pixels.
/// </summary>
/// <param name="i">The row</param>
/// <returns></returns>
private float GetRowHeightInPixels(int i)
{
IRow row = _patriarch.Sheet.GetRow(i);
float height;
if (row != null) height = row.Height;
else height = _patriarch.Sheet.DefaultRowHeight;
return height / PX_ROW;
}
/// <summary>
/// Gets the width of the pixel.
/// </summary>
/// <param name="column">The column.</param>
/// <returns></returns>
private float GetPixelWidth(int column)
{
int def = _patriarch.Sheet.DefaultColumnWidth * 256;
int cw = _patriarch.Sheet.GetColumnWidth(column);
return cw == def ? PX_DEFAULT : PX_MODIFIED;
}
/// <summary>
/// The metadata of PNG and JPEG can contain the width of a pixel in millimeters.
/// Return the the "effective" dpi calculated as
/// <c>25.4/HorizontalPixelSize</c>
/// and
/// <c>25.4/VerticalPixelSize</c>
/// . Where 25.4 is the number of mm in inch.
/// </summary>
/// <param name="r">The image.</param>
/// <returns>the resolution</returns>
protected Size GetResolution(Image r)
{
//int hdpi = 96, vdpi = 96;
//double mm2inch = 25.4;
//NodeList lst;
//Element node = (Element)r.GetImageMetadata(0).GetAsTree("javax_imageio_1.0");
//lst = node.GetElementsByTagName("HorizontalPixelSize");
//if (lst != null && lst.GetLength == 1) hdpi = (int)(mm2inch / Float.ParseFloat(((Element)lst.item(0)).GetAttribute("value")));
//lst = node.GetElementsByTagName("VerticalPixelSize");
//if (lst != null && lst.GetLength == 1) vdpi = (int)(mm2inch / Float.ParseFloat(((Element)lst.item(0)).GetAttribute("value")));
return new Size((int)r.HorizontalResolution, (int)r.VerticalResolution);
}
/// <summary>
/// Return the dimension of this image
/// </summary>
/// <returns>image dimension</returns>
public Size GetImageDimension()
{
EscherBSERecord bse = (_patriarch.Sheet.Workbook as HSSFWorkbook).Workbook.GetBSERecord(PictureIndex);
byte[] data = bse.BlipRecord.PictureData;
//int type = bse.BlipTypeWin32;
using (MemoryStream ms = new MemoryStream(data))
{
using (Image img = Image.FromStream(ms))
{
return img.Size;
}
}
}
/**
* Return picture data for this shape
*
* @return picture data for this shape
*/
public IPictureData PictureData
{
get
{
InternalWorkbook iwb = ((_patriarch.Sheet.Workbook) as HSSFWorkbook).Workbook;
EscherBlipRecord blipRecord = iwb.GetBSERecord(PictureIndex).BlipRecord;
return new HSSFPictureData(blipRecord);
}
}
internal override void AfterInsert(HSSFPatriarch patriarch)
{
EscherAggregate agg = patriarch.GetBoundAggregate();
agg.AssociateShapeToObjRecord(GetEscherContainer().GetChildById(EscherClientDataRecord.RECORD_ID), GetObjRecord());
EscherBSERecord bse =
(patriarch.Sheet.Workbook as HSSFWorkbook).Workbook.GetBSERecord(PictureIndex);
bse.Ref = (bse.Ref + 1);
}
/**
* The color applied to the lines of this shape.
*/
public String FileName
{
get
{
EscherComplexProperty propFile = (EscherComplexProperty)GetOptRecord().Lookup(
EscherProperties.BLIP__BLIPFILENAME);
try
{
if (null == propFile)
{
return "";
}
return Trim(Encoding.Unicode.GetString(propFile.ComplexData));
}
catch (Exception)
{
return "";
}
}
set
{
try
{
EscherComplexProperty prop = new EscherComplexProperty(EscherProperties.BLIP__BLIPFILENAME, true,
Encoding.Unicode.GetBytes(value));
SetPropertyValue(prop);
}
catch (Exception)
{
logger.Log(POILogger.ERROR, "Unsupported encoding: UTF-16LE");
}
}
}
private String Trim(string value)
{
int end = value.Length;
int st = 0;
//int off = offset; /* avoid getfield opcode */
char[] val = value.ToCharArray(); /* avoid getfield opcode */
while ((st < end) && (val[st] <= ' '))
{
st++;
}
while ((st < end) && (val[end - 1] <= ' '))
{
end--;
}
return ((st > 0) || (end < value.Length)) ? value.Substring(st, end - st) : value;
}
public override int ShapeType
{
get { return base.ShapeType; }
set
{
throw new InvalidOperationException("Shape type can not be changed in " + this.GetType().Name);
}
}
internal override HSSFShape CloneShape()
{
EscherContainerRecord spContainer = new EscherContainerRecord();
byte[] inSp = GetEscherContainer().Serialize();
spContainer.FillFields(inSp, 0, new DefaultEscherRecordFactory());
ObjRecord obj = (ObjRecord)GetObjRecord().CloneViaReserialise();
return new HSSFPicture(spContainer, obj);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
namespace DiscUtils.Streams
{
/// <summary>
/// Represents a sparse stream.
/// </summary>
/// <remarks>A sparse stream is a logically contiguous stream where some parts of the stream
/// aren't stored. The unstored parts are implicitly zero-byte ranges.</remarks>
public abstract class SparseStream : Stream
{
/// <summary>
/// Gets the parts of the stream that are stored.
/// </summary>
/// <remarks>This may be an empty enumeration if all bytes are zero.</remarks>
public abstract IEnumerable<StreamExtent> Extents { get; }
/// <summary>
/// Converts any stream into a sparse stream.
/// </summary>
/// <param name="stream">The stream to convert.</param>
/// <param name="takeOwnership"><c>true</c> to have the new stream dispose the wrapped
/// stream when it is disposed.</param>
/// <returns>A sparse stream.</returns>
/// <remarks>The returned stream has the entire wrapped stream as a
/// single extent.</remarks>
public static SparseStream FromStream(Stream stream, Ownership takeOwnership)
{
return new SparseWrapperStream(stream, takeOwnership, null);
}
/// <summary>
/// Converts any stream into a sparse stream.
/// </summary>
/// <param name="stream">The stream to convert.</param>
/// <param name="takeOwnership"><c>true</c> to have the new stream dispose the wrapped
/// stream when it is disposed.</param>
/// <param name="extents">The set of extents actually stored in <c>stream</c>.</param>
/// <returns>A sparse stream.</returns>
/// <remarks>The returned stream has the entire wrapped stream as a
/// single extent.</remarks>
public static SparseStream FromStream(Stream stream, Ownership takeOwnership, IEnumerable<StreamExtent> extents)
{
return new SparseWrapperStream(stream, takeOwnership, extents);
}
/// <summary>
/// Efficiently pumps data from a sparse stream to another stream.
/// </summary>
/// <param name="inStream">The sparse stream to pump from.</param>
/// <param name="outStream">The stream to pump to.</param>
/// <remarks><paramref name="outStream"/> must support seeking.</remarks>
public static void Pump(Stream inStream, Stream outStream)
{
Pump(inStream, outStream, Sizes.Sector);
}
/// <summary>
/// Efficiently pumps data from a sparse stream to another stream.
/// </summary>
/// <param name="inStream">The stream to pump from.</param>
/// <param name="outStream">The stream to pump to.</param>
/// <param name="chunkSize">The smallest sequence of zero bytes that will be skipped when writing to <paramref name="outStream"/>.</param>
/// <remarks><paramref name="outStream"/> must support seeking.</remarks>
public static void Pump(Stream inStream, Stream outStream, int chunkSize)
{
StreamPump pump = new StreamPump(inStream, outStream, chunkSize);
pump.Run();
}
/// <summary>
/// Wraps a sparse stream in a read-only wrapper, preventing modification.
/// </summary>
/// <param name="toWrap">The stream to make read-only.</param>
/// <param name="ownership">Whether to transfer responsibility for calling Dispose on <c>toWrap</c>.</param>
/// <returns>The read-only stream.</returns>
public static SparseStream ReadOnly(SparseStream toWrap, Ownership ownership)
{
return new SparseReadOnlyWrapperStream(toWrap, ownership);
}
/// <summary>
/// Clears bytes from the stream.
/// </summary>
/// <param name="count">The number of bytes (from the current position) to clear.</param>
/// <remarks>
/// <para>Logically equivalent to writing <c>count</c> null/zero bytes to the stream, some
/// implementations determine that some (or all) of the range indicated is not actually
/// stored. There is no direct, automatic, correspondence to clearing bytes and them
/// not being represented as an 'extent' - for example, the implementation of the underlying
/// stream may not permit fine-grained extent storage.</para>
/// <para>It is always safe to call this method to 'zero-out' a section of a stream, regardless of
/// the underlying stream implementation.</para>
/// </remarks>
public virtual void Clear(int count)
{
Write(new byte[count], 0, count);
}
/// <summary>
/// Gets the parts of a stream that are stored, within a specified range.
/// </summary>
/// <param name="start">The offset of the first byte of interest.</param>
/// <param name="count">The number of bytes of interest.</param>
/// <returns>An enumeration of stream extents, indicating stored bytes.</returns>
public virtual IEnumerable<StreamExtent> GetExtentsInRange(long start, long count)
{
return StreamExtent.Intersect(Extents, new[] { new StreamExtent(start, count) });
}
private class SparseReadOnlyWrapperStream : SparseStream
{
private readonly Ownership _ownsWrapped;
private SparseStream _wrapped;
public SparseReadOnlyWrapperStream(SparseStream wrapped, Ownership ownsWrapped)
{
_wrapped = wrapped;
_ownsWrapped = ownsWrapped;
}
public override bool CanRead
{
get { return _wrapped.CanRead; }
}
public override bool CanSeek
{
get { return _wrapped.CanSeek; }
}
public override bool CanWrite
{
get { return false; }
}
public override IEnumerable<StreamExtent> Extents
{
get { return _wrapped.Extents; }
}
public override long Length
{
get { return _wrapped.Length; }
}
public override long Position
{
get { return _wrapped.Position; }
set { _wrapped.Position = value; }
}
public override void Flush() {}
public override int Read(byte[] buffer, int offset, int count)
{
return _wrapped.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _wrapped.Seek(offset, origin);
}
public override void SetLength(long value)
{
throw new InvalidOperationException("Attempt to change length of read-only stream");
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new InvalidOperationException("Attempt to write to read-only stream");
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && _ownsWrapped == Ownership.Dispose && _wrapped != null)
{
_wrapped.Dispose();
_wrapped = null;
}
}
finally
{
base.Dispose(disposing);
}
}
}
private class SparseWrapperStream : SparseStream
{
private readonly List<StreamExtent> _extents;
private readonly Ownership _ownsWrapped;
private Stream _wrapped;
public SparseWrapperStream(Stream wrapped, Ownership ownsWrapped, IEnumerable<StreamExtent> extents)
{
_wrapped = wrapped;
_ownsWrapped = ownsWrapped;
if (extents != null)
{
_extents = new List<StreamExtent>(extents);
}
}
public override bool CanRead
{
get { return _wrapped.CanRead; }
}
public override bool CanSeek
{
get { return _wrapped.CanSeek; }
}
public override bool CanWrite
{
get { return _wrapped.CanWrite; }
}
public override IEnumerable<StreamExtent> Extents
{
get
{
if (_extents != null)
{
return _extents;
}
SparseStream wrappedAsSparse = _wrapped as SparseStream;
if (wrappedAsSparse != null)
{
return wrappedAsSparse.Extents;
}
return new[] { new StreamExtent(0, _wrapped.Length) };
}
}
public override long Length
{
get { return _wrapped.Length; }
}
public override long Position
{
get { return _wrapped.Position; }
set { _wrapped.Position = value; }
}
public override void Flush()
{
_wrapped.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _wrapped.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _wrapped.Seek(offset, origin);
}
public override void SetLength(long value)
{
_wrapped.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
if (_extents != null)
{
throw new InvalidOperationException("Attempt to write to stream with explicit extents");
}
_wrapped.Write(buffer, offset, count);
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && _ownsWrapped == Ownership.Dispose && _wrapped != null)
{
_wrapped.Dispose();
_wrapped = null;
}
}
finally
{
base.Dispose(disposing);
}
}
}
}
}
| |
// Copyright (c) 2011 Morten Bakkedal
// This code is published under the MIT License.
using System;
using System.Diagnostics;
namespace FuncLib.Mathematics
{
[Serializable]
[DebuggerStepThrough]
public struct Complex
{
private double re, im;
public Complex(double re, double im)
{
this.re = re;
this.im = im;
}
public override string ToString()
{
if (double.IsNaN(re) && double.IsNaN(im))
{
return double.NaN.ToString();
}
else if (im == 0.0)
{
return re.ToString();
}
else if (im > 0.0)
{
return string.Format("{0}+i{1}", re, im);
}
else
{
return string.Format("{0}-i{1}", re, -im);
}
}
public override int GetHashCode()
{
return re.GetHashCode() * re.GetHashCode() + im.GetHashCode() * im.GetHashCode();
}
public override bool Equals(object other)
{
if (other is Complex)
{
return ((Complex)other) == this;
}
else
{
return false;
}
}
public static Complex operator +(Complex z1, Complex z2)
{
return new Complex(z1.re + z2.re, z1.im + z2.im);
}
public static Complex operator +(double a, Complex z)
{
return new Complex(a + z.re, z.im);
}
public static Complex operator +(Complex z, double a)
{
return new Complex(z.re + a, z.im);
}
public static Complex operator -(Complex z)
{
return new Complex(-z.re, -z.im);
}
public static Complex operator -(Complex z1, Complex z2)
{
return new Complex(z1.re - z2.re, z1.im - z2.im);
}
public static Complex operator -(double a, Complex z)
{
return new Complex(a - z.re, -z.im);
}
public static Complex operator -(Complex z, double a)
{
return new Complex(z.re - a, z.im);
}
public static Complex operator *(Complex z1, Complex z2)
{
return new Complex(z1.re * z2.re - z1.im * z2.im, z1.im * z2.re + z1.re * z2.im);
}
public static Complex operator *(double a, Complex z)
{
return new Complex(a * z.re, a * z.im);
}
public static Complex operator *(Complex z, double a)
{
return new Complex(z.re * a, z.im * a);
}
public static Complex operator /(Complex z1, Complex z2)
{
double c = z2.re * z2.re + z2.im * z2.im;
return new Complex((z1.re * z2.re + z1.im * z2.im) / c, (z1.im * z2.re - z1.re * z2.im) / c);
}
public static Complex operator /(double a, Complex z)
{
double c = z.re * z.re + z.im * z.im;
return new Complex(a * z.re / c, -a * z.im / c);
}
public static Complex operator /(Complex z, double a)
{
return new Complex(z.re / a, z.im / a);
}
public static bool operator ==(Complex z1, Complex z2)
{
return z1.re == z2.re && z1.im == z2.im;
}
public static bool operator !=(Complex z1, Complex z2)
{
return z1.re != z2.re || z1.im != z2.im;
}
public static implicit operator Complex(double a)
{
return new Complex(a, 0.0);
}
public static explicit operator double(Complex z)
{
return z.re;
}
public static double Re(Complex z)
{
return z.re;
}
public static double Im(Complex z)
{
return z.im;
}
public static Complex Conjugate(Complex z)
{
return new Complex(z.re, -z.im);
}
public static double Abs(Complex z)
{
return Math.Sqrt(z.re * z.re + z.im * z.im);
}
public static Complex Exp(Complex z)
{
double c = Math.Exp(z.re);
if (z.im == 0.0)
{
return new Complex(c, 0.0);
}
else
{
return new Complex(c * Math.Cos(z.im), c * Math.Sin(z.im));
}
}
public static Complex Sqr(Complex z)
{
return new Complex(z.re * z.re - z.im * z.im, 2.0 * z.re * z.im);
}
public static Complex Sqrt(Complex z)
{
// Using the identity described at
// http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers.
if (z.im != 0.0)
{
double c = Complex.Abs(z) + z.re;
return new Complex(Math.Sqrt(0.5 * c), z.im / Math.Sqrt(2.0 * c));
}
else if (z.re < 0.0)
{
return new Complex(0.0, Math.Sqrt(-z.re));
}
else
{
return new Complex(Math.Sqrt(z.re), 0.0);
}
}
public static double Arg(Complex z)
{
if (z.re > 0.0 || z.im != 0.0)
{
return 2.0 * Math.Atan2(z.im, Abs(z) + z.re);
}
else if (z.re < 0.0 && z.im == 0.0)
{
return Math.PI;
}
else
{
return double.NaN;
}
}
public static Complex Log(Complex z)
{
return new Complex(0.5 * Math.Log(z.re * z.re + z.im * z.im), Arg(z));
}
public static Complex I
{
get
{
return new Complex(0.0, 1.0);
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using SandcastleBuilder.Utils;
using SandcastleBuilder.Utils.Design;
namespace XsdDocumentation.PlugIn
{
internal sealed class XsdPlugInConfiguration
{
private XsdPlugInConfiguration(XsdPlugInConfiguration other)
{
BasePathProvider = other.BasePathProvider;
DocumentRootSchemas = other.DocumentRootSchemas;
DocumentRootElements = other.DocumentRootElements;
DocumentConstraints = other.DocumentConstraints;
DocumentSchemas = other.DocumentSchemas;
DocumentSyntax = other.DocumentSyntax;
UseTypeDocumentationForUndocumentedAttributes = other.UseTypeDocumentationForUndocumentedAttributes;
UseTypeDocumentationForUndocumentedElements = other.UseTypeDocumentationForUndocumentedElements;
SchemaSetContainer = other.SchemaSetContainer;
SchemaSetTitle = other.SchemaSetTitle;
NamespaceContainer = other.NamespaceContainer;
SortOrder = other.SortOrder;
IncludeLinkUriInKeywordK = other.IncludeLinkUriInKeywordK;
AnnotationTransformFilePath = (FilePath)other.AnnotationTransformFilePath.Clone();
SchemaFilePaths = other.SchemaFilePaths.Clone();
SchemaDependencyFilePaths = other.SchemaDependencyFilePaths.Clone();
DocFilePaths = other.DocFilePaths.Clone();
}
private XsdPlugInConfiguration(IBasePathProvider basePathProvider, XPathNavigator navigator)
{
BasePathProvider = basePathProvider;
DocumentRootSchemas = GetBoolean(navigator, "configuration/document/@rootSchemas", true);
DocumentRootElements = GetBoolean(navigator, "configuration/document/@rootElements", true);
DocumentConstraints = GetBoolean(navigator, "configuration/document/@constraints", true);
DocumentSchemas = GetBoolean(navigator, "configuration/document/@schemas", true);
DocumentSyntax = GetBoolean(navigator, "configuration/document/@syntax", true);
UseTypeDocumentationForUndocumentedAttributes = GetBoolean(navigator, "configuration/useTypeDocumentation/@forUndocumentedAttributes", true);
UseTypeDocumentationForUndocumentedElements = GetBoolean(navigator, "configuration/useTypeDocumentation/@forUndocumentedElements", true);
SchemaSetContainer = GetBoolean(navigator, "configuration/schemaSet/@container", false);
SchemaSetTitle = GetString(navigator, "configuration/schemaSet/@title", string.Empty);
NamespaceContainer = GetBoolean(navigator, "configuration/namespace/@container", true);
SortOrder = GetInt32(navigator, "configuration/sortOrder", 1);
IncludeLinkUriInKeywordK = GetBoolean(navigator, "configuration/includeLinkUriInKeywordK", false);
AnnotationTransformFilePath = GetFilePath(basePathProvider, navigator, "configuration/annotationTransformFile/@path");
SchemaFilePaths = GetFilePaths(basePathProvider, navigator, "configuration/schemaFiles/schemaFile/@path");
SchemaDependencyFilePaths = GetFilePaths(basePathProvider, navigator, "configuration/dependencyFiles/schemaFile/@path");
DocFilePaths = GetFilePaths(basePathProvider, navigator, "configuration/docFiles/docFile/@path");
}
[Browsable(false)]
public IBasePathProvider BasePathProvider { get; private set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionDocumentRootSchemas")]
[DefaultValue(true)]
public bool DocumentRootSchemas { get; set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionDocumentRootElements")]
[DefaultValue(true)]
public bool DocumentRootElements { get; set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionDocumentConstraints")]
[DefaultValue(true)]
public bool DocumentConstraints { get; set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionDocumentSchemas")]
[DefaultValue(true)]
public bool DocumentSchemas { get; set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionDocumentSyntax")]
[DefaultValue(true)]
public bool DocumentSyntax { get; set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionUseTypeDocumentationForUndocumentedAttributes")]
[DefaultValue(true)]
public bool UseTypeDocumentationForUndocumentedAttributes { get; set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionUseTypeDocumentationForUndocumentedElements")]
[DefaultValue(true)]
public bool UseTypeDocumentationForUndocumentedElements { get; set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionSchemaSetContainer")]
[DefaultValue(false)]
public bool SchemaSetContainer { get; set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionSchemaSetTitle")]
[DefaultValue("")]
public string SchemaSetTitle { get; set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionNamespaceContainer")]
[DefaultValue(true)]
public bool NamespaceContainer { get; set; }
[LocalizableCategory("ConfigCategoryAppearance")]
[LocalizableDescription("ConfigDescriptionSortOrder")]
[DefaultValue(1)]
public int SortOrder { get; set; }
[LocalizableCategory("ConfigCategoryIndex")]
[LocalizableDescription("ConfigDescriptionIncludeLinkUriInKeywordK")]
[DefaultValue(false)]
public bool IncludeLinkUriInKeywordK { get; set; }
[Editor(typeof(FilePathObjectEditor), typeof(UITypeEditor))]
[LocalizableCategory("ConfigCategoryFiles")]
[LocalizableDescription("ConfigDescriptionAnnotationTransformFilePath")]
public FilePath AnnotationTransformFilePath { get; set; }
[Editor(typeof(SchemaFilePathsEditor), typeof(UITypeEditor))]
[LocalizableCategory("ConfigCategoryFiles")]
[LocalizableDescription("ConfigDescriptionSchemaFilePaths")]
public FilePathCollection SchemaFilePaths { get; private set; }
[Editor(typeof(SchemaDependencyFilePathsEditor), typeof(UITypeEditor))]
[LocalizableCategory("ConfigCategoryFiles")]
[LocalizableDescription("ConfigDescriptionSchemaDependencyFilePaths")]
public FilePathCollection SchemaDependencyFilePaths { get; private set; }
[Editor(typeof(DocFilePathsEditor), typeof(UITypeEditor))]
[LocalizableCategory("ConfigCategoryFiles")]
[LocalizableDescription("ConfigDescriptionDocFilePaths")]
public FilePathCollection DocFilePaths { get; private set; }
[Browsable(false)]
private bool ShouldSerializeAnnotationTransformFilePath()
{
return !string.IsNullOrEmpty(AnnotationTransformFilePath.ExpandedPath);
}
[Browsable(false)]
private bool ShouldSerializeSchemaFilePaths()
{
return SchemaFilePaths.Count > 0;
}
[Browsable(false)]
private bool ShouldSerializeSchemaDependencyFilePaths()
{
return SchemaDependencyFilePaths.Count > 0;
}
[Browsable(false)]
private bool ShouldSerializeDocFilePaths()
{
return DocFilePaths.Count > 0;
}
public static XsdPlugInConfiguration FromXml(IBasePathProvider basePathProvider, XPathNavigator configuration)
{
return new XsdPlugInConfiguration(basePathProvider, configuration);
}
public static XsdPlugInConfiguration FromXml(IBasePathProvider basePathProvider, string configuration)
{
var stringReader = new StringReader(configuration);
var document = new XPathDocument(stringReader);
var navigator = document.CreateNavigator();
return FromXml(basePathProvider, navigator);
}
private static bool GetBoolean(XPathNavigator navigator, string xpath, bool defaultValue)
{
var value = navigator.SelectSingleNode(xpath);
return (value == null)
? defaultValue
: value.ValueAsBoolean;
}
private static int GetInt32(XPathNavigator navigator, string xpath, int defaultValue)
{
var value = navigator.SelectSingleNode(xpath);
return (value == null)
? defaultValue
: value.ValueAsInt;
}
private static string GetString(XPathNavigator navigator, string xpath, string defaultValue)
{
var value = navigator.SelectSingleNode(xpath);
return (value == null)
? defaultValue
: value.Value;
}
private static FilePath GetFilePath(IBasePathProvider basePathProvider, XPathNavigator navigator, string xpath)
{
var path = navigator.SelectSingleNode(xpath);
return path == null
? new FilePath(string.Empty, basePathProvider)
: new FilePath(path.Value, basePathProvider);
}
private static FilePathCollection GetFilePaths(IBasePathProvider basePathProvider, XPathNavigator navigator, string xpath)
{
var schemaFilePaths = new FilePathCollection();
var schemaFilePathsNodeList = navigator.Select(xpath);
foreach (XPathNavigator pathAttribute in schemaFilePathsNodeList)
{
var filePath = new FilePath(pathAttribute.Value, basePathProvider);
schemaFilePaths.Add(filePath);
}
return schemaFilePaths;
}
public static string ToXml(XsdPlugInConfiguration configuration)
{
var doc = new XmlDocument();
var configurationNode = doc.CreateElement("configuration");
doc.AppendChild(configurationNode);
var documentNode = doc.CreateElement("document");
documentNode.SetAttribute("rootSchemas", XmlConvert.ToString(configuration.DocumentRootSchemas));
documentNode.SetAttribute("rootElements", XmlConvert.ToString(configuration.DocumentRootElements));
documentNode.SetAttribute("constraints", XmlConvert.ToString(configuration.DocumentConstraints));
documentNode.SetAttribute("schemas", XmlConvert.ToString(configuration.DocumentSchemas));
documentNode.SetAttribute("syntax", XmlConvert.ToString(configuration.DocumentSyntax));
configurationNode.AppendChild(documentNode);
var useTypeDocumentationNode = doc.CreateElement("useTypeDocumentation");
useTypeDocumentationNode.SetAttribute("forUndocumentedAttributes", XmlConvert.ToString(configuration.UseTypeDocumentationForUndocumentedAttributes));
useTypeDocumentationNode.SetAttribute("forUndocumentedElements", XmlConvert.ToString(configuration.UseTypeDocumentationForUndocumentedElements));
configurationNode.AppendChild(useTypeDocumentationNode);
var schemaSetNode = doc.CreateElement("schemaSet");
schemaSetNode.SetAttribute("container", XmlConvert.ToString(configuration.SchemaSetContainer));
schemaSetNode.SetAttribute("title", configuration.SchemaSetTitle);
configurationNode.AppendChild(schemaSetNode);
var namespaceNode = doc.CreateElement("namespace");
namespaceNode.SetAttribute("container", XmlConvert.ToString(configuration.NamespaceContainer));
configurationNode.AppendChild(namespaceNode);
var sortOrderNode = doc.CreateElement("sortOrder");
sortOrderNode.InnerText = XmlConvert.ToString(configuration.SortOrder);
configurationNode.AppendChild(sortOrderNode);
var includeLinkUriInKeywordKNode = doc.CreateElement("includeLinkUriInKeywordK");
includeLinkUriInKeywordKNode.InnerText = XmlConvert.ToString(configuration.IncludeLinkUriInKeywordK);
configurationNode.AppendChild(includeLinkUriInKeywordKNode);
var annotationTransformFileNode = doc.CreateElement("annotationTransformFile");
annotationTransformFileNode.SetAttribute("path", configuration.AnnotationTransformFilePath.PersistablePath);
configurationNode.AppendChild(annotationTransformFileNode);
var schemaFilesNode = doc.CreateElement("schemaFiles");
configurationNode.AppendChild(schemaFilesNode);
foreach (var filePath in configuration.SchemaFilePaths)
{
var schemaFileNode = doc.CreateElement("schemaFile");
schemaFileNode.SetAttribute("path", filePath.PersistablePath);
schemaFilesNode.AppendChild(schemaFileNode);
}
var dependencyFilesNode = doc.CreateElement("dependencyFiles");
configurationNode.AppendChild(dependencyFilesNode);
foreach (var filePath in configuration.SchemaDependencyFilePaths)
{
var schemaFileNode = doc.CreateElement("schemaFile");
schemaFileNode.SetAttribute("path", filePath.PersistablePath);
dependencyFilesNode.AppendChild(schemaFileNode);
}
var docFilesNode = doc.CreateElement("docFiles");
configurationNode.AppendChild(docFilesNode);
foreach (var filePath in configuration.DocFilePaths)
{
var docFileNode = doc.CreateElement("docFile");
docFileNode.SetAttribute("path", filePath.PersistablePath);
docFilesNode.AppendChild(docFileNode);
}
return doc.OuterXml;
}
public XsdPlugInConfiguration Clone()
{
return new XsdPlugInConfiguration(this);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Xml;
using System.Xml.XPath;
using XPathTests.Common;
namespace XPathTests.FunctionalTests.MiscellaneousCases
{
/// <summary>
/// Miscellaneous Cases (regression tests)
/// </summary>
public static partial class RegressionTestsTests
{
/// <summary>
/// translate() cannot handle surrogate pair mapping correctly
/// </summary>
[Fact]
public static void RegressionTestsTest552()
{
var xml = "dummy.xml";
var testExpression = "translate('+\uD800\uDF30+', '\uD800\uDF30', 'x')";
var expected = @"+x+";
Utils.XPathStringTest(xml, testExpression, expected);
}
/// <summary>
/// translate() cannot handle surrogate pair mapping correctly
/// </summary>
[Fact]
public static void RegressionTestsTest553()
{
var xml = "dummy.xml";
var testExpression = "translate('+\uD800\uDF30+', '\uD800\uDF30', 'xy')";
var expected = @"+xy+";
Utils.XPathStringTest(xml, testExpression, expected);
}
/// <summary>
/// translate() cannot handle surrogate pair mapping correctly
/// </summary>
[Fact]
public static void RegressionTestsTest554()
{
var xml = "dummy.xml";
var testExpression = @"translate('1.2.3.4.5.6.7.8.9.', '112233445566778899', 'axaxaxaxaxaxaxaxax')";
var expected = @"a.a.a.a.a.a.a.a.a.";
Utils.XPathStringTest(xml, testExpression, expected);
}
/// <summary>
/// translate('--aaa--', 'xyz', '')
/// </summary>
[Fact]
public static void RegressionTestsTest555()
{
var xml = "dummy.xml";
var testExpression = @"translate('--aaa--', 'xyz', '')";
var expected = @"--aaa--";
Utils.XPathStringTest(xml, testExpression, expected);
}
/// <summary>
/// translate('abc', 'abc', '')
/// </summary>
[Fact]
public static void RegressionTestsTest556()
{
var xml = "dummy.xml";
var testExpression = @"translate('abc', 'abc', '')";
var expected = @"";
Utils.XPathStringTest(xml, testExpression, expected);
}
/// <summary>
/// //namespace::*
/// </summary>
[Fact]
public static void RegressionTestsTest557()
{
var xml = "t98598.xml";
var testExpression = @"//namespace::*";
var expected = new XPathResult(0,
new XPathResultToken
{
NodeType = XPathNodeType.Namespace,
LocalName = "xml",
Name = "xml",
HasNameTable = true,
Value = "http://www.w3.org/XML/1998/namespace"
},
new XPathResultToken
{
NodeType = XPathNodeType.Namespace,
LocalName = "foo2",
Name = "foo2",
HasNameTable = true,
Value = "f2"
},
new XPathResultToken
{
NodeType = XPathNodeType.Namespace,
LocalName = "foo1",
Name = "foo1",
HasNameTable = true,
Value = "f1"
},
new XPathResultToken { NodeType = XPathNodeType.Namespace, HasNameTable = true, Value = "f0" },
new XPathResultToken
{
NodeType = XPathNodeType.Namespace,
LocalName = "xml",
Name = "xml",
HasNameTable = true,
Value = "http://www.w3.org/XML/1998/namespace"
},
new XPathResultToken
{
NodeType = XPathNodeType.Namespace,
LocalName = "bar2",
Name = "bar2",
HasNameTable = true,
Value = "b2"
},
new XPathResultToken
{
NodeType = XPathNodeType.Namespace,
LocalName = "bar1",
Name = "bar1",
HasNameTable = true,
Value = "b1"
},
new XPathResultToken { NodeType = XPathNodeType.Namespace, HasNameTable = true, Value = "b0" },
new XPathResultToken
{
NodeType = XPathNodeType.Namespace,
LocalName = "xml",
Name = "xml",
HasNameTable = true,
Value = "http://www.w3.org/XML/1998/namespace"
});
;
Utils.XPathNodesetTest(xml, testExpression, expected);
}
/// <summary>
/// position()
/// </summary>
[Fact]
public static void RegressionTestsTest558()
{
var xml = "dummy.xml";
var testExpression = @"position()";
var expected = 1d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// //book[starts-with(@stype,'text')]
/// </summary>
[Fact]
public static void RegressionTestsTest559()
{
var xml = "books.xml";
var testExpression = @"//book[starts-with(@stype,'text')]";
var expected = new XPathResult(0);
;
Utils.XPathNodesetTest(xml, testExpression, expected);
}
/// <summary>
/// //book[starts-with(@stype,'glo')]
/// </summary>
[Fact]
public static void RegressionTestsTest5510()
{
var xml = "books.xml";
var testExpression = @"//book[starts-with(@stype,'glo')]";
var expected = new XPathResult(0);
;
Utils.XPathNodesetTest(xml, testExpression, expected);
}
/// <summary>
/// //book[starts-with(@stype,'')]
/// </summary>
[Fact]
public static void RegressionTestsTest5511()
{
var xml = "books.xml";
var testExpression = @"//book[starts-with(@stype,'')]";
var expected = new XPathResult(0,
new XPathResultToken
{
NodeType = XPathNodeType.Element,
HasChildren = true,
HasAttributes = true,
LocalName = "book",
Name = "book",
HasNameTable = true,
Value =
"\n\t\tSeven Years in Trenton\n\t\t\n\t\t\tJoe\n\t\t\tBob\n\t\t\tTrenton Literary Review Honorable Mention\n\t\t\tUSA\n\t\t\n\t\t12\n\t"
},
new XPathResultToken
{
NodeType = XPathNodeType.Element,
HasChildren = true,
HasAttributes = true,
LocalName = "book",
Name = "book",
HasNameTable = true,
Value =
"\n\t\tHistory of Trenton\n\t\t\n\t\t\tMary\n\t\t\tBob\n\t\t\t\n\t\t\t\tSelected Short Stories of\n\t\t\t\tJoeBob\n\t\t\t\tLoser\n\t\t\t\tUS\n\t\t\t\n\t\t\n\t\t55\n\t"
},
new XPathResultToken
{
NodeType = XPathNodeType.Element,
HasChildren = true,
HasAttributes = true,
LocalName = "book",
Name = "book",
HasNameTable = true,
Value =
"\n\t\tXQL The Golden Years\n\t\t\n\t\t\tMike\n\t\t\tHyman\n\t\t\t\n\t\t\t\tXQL For Dummies\n\t\t\t\tJonathan\n\t\t\t\tMarsh\n\t\t\t\n\t\t\n\t\t55.95\n\t"
},
new XPathResultToken
{
NodeType = XPathNodeType.Element,
HasChildren = true,
HasAttributes = true,
LocalName = "book",
Name = "book",
HasNameTable = true,
Value =
"\n\t\tHistory of Trenton 2\n\t\t\n\t\t\tMary F\n\t\t\tRobinson\n\t\t\t\n\t\t\t\tSelected Short Stories of\n\t\t\t\tMary F\n\t\t\t\tRobinson\n\t\t\t\n\t\t\n\t\t55\n\t"
},
new XPathResultToken
{
NodeType = XPathNodeType.Element,
HasChildren = true,
HasAttributes = true,
LocalName = "book",
Name = "book",
HasNameTable = true,
Value =
"\n\t\tHistory of Trenton Vol 3\n\t\t\n\t\t\tMary F\n\t\t\tRobinson\n\t\t\tFrank\n\t\t\tAnderson\n\t\t\tPulizer\n\t\t\t\n\t\t\t\tSelected Short Stories of\n\t\t\t\tMary F\n\t\t\t\tRobinson\n\t\t\t\n\t\t\n\t\t10\n\t"
},
new XPathResultToken
{
NodeType = XPathNodeType.Element,
HasChildren = true,
HasAttributes = true,
LocalName = "book",
Name = "book",
HasNameTable = true,
Value = "\n\t\tHow To Fix Computers\n\t\t\n\t\t\tHack\n\t\t\ter\n\t\t\tPh.D.\n\t\t\n\t\t08\n\t"
},
new XPathResultToken
{
NodeType = XPathNodeType.Element,
HasChildren = true,
HasAttributes = true,
LocalName = "book",
Name = "book",
HasNameTable = true,
Value =
"\n\t\tTrenton Today, Trenton Tomorrow\n\t\t\n\t\t\tToni\n\t\t\tBob\n\t\t\tB.A.\n\t\t\tPh.D.\n\t\t\tPulizer\n\t\t\tStill in Trenton\n\t\t\tTrenton Forever\n\t\t\n\t\t6.50\n\t\t\n\t\t\tIt was a dark and stormy night.\n\t\t\tBut then all nights in Trenton seem dark and\n\t\t\tstormy to someone who has gone through what\n\t\t\tI have.\n\t\t\t\n\t\t\t\n\t\t\t\tTrenton\n\t\t\t\tmisery\n\t\t\t\n\t\t\n\t"
});
;
Utils.XPathNodesetTest(xml, testExpression, expected);
}
/// <summary>
/// //book[starts-with(@stype,' ')]
/// </summary>
[Fact]
public static void RegressionTestsTest5512()
{
var xml = "books.xml";
var testExpression = @"//book[starts-with(@stype,' ')]";
var expected = new XPathResult(0);
;
Utils.XPathNodesetTest(xml, testExpression, expected);
}
/// <summary>
/// //book[starts-with(@stype,' text')]
/// </summary>
[Fact]
public static void RegressionTestsTest5513()
{
var xml = "books.xml";
var testExpression = @"//book[starts-with(@stype,' text')]";
var expected = new XPathResult(0);
;
Utils.XPathNodesetTest(xml, testExpression, expected);
}
/// <summary>
/// //book[starts-with(@stype,'text ')]
/// </summary>
[Fact]
public static void RegressionTestsTest5514()
{
var xml = "books.xml";
var testExpression = @"//book[starts-with(@stype,'text ')]";
var expected = new XPathResult(0);
;
Utils.XPathNodesetTest(xml, testExpression, expected);
}
/// <summary>
/// last()
/// </summary>
[Fact]
public static void RegressionTestsTest5515()
{
var xml = "books.xml";
var testExpression = @"last()";
var expected = 1d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// /child::MyComputer/descendant::UIntData/descendant::Value//@value
/// last()
/// </summary>
[Fact]
public static void RegressionTestsTest5516()
{
var xml = "t114730.xml";
var testExpression = @"/child::MyComputer/descendant::UIntData/descendant::Value//@value";
var expected = new XPathResult(0);
;
Utils.XPathNodesetTest(xml, testExpression, expected);
}
/// <summary>
/// Execution of XPath expressions like that compare string to node-set with arithmetic operators in context of parent expression results in NRE.
/// </summary>
[Fact]
public static void RegressionTestsTest5519()
{
var xml = "books.xml";
var testExpression = @"/*['6' > *]";
var expected = new XPathResult(0);
;
Utils.XPathNodesetTest(xml, testExpression, expected);
}
/// <summary>
/// Match() String functions inside predicate use wrong context node
/// </summary>
[Fact]
public static void RegressionTestsTest5520()
{
var xml = "bookstore.xml";
var testExpression = @"book[substring-before(local-name(),'store')]";
var expected = new XPathResult(0);
;
Utils.XPathNodesetTest(xml, testExpression, expected);
}
/// <summary>
/// Expected: Line 1 == Line 3, Actual Line 1 == Line 2 (this test cases is Line1==Line2?)
/// count(/*[1]//node()[1]) = count(/*[1]/descendant::node()[1])
/// </summary>
[Fact]
public static void RegressionTestsTest5523()
{
var xml = "bookstore.xml";
var testExpression = @"count(/*[1]//node()[1]) = count(/*[1]/descendant::node()[1])";
var expected = false;
Utils.XPathBooleanTest(xml, testExpression, expected);
}
/// <summary>
/// Expected: Line 1 == Line 3, Actual Line 1 == Line 2 (this test cases is Line1==Line3?)
/// count(/*[1]//node()[1]) = count(/*//node()[1])
/// </summary>
[Fact]
public static void RegressionTestsTest5524()
{
var xml = "bookstore.xml";
var testExpression = @"count(/*[1]//node()[1]) = count(/*//node()[1])";
var expected = true;
Utils.XPathBooleanTest(xml, testExpression, expected);
}
/// <summary>
/// Numeric operators are incorrectly treated as returning boolean
/// not(0+0)
/// </summary>
[Fact]
public static void RegressionTestsTest5525()
{
var xml = "dummy.xml";
var testExpression = @"not(0+0)";
var expected = true;
Utils.XPathBooleanTest(xml, testExpression, expected);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using FluentAssertions.Equivalency;
namespace FluentAssertions.Common
{
public static class TypeExtensions
{
private const BindingFlags PublicMembersFlag =
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
private const BindingFlags AllMembersFlag =
PublicMembersFlag | BindingFlags.NonPublic | BindingFlags.Static;
/// <summary>
/// Determines whether the specified method has been annotated with a specific attribute.
/// </summary>
/// <returns>
/// <c>true</c> if the specified method has attribute; otherwise, <c>false</c>.
/// </returns>
public static bool HasAttribute<TAttribute>(this MemberInfo method) where TAttribute : Attribute
{
return (method.GetCustomAttributes(typeof(TAttribute), true).Any());
}
public static bool HasAttribute<TAttribute>(this Type method) where TAttribute : Attribute
{
#if NEW_REFLECTION
return (method.GetTypeInfo().GetCustomAttributes(typeof(TAttribute), true).Any());
#else
return (method.GetCustomAttributes(typeof(TAttribute), true).Any());
#endif
}
public static bool HasMatchingAttribute<TAttribute>(this MemberInfo type, Expression<Func<TAttribute, bool>> isMatchingAttributePredicate)
where TAttribute : Attribute
{
Func<TAttribute, bool> isMatchingAttribute = isMatchingAttributePredicate.Compile();
return GetCustomAttributes<TAttribute>(type).Any(isMatchingAttribute);
}
public static bool HasMatchingAttribute<TAttribute>(this Type type, Expression<Func<TAttribute, bool>> isMatchingAttributePredicate)
where TAttribute : Attribute
{
Func<TAttribute, bool> isMatchingAttribute = isMatchingAttributePredicate.Compile();
return GetCustomAttributes<TAttribute>(type).Any(isMatchingAttribute);
}
public static bool IsDecoratedWith<TAttribute>(this MemberInfo type)
where TAttribute : Attribute
{
return GetCustomAttributes<TAttribute>(type).Any();
}
public static bool IsDecoratedWith<TAttribute>(this Type type)
where TAttribute : Attribute
{
return GetCustomAttributes<TAttribute>(type).Any();
}
private static IEnumerable<TAttribute> GetCustomAttributes<TAttribute>(MemberInfo type)
{
return type.GetCustomAttributes(false).OfType<TAttribute>();
}
private static IEnumerable<TAttribute> GetCustomAttributes<TAttribute>(Type type)
{
#if NEW_REFLECTION
return type.GetTypeInfo().GetCustomAttributes(false).OfType<TAttribute>();
#else
return type.GetCustomAttributes(false).OfType<TAttribute>();
#endif
}
/// <summary>
/// Determines whether two <see cref="FluentAssertions.Equivalency.SelectedMemberInfo"/> objects refer to the same member.
/// </summary>
public static bool IsEquivalentTo(this SelectedMemberInfo property, SelectedMemberInfo otherProperty)
{
return (property.DeclaringType.IsSameOrInherits(otherProperty.DeclaringType) ||
otherProperty.DeclaringType.IsSameOrInherits(property.DeclaringType)) &&
(property.Name == otherProperty.Name);
}
public static bool IsSameOrInherits(this Type actualType, Type expectedType)
{
return (actualType == expectedType) ||
(expectedType.IsAssignableFrom(actualType));
}
public static bool Implements<TInterface>(this Type type)
{
return Implements(type, typeof (TInterface));
}
/// <summary>
/// NOTE: This method does not give the expected results with open generics
/// </summary>
public static bool Implements(this Type type, Type expectedBaseType)
{
return
expectedBaseType.IsAssignableFrom(type)
&& (type != expectedBaseType);
}
internal static Type[] GetClosedGenericInterfaces(Type type, Type openGenericType)
{
if (type.IsGenericType() && type.GetGenericTypeDefinition() == openGenericType)
{
return new[] { type };
}
Type[] interfaces = type.GetInterfaces();
return
interfaces
.Where(t => (t.IsGenericType() && (t.GetGenericTypeDefinition() == openGenericType)))
.ToArray();
}
public static bool IsComplexType(this Type type)
{
return HasProperties(type) && !AssertionOptions.IsValueType(type);
}
private static bool HasProperties(Type type)
{
return type.GetProperties(PublicMembersFlag).Any();
}
/// <summary>
/// Finds a member by its case-sensitive name.
/// </summary>
/// <returns>
/// Returns <c>null</c> if no such member exists.
/// </returns>
public static SelectedMemberInfo FindMember(this Type type, string memberName, Type preferredType)
{
return SelectedMemberInfo.Create(FindProperty(type, memberName, preferredType)) ??
SelectedMemberInfo.Create(FindField(type, memberName, preferredType));
}
/// <summary>
/// Finds the property by a case-sensitive name.
/// </summary>
/// <returns>
/// Returns <c>null</c> if no such property exists.
/// </returns>
public static PropertyInfo FindProperty(this Type type, string propertyName, Type preferredType)
{
IEnumerable<PropertyInfo> properties =
type.GetProperties(PublicMembersFlag)
.Where(pi => pi.Name == propertyName)
.ToList();
return (properties.Count() > 1)
? properties.SingleOrDefault(p => p.PropertyType == preferredType)
: properties.SingleOrDefault();
}
/// <summary>
/// Finds the field by a case-sensitive name.
/// </summary>
/// <returns>
/// Returns <c>null</c> if no such property exists.
/// </returns>
public static FieldInfo FindField(this Type type, string fieldName, Type preferredType)
{
IEnumerable<FieldInfo> properties =
type.GetFields(PublicMembersFlag)
.Where(pi => pi.Name == fieldName)
.ToList();
return (properties.Count() > 1)
? properties.SingleOrDefault(p => p.FieldType == preferredType)
: properties.SingleOrDefault();
}
public static IEnumerable<SelectedMemberInfo> GetNonPrivateMembers(this Type typeToReflect)
{
return
GetNonPrivateProperties(typeToReflect)
.Select(SelectedMemberInfo.Create)
.Concat(GetNonPrivateFields(typeToReflect).Select(SelectedMemberInfo.Create))
.ToArray();
}
public static IEnumerable<PropertyInfo> GetNonPrivateProperties(this Type typeToReflect, IEnumerable<string> filter = null)
{
var query =
from propertyInfo in GetPropertiesFromHierarchy(typeToReflect)
where HasNonPrivateGetter(propertyInfo)
where !propertyInfo.IsIndexer()
where (filter == null) || filter.Contains(propertyInfo.Name)
select propertyInfo;
return query.ToArray();
}
public static IEnumerable<FieldInfo> GetNonPrivateFields(this Type typeToReflect)
{
var query =
from fieldInfo in GetFieldsFromHierarchy(typeToReflect)
where !fieldInfo.IsPrivate
where !fieldInfo.IsFamily
select fieldInfo;
return query.ToArray();
}
private static IEnumerable<FieldInfo> GetFieldsFromHierarchy(Type typeToReflect)
{
return GetMembersFromHierarchy(typeToReflect, GetPublicFields);
}
private static IEnumerable<PropertyInfo> GetPropertiesFromHierarchy(Type typeToReflect)
{
return GetMembersFromHierarchy(typeToReflect, GetPublicProperties);
}
private static IEnumerable<TMemberInfo> GetMembersFromHierarchy<TMemberInfo>(
Type typeToReflect,
Func<Type, IEnumerable<TMemberInfo>> getMembers) where TMemberInfo : MemberInfo
{
if (IsInterface(typeToReflect))
{
var propertyInfos = new List<TMemberInfo>();
var considered = new List<Type>();
var queue = new Queue<Type>();
considered.Add(typeToReflect);
queue.Enqueue(typeToReflect);
while (queue.Count > 0)
{
var subType = queue.Dequeue();
foreach (var subInterface in GetInterfaces(subType))
{
if (considered.Contains(subInterface))
{
continue;
}
considered.Add(subInterface);
queue.Enqueue(subInterface);
}
IEnumerable<TMemberInfo> typeProperties = getMembers(subType);
IEnumerable<TMemberInfo> newPropertyInfos = typeProperties.Where(x => !propertyInfos.Contains(x));
propertyInfos.InsertRange(0, newPropertyInfos);
}
return propertyInfos.ToArray();
}
else
{
return getMembers(typeToReflect);
}
}
private static bool IsInterface(Type typeToReflect)
{
return typeToReflect.IsInterface();
}
private static IEnumerable<Type> GetInterfaces(Type type)
{
return type.GetInterfaces();
}
private static IEnumerable<PropertyInfo> GetPublicProperties(Type type)
{
return type.GetProperties(PublicMembersFlag);
}
private static IEnumerable<FieldInfo> GetPublicFields(Type type)
{
return type.GetFields(PublicMembersFlag);
}
private static bool HasNonPrivateGetter(PropertyInfo propertyInfo)
{
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
return (getMethod != null) && !getMethod.IsPrivate && !getMethod.IsFamily;
}
public static MethodInfo GetMethod(this Type type, string methodName, IEnumerable<Type> parameterTypes)
{
return type.GetMethods(AllMembersFlag)
.SingleOrDefault(m => m.Name == methodName && m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes));
}
public static bool HasMethod(this Type type, string methodName, IEnumerable<Type> parameterTypes)
{
return type.GetMethod(methodName, parameterTypes) != null;
}
public static MethodInfo GetParameterlessMethod(this Type type, string methodName)
{
return type.GetMethod(methodName, Enumerable.Empty<Type>());
}
public static bool HasParameterlessMethod(this Type type, string methodName)
{
return type.GetParameterlessMethod(methodName) != null;
}
public static PropertyInfo GetPropertyByName(this Type type, string propertyName)
{
return type.GetProperty(propertyName, AllMembersFlag);
}
public static bool HasExplicitlyImplementedProperty(this Type type, Type interfaceType, string propertyName)
{
var hasGetter = type.HasParameterlessMethod(string.Format("{0}.get_{1}", interfaceType.FullName, propertyName));
var hasSetter = type.GetMethods(AllMembersFlag)
.SingleOrDefault(m => m.Name == string.Format("{0}.set_{1}", interfaceType.FullName, propertyName) && m.GetParameters().Count() == 1) != null;
return hasGetter || hasSetter;
}
public static PropertyInfo GetIndexerByParameterTypes(this Type type, IEnumerable<Type> parameterTypes)
{
return type.GetProperties(AllMembersFlag)
.SingleOrDefault(p => p.IsIndexer() && p.GetIndexParameters().Select(i => i.ParameterType).SequenceEqual(parameterTypes));
}
public static bool IsIndexer(this PropertyInfo member)
{
return (member.GetIndexParameters().Length != 0);
}
public static ConstructorInfo GetConstructor(this Type type, IEnumerable<Type> parameterTypes)
{
return type
.GetConstructors(AllMembersFlag)
.SingleOrDefault(m => m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes));
}
}
}
| |
// 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 ShiftRightLogical128BitLaneUInt641()
{
var test = new ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt641();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
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();
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 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 ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt641
{
private struct TestStruct
{
public Vector256<UInt64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt641 testClass)
{
var result = Avx2.ShiftRightLogical128BitLane(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector256<UInt64> _clsVar;
private Vector256<UInt64> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt641()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
}
public ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt641()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)8; }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftRightLogical128BitLane(
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftRightLogical128BitLane(
Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftRightLogical128BitLane(
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftRightLogical128BitLane(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt641();
var result = Avx2.ShiftRightLogical128BitLane(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftRightLogical128BitLane(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftRightLogical128BitLane(test._fld, 1);
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(Vector256<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != 576460752303423488UL)
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i == 2 ? result[i] != 576460752303423488UL : result[i] != 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical128BitLane)}<UInt64>(Vector256<UInt64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using NUnit.Framework;
using ServiceStack.Common.Web;
using ServiceStack.Logging;
using ServiceStack.Logging.Support.Logging;
using ServiceStack.ServiceClient.Web;
using ServiceStack.WebHost.Endpoints.Tests.Support.Host;
namespace ServiceStack.WebHost.Endpoints.Tests
{
[TestFixture]
public class AppHostListenerBaseTests
{
private const string ListeningOn = "http://localhost:82/";
ExampleAppHostHttpListener appHost;
static AppHostListenerBaseTests()
{
LogManager.LogFactory = new ConsoleLogFactory();
}
[TestFixtureSetUp]
public void OnTestFixtureStartUp()
{
appHost = new ExampleAppHostHttpListener();
appHost.Init();
appHost.Start(ListeningOn);
System.Console.WriteLine("ExampleAppHost Created at {0}, listening on {1}",
DateTime.Now, ListeningOn);
}
[TestFixtureTearDown]
public void OnTestFixtureTearDown()
{
appHost.Dispose();
appHost = null;
}
[Test]
public void Root_path_redirects_to_metadata_page()
{
var html = ListeningOn.DownloadUrl();
Assert.That(html.Contains("The following operations are supported."));
}
[Test]
public void Can_download_webpage_html_page()
{
var html = (ListeningOn + "webpage.html").DownloadUrl();
Assert.That(html.Contains("Default index ServiceStack.WebHost.Endpoints.Tests page"));
}
[Test]
public void Can_download_requestinfo_json()
{
var html = (ListeningOn + "_requestinfo").DownloadUrl();
Assert.That(html.Contains("\"Host\":"));
}
[Test]
public void Gets_404_on_non_existant_page()
{
var webRes = (ListeningOn + "nonexistant.html").GetErrorResponse();
Assert.That(webRes.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public void Gets_403_on_page_with_non_whitelisted_extension()
{
var webRes = (ListeningOn + "webpage.forbidden").GetErrorResponse();
Assert.That(webRes.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
}
[Test]
public void Can_call_GetFactorial_WebService()
{
var client = new XmlServiceClient(ListeningOn);
var request = new GetFactorial { ForNumber = 3 };
var response = client.Send<GetFactorialResponse>(request);
Assert.That(response.Result, Is.EqualTo(GetFactorialService.GetFactorial(request.ForNumber)));
}
[Test]
public void Can_call_jsv_debug_on_GetFactorial_WebService()
{
const string url = ListeningOn + "jsv/syncreply/GetFactorial?ForNumber=3&debug=true";
var contents = new StreamReader(WebRequest.Create(url).GetResponse().GetResponseStream()).ReadToEnd();
Console.WriteLine("JSV DEBUG: " + contents);
Assert.That(contents, Is.Not.Null);
}
[Test]
public void Calling_missing_web_service_does_not_break_HttpListener()
{
var missingUrl = ListeningOn + "missing.html";
int errorCount = 0;
try
{
new StreamReader(WebRequest.Create(missingUrl).GetResponse().GetResponseStream()).ReadToEnd();
}
catch (Exception ex)
{
errorCount++;
Console.WriteLine("Error [{0}]: {1}", ex.GetType().Name, ex.Message);
}
try
{
new StreamReader(WebRequest.Create(missingUrl).GetResponse().GetResponseStream()).ReadToEnd();
}
catch (Exception ex)
{
errorCount++;
Console.WriteLine("Error [{0}]: {1}", ex.GetType().Name, ex.Message);
}
Assert.That(errorCount, Is.EqualTo(2));
}
[Test]
public void Can_call_MoviesZip_WebService()
{
var client = new JsonServiceClient(ListeningOn);
var request = new MoviesZip();
var response = client.Send<MoviesZipResponse>(request);
Assert.That(response.Movies.Count, Is.GreaterThan(0));
}
[Test]
public void Calling_not_implemented_method_returns_405()
{
var client = new JsonServiceClient(ListeningOn);
try
{
var response = client.Put<MoviesZipResponse>("movies.zip", new MoviesZip());
Assert.Fail("Should throw 405 excetpion");
}
catch (WebServiceException ex)
{
Assert.That(ex.StatusCode, Is.EqualTo(405));
}
}
[Test]
public void Can_GET_single_gethttpresult_using_RestClient_with_JSONP_from_service_returning_HttpResult()
{
var url = ListeningOn + "gethttpresult?callback=cb";
string response;
var webReq = (HttpWebRequest)WebRequest.Create(url);
webReq.Accept = "*/*";
using (var webRes = webReq.GetResponse())
{
Assert.That(webRes.ContentType, Is.StringStarting(ContentType.Json));
response = webRes.DownloadText();
}
Assert.That(response, Is.Not.Null, "No response received");
Console.WriteLine(response);
Assert.That(response, Is.StringStarting("cb("));
Assert.That(response, Is.StringEnding(")"));
}
[Test, Ignore]
public void DebugHost()
{
Thread.Sleep(180 * 1000);
}
[Test, Ignore]
public void PerformanceTest()
{
const int clientCount = 500;
var threads = new List<Thread>(clientCount);
ThreadPool.SetMinThreads(500, 50);
ThreadPool.SetMaxThreads(1000, 50);
for (int i = 0; i < clientCount; i++)
{
threads.Add(new Thread(() =>
{
var html = (ListeningOn + "long_running").DownloadUrl();
}));
}
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < clientCount; i++)
{
threads[i].Start();
}
for (int i = 0; i < clientCount; i++)
{
threads[i].Join();
}
sw.Stop();
Trace.TraceInformation("Elapsed time for " + clientCount + " requests : " + sw.Elapsed);
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class AttributeSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public AttributeSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new AttributeSignatureHelpProvider();
}
#region "Regular tests"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParameters()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
}
[[|Something($$|]]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <summary>Summary For Attribute</summary>
public SomethingAttribute() { }
}
[[|Something($$|]]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", "Summary For Attribute", null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public SomethingAttribute(int someInteger, string someString) { }
}
[[|Something($$|]]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <summary>
/// Summary For Attribute
/// </summary>
/// <param name=""someInteger"">Param someInteger</param>
/// <param name=""someString"">Param someString</param>
public SomethingAttribute(int someInteger, string someString) { }
}
[[|Something($$
|]class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someInteger", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public SomethingAttribute(int someInteger, string someString) { }
}
[[|Something(22, $$|]]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <summary>
/// Summary For Attribute
/// </summary>
/// <param name=""someInteger"">Param someInteger</param>
/// <param name=""someString"">Param someString</param>
public SomethingAttribute(int someInteger, string someString) { }
}
[[|Something(22, $$
|]class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someString", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithClosingParen()
{
var markup = @"
class SomethingAttribute : System.Attribute
{ }
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationSpan1()
{
await TestAsync(
@"using System;
class C
{
[[|Obsolete($$|])]
void Foo()
{
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationSpan2()
{
await TestAsync(
@"using System;
class C
{
[[|Obsolete( $$|])]
void Foo()
{
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationSpan3()
{
await TestAsync(
@"using System;
class C
{
[[|Obsolete(
$$|]]
void Foo()
{
}
}");
}
#endregion
#region "Current Parameter Name"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
using System;
class SomethingAttribute : Attribute
{
public SomethingAttribute(int someParameter, bool somethingElse) { }
}
[[|Something(somethingElse: false, someParameter: $$22|])]
class C
{
}";
await VerifyCurrentParameterNameAsync(markup, "someParameter");
}
#endregion
#region "Setting fields in attributes"
[WorkItem(545425)]
[WorkItem(544139)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithValidField()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo;
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute({CSharpEditorResources.Properties}: [foo = int])", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithInvalidFieldReadonly()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public readonly int foo;
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithInvalidFieldStatic()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public static int foo;
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithInvalidFieldConst()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public const int foo = 42;
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Setting properties in attributes"
[WorkItem(545425)]
[WorkItem(544139)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithValidProperty()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo { get; set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute({CSharpEditorResources.Properties}: [foo = int])", string.Empty, string.Empty, currentParameterIndex: 0));
// TODO: Bug 12319: Enable tests for script when this is fixed.
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithInvalidPropertyStatic()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public static int foo { get; set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithInvalidPropertyNoSetter()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo { get { return 0; } }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithInvalidPropertyNoGetter()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo { set { } }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithInvalidPropertyPrivateGetter()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo { private get; set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithInvalidPropertyPrivateSetter()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo { get; private set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Setting fields and arguments"
[WorkItem(545425)]
[WorkItem(544139)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithArgumentsAndNamedParameters1()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <param name=""foo"">FooParameter</param>
/// <param name=""bar"">BarParameter</param>
public SomethingAttribute(int foo = 0, string bar = null) { }
public int fieldfoo { get; set; }
public string fieldbar { get; set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int foo = 0], [string bar = null], {CSharpEditorResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "FooParameter", currentParameterIndex: 0));
// TODO: Bug 12319: Enable tests for script when this is fixed.
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[WorkItem(545425)]
[WorkItem(544139)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithArgumentsAndNamedParameters2()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <param name=""foo"">FooParameter</param>
/// <param name=""bar"">BarParameter</param>
public SomethingAttribute(int foo = 0, string bar = null) { }
public int fieldfoo { get; set; }
public string fieldbar { get; set; }
}
[[|Something(22, $$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int foo = 0], [string bar = null], {CSharpEditorResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "BarParameter", currentParameterIndex: 1));
// TODO: Bug 12319: Enable tests for script when this is fixed.
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[WorkItem(545425)]
[WorkItem(544139)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithArgumentsAndNamedParameters3()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <param name=""foo"">FooParameter</param>
/// <param name=""bar"">BarParameter</param>
public SomethingAttribute(int foo = 0, string bar = null) { }
public int fieldfoo { get; set; }
public string fieldbar { get; set; }
}
[[|Something(22, null, $$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int foo = 0], [string bar = null], {CSharpEditorResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, string.Empty, currentParameterIndex: 2));
// TODO: Bug 12319: Enable tests for script when this is fixed.
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[WorkItem(545425)]
[WorkItem(544139)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithOptionalArgumentAndNamedParameterWithSameName1()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <param name=""foo"">FooParameter</param>
public SomethingAttribute(int foo = 0) { }
public int foo { get; set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int foo = 0], {CSharpEditorResources.Properties}: [foo = int])", string.Empty, "FooParameter", currentParameterIndex: 0));
// TODO: Bug 12319: Enable tests for script when this is fixed.
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[WorkItem(545425)]
[WorkItem(544139)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestAttributeWithOptionalArgumentAndNamedParameterWithSameName2()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <param name=""foo"">FooParameter</param>
public SomethingAttribute(int foo = 0) { }
public int foo { get; set; }
}
[[|Something(22, $$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int foo = 0], {CSharpEditorResources.Properties}: [foo = int])", string.Empty, string.Empty, currentParameterIndex: 1));
// TODO: Bug 12319: Enable tests for script when this is fixed.
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
#endregion
#region "Trigger tests"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerParens()
{
var markup = @"
using System;
class SomethingAttribute : Attribute
{
public SomethingAttribute(int someParameter, bool somethingElse) { }
}
[[|Something($$|])]
class C
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
using System;
class SomethingAttribute : Attribute
{
public SomethingAttribute(int someParameter, bool somethingElse) { }
}
[[|Something(22,$$|])]
class C
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
using System;
class SomethingAttribute : Attribute
{
public SomethingAttribute(int someParameter, bool somethingElse) { }
}
[[|Something(22, $$|])]
class C
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Attribute_BrowsableAlways()
{
var markup = @"
[MyAttribute($$
class Program
{
}";
var referencedCode = @"
public class MyAttribute
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public MyAttribute(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Attribute_BrowsableNever()
{
var markup = @"
[MyAttribute($$
class Program
{
}";
var referencedCode = @"
public class MyAttribute
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public MyAttribute(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Attribute_BrowsableAdvanced()
{
var markup = @"
[MyAttribute($$
class Program
{
}";
var referencedCode = @"
public class MyAttribute
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public MyAttribute(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Attribute_BrowsableMixed()
{
var markup = @"
[MyAttribute($$
class Program
{
}";
var referencedCode = @"
public class MyAttribute
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public MyAttribute(int x)
{
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public MyAttribute(int x, int y)
{
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("MyAttribute(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret : System.Attribute
{
}
#endif
[Secret($$
void Foo()
{
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret : System.Attribute
{
}
#endif
#if BAR
[Secret($$
void Foo()
{
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WorkItem(1067933)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// [foo($$";
await TestAsync(markup);
}
[WorkItem(1081535)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithBadParameterList()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
}
[Something{$$]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems);
}
}
}
| |
using System.ComponentModel;
using System.Linq;
using NetGore.IO;
using NetGore.World;
using SFML.Graphics;
namespace NetGore.Graphics
{
/// <summary>
/// Describes a single light.
/// </summary>
public class Light : ILight
{
const string _colorValueKey = "Color";
const string _isEnabledValueKey = "IsEnabled";
const string _positionValueKey = "Position";
const string _rotationValueKey = "Rotation";
const string _sizeValueKey = "Size";
const string _spriteValueKey = "Sprite";
Color _color = Color.White;
Vector2 _position;
ISpatial _positionProvider;
Vector2 _size = new Vector2(128);
/// <summary>
/// Initializes a new instance of the <see cref="Light"/> class.
/// </summary>
public Light()
{
IsEnabled = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="Light"/> class.
/// </summary>
/// <param name="reader">The <see cref="IValueReader"/> to read the initial light state from.</param>
public Light(IValueReader reader)
{
ReadState(reader);
}
/// <summary>
/// Handles when the <see cref="ILight.PositionProvider"/> moves.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs{Vector2}"/> instance containing the event data.</param>
void PositionProvider_Moved(ISpatial sender, EventArgs<Vector2> e)
{
_position = sender.Position;
}
#region ILight Members
/// <summary>
/// Notifies listeners when this <see cref="ISpatial"/> has moved.
/// </summary>
public event TypedEventHandler<ISpatial, EventArgs<Vector2>> Moved;
/// <summary>
/// Notifies listeners when this <see cref="ISpatial"/> has been resized.
/// </summary>
public event TypedEventHandler<ISpatial, EventArgs<Vector2>> Resized;
/// <summary>
/// Gets or sets the center position of the <see cref="ISpatial"/>.
/// </summary>
[Browsable(false)]
public Vector2 Center
{
get { return Position + (Size / 2f); }
set { Position = value - (Size / 2f); }
}
/// <summary>
/// Gets or sets the color of the light. The alpha value has no affect and will always be set to 255.
/// </summary>
[DisplayName("Color")]
[Description("The color of the light. The alpha value has no affect and will always be set to 255.")]
[DefaultValue(typeof(Color), "{255, 255, 255, 255}")]
[Browsable(true)]
public Color Color
{
get { return _color; }
set { _color = new Color(value.R, value.G, value.B, 255); }
}
/// <summary>
/// Gets or sets if this light is enabled.
/// </summary>
[DisplayName("Enabled")]
[Description("If this light is enabled.")]
[DefaultValue(true)]
[Browsable(true)]
public bool IsEnabled { get; set; }
/// <summary>
/// Gets the world coordinates of the bottom-right corner of this <see cref="ISpatial"/>.
/// </summary>
[Browsable(false)]
public Vector2 Max
{
get { return Position + Size; }
}
/// <summary>
/// Gets the world coordinates of the top-left corner of this <see cref="ISpatial"/>.
/// </summary>
[DisplayName("Position")]
[Description("The world position of the light.")]
[Browsable(true)]
public Vector2 Position
{
get { return _position; }
set
{
if (_position == value)
return;
var oldValue = _position;
_position = value;
if (Moved != null)
Moved.Raise(this, EventArgsHelper.Create(oldValue));
}
}
/// <summary>
/// Gets or sets an <see cref="ISpatial"/> that provides the position to use. If set, the
/// <see cref="ISpatial.Position"/> value will automatically be acquired with the position of the
/// <see cref="ISpatial"/> instead, and setting the position will have no affect.
/// </summary>
[Browsable(false)]
public ISpatial PositionProvider
{
get { return _positionProvider; }
set
{
if (_positionProvider == value)
return;
if (_positionProvider != null)
_positionProvider.Moved -= PositionProvider_Moved;
_positionProvider = value;
if (_positionProvider != null)
{
_positionProvider.Moved -= PositionProvider_Moved;
_positionProvider.Moved += PositionProvider_Moved;
_position = _positionProvider.Center;
}
}
}
/// <summary>
/// Gets or sets the amount to rotate the <see cref="ILight"/> in radians.
/// </summary>
[DisplayName("Rotation")]
[Description("The amount to rotate the light in radians.")]
[DefaultValue(0f)]
[Browsable(true)]
public float Rotation { get; set; }
/// <summary>
/// Gets or sets the size of this <see cref="ILight"/>.
/// </summary>
[DisplayName("Size")]
[Description("The size of the light.")]
[Browsable(true)]
public Vector2 Size
{
get { return _size; }
set
{
if (_size == value)
return;
var oldSize = _size;
_size = value;
if (Resized != null)
Resized.Raise(this, EventArgsHelper.Create(oldSize));
}
}
/// <summary>
/// Gets or sets the <see cref="Grh"/> used to draw the light. If null, the light will not be drawn.
/// </summary>
[DisplayName("Sprite")]
[Description("The sprite used to draw the light.")]
[Browsable(true)]
public Grh Sprite { get; set; }
/// <summary>
/// Gets if this <see cref="ISpatial"/> can ever be moved with <see cref="ISpatial.TryMove"/>.
/// </summary>
bool ISpatial.SupportsMove
{
get { return true; }
}
/// <summary>
/// Gets if this <see cref="ISpatial"/> can ever be resized with <see cref="ISpatial.TryResize"/>.
/// </summary>
bool ISpatial.SupportsResize
{
get { return true; }
}
/// <summary>
/// Gets or sets an object that can be used to identify or store information about this <see cref="ILight"/>.
/// This property is purely optional.
/// </summary>
[Browsable(false)]
public object Tag { get; set; }
/// <summary>
/// Draws the <see cref="ILight"/>.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to draw with.</param>
public void Draw(ISpriteBatch spriteBatch)
{
// Skip when not enabled
if (!IsEnabled)
return;
// Make sure we have a valid sprite
var s = Sprite;
if (s == null)
return;
// Draw
var scale = Size / s.Size;
s.Draw(spriteBatch, Position, Color, SpriteEffects.None, Rotation, scale / 2f, scale);
}
/// <summary>
/// Translates this <see cref="ILight"/> relative to the current position.
/// </summary>
/// <param name="offset">The amount to move from the current position.</param>
public void Move(Vector2 offset)
{
Position += offset;
}
/// <summary>
/// Reads the state of the object from an <see cref="IValueReader"/>. Values should be read in the exact
/// same order as they were written.
/// </summary>
/// <param name="reader">The <see cref="IValueReader"/> to read the values from.</param>
public void ReadState(IValueReader reader)
{
PositionProvider = null;
Tag = null;
Position = reader.ReadVector2(_positionValueKey);
Size = reader.ReadVector2(_sizeValueKey);
Color = reader.ReadColor(_colorValueKey);
Rotation = reader.ReadFloat(_rotationValueKey);
IsEnabled = reader.ReadBool(_isEnabledValueKey);
var grhIndex = reader.ReadGrhIndex(_spriteValueKey);
if (!grhIndex.IsInvalid)
Sprite = new Grh(grhIndex, AnimType.Loop, 0);
else
Sprite = null;
}
/// <summary>
/// Sets the size of this <see cref="ILight"/>.
/// </summary>
/// <param name="newSize">The new size.</param>
public void Resize(Vector2 newSize)
{
Size = newSize;
}
/// <summary>
/// Sets the center position of the <see cref="ILight"/>.
/// </summary>
/// <param name="value">The new center.</param>
public void SetCenter(Vector2 value)
{
Center = value;
}
/// <summary>
/// Moves this <see cref="ILight"/> to a new position.
/// </summary>
/// <param name="newPosition">The new position.</param>
public void Teleport(Vector2 newPosition)
{
Position = newPosition;
}
/// <summary>
/// Gets a <see cref="Rectangle"/> that represents the world area that this <see cref="ISpatial"/> occupies.
/// </summary>
/// <returns>A <see cref="Rectangle"/> that represents the world area that this <see cref="ISpatial"/>
/// occupies.</returns>
public Rectangle ToRectangle()
{
return SpatialHelper.ToRectangle(this);
}
/// <summary>
/// Tries to move the <see cref="ISpatial"/>.
/// </summary>
/// <param name="newPos">The new position.</param>
/// <returns>True if the <see cref="ISpatial"/> was moved to the <paramref name="newPos"/>; otherwise false.</returns>
bool ISpatial.TryMove(Vector2 newPos)
{
Position = newPos;
return true;
}
/// <summary>
/// Tries to resize the <see cref="ISpatial"/>.
/// </summary>
/// <param name="newSize">The new size.</param>
/// <returns>True if the <see cref="ISpatial"/> was resized to the <paramref name="newSize"/>; otherwise false.</returns>
bool ISpatial.TryResize(Vector2 newSize)
{
Size = newSize;
return true;
}
/// <summary>
/// Updates the <see cref="ILight"/>.
/// </summary>
/// <param name="currentTime">The current game time in milliseconds.</param>
public void Update(TickCount currentTime)
{
// Skip when not enabled
if (!IsEnabled)
return;
// Update our sprite (if we have one)
var s = Sprite;
if (s != null)
s.Update(currentTime);
}
/// <summary>
/// Writes the state of the object to an <see cref="IValueWriter"/>.
/// </summary>
/// <param name="writer">The <see cref="IValueWriter"/> to write the values to.</param>
public void WriteState(IValueWriter writer)
{
writer.Write(_positionValueKey, Position);
writer.Write(_sizeValueKey, Size);
writer.Write(_colorValueKey, Color);
writer.Write(_rotationValueKey, Rotation);
writer.Write(_isEnabledValueKey, IsEnabled);
writer.Write(_spriteValueKey, Sprite != null ? Sprite.GrhData.GrhIndex : GrhIndex.Invalid);
}
#endregion
}
}
| |
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2004, 2006-2010 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.Net;
using System.Collections;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using X509Cert = System.Security.Cryptography.X509Certificates;
using Mono.Security.X509;
using Mono.Security.X509.Extensions;
using Mono.Security.Interface;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsServerCertificate : HandshakeMessage
{
#region Fields
private X509CertificateCollection certificates;
#endregion
#region Constructors
public TlsServerCertificate(Context context, byte[] buffer)
: base(context, HandshakeType.Certificate, buffer)
{
}
#endregion
#region Methods
public override void Update()
{
base.Update();
this.Context.ServerSettings.Certificates = this.certificates;
this.Context.ServerSettings.UpdateCertificateRSA();
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
this.certificates = new X509CertificateCollection();
int readed = 0;
int length = this.ReadInt24();
while (readed < length)
{
// Read certificate length
int certLength = ReadInt24();
// Increment readed
readed += 3;
if (certLength > 0)
{
// Read certificate data
byte[] buffer = this.ReadBytes(certLength);
// Create a new X509 Certificate
X509Certificate certificate = new X509Certificate(buffer);
certificates.Add(certificate);
readed += certLength;
DebugHelper.WriteLine(
String.Format("Server Certificate {0}", certificates.Count),
buffer);
}
}
this.validateCertificates(certificates);
}
#endregion
#region Private Methods
// Note: this method only works for RSA certificates
// DH certificates requires some changes - does anyone use one ?
private bool checkCertificateUsage (X509Certificate cert)
{
ClientContext context = (ClientContext)this.Context;
// certificate extensions are required for this
// we "must" accept older certificates without proofs
if (cert.Version < 3)
return true;
KeyUsages ku = KeyUsages.none;
switch (context.Negotiating.Cipher.ExchangeAlgorithmType)
{
case ExchangeAlgorithmType.RsaSign:
ku = KeyUsages.digitalSignature;
break;
case ExchangeAlgorithmType.RsaKeyX:
ku = KeyUsages.keyEncipherment;
break;
case ExchangeAlgorithmType.DiffieHellman:
ku = KeyUsages.keyAgreement;
break;
case ExchangeAlgorithmType.Fortezza:
return false; // unsupported certificate type
}
KeyUsageExtension kux = null;
ExtendedKeyUsageExtension eku = null;
X509Extension xtn = cert.Extensions ["2.5.29.15"];
if (xtn != null)
kux = new KeyUsageExtension (xtn);
xtn = cert.Extensions ["2.5.29.37"];
if (xtn != null)
eku = new ExtendedKeyUsageExtension (xtn);
if ((kux != null) && (eku != null))
{
// RFC3280 states that when both KeyUsageExtension and
// ExtendedKeyUsageExtension are present then BOTH should
// be valid
if (!kux.Support (ku))
return false;
return (eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.1") ||
eku.KeyPurpose.Contains ("2.16.840.1.113730.4.1"));
}
else if (kux != null)
{
return kux.Support (ku);
}
else if (eku != null)
{
// Server Authentication (1.3.6.1.5.5.7.3.1) or
// Netscape Server Gated Crypto (2.16.840.1.113730.4)
return (eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.1") ||
eku.KeyPurpose.Contains ("2.16.840.1.113730.4.1"));
}
// last chance - try with older (deprecated) Netscape extensions
xtn = cert.Extensions ["2.16.840.1.113730.1.1"];
if (xtn != null)
{
NetscapeCertTypeExtension ct = new NetscapeCertTypeExtension (xtn);
return ct.Support (NetscapeCertTypeExtension.CertTypes.SslServer);
}
// if the CN=host (checked later) then we assume this is meant for SSL/TLS
// e.g. the new smtp.gmail.com certificate
return true;
}
private void validateCertificates(X509CertificateCollection certificates)
{
ClientContext context = (ClientContext)this.Context;
AlertDescription description = AlertDescription.BadCertificate;
#if INSIDE_SYSTEM
// This helps the linker to remove a lot of validation code that will never be used since
// System.dll will, for OSX and iOS, uses the operating system X.509 certificate validations
RemoteValidation (context, description);
#else
if (context.SslStream.HaveRemoteValidation2Callback)
RemoteValidation (context, description);
else
LocalValidation (context, description);
#endif
}
void RemoteValidation (ClientContext context, AlertDescription description)
{
ValidationResult res = context.SslStream.RaiseServerCertificateValidation2 (certificates);
if (res.Trusted)
return;
long error = res.ErrorCode;
switch (error) {
case 0x800B0101:
description = AlertDescription.CertificateExpired;
break;
case 0x800B010A:
description = AlertDescription.UnknownCA;
break;
case 0x800B0109:
description = AlertDescription.UnknownCA;
break;
default:
description = AlertDescription.CertificateUnknown;
break;
}
string err = String.Format ("Invalid certificate received from server. Error code: 0x{0:x}", error);
throw new TlsException (description, err);
}
void LocalValidation (ClientContext context, AlertDescription description)
{
// the leaf is the web server certificate
X509Certificate leaf = certificates [0];
X509Cert.X509CertificateMono cert = new X509Cert.X509CertificateMono (leaf.RawData);
ArrayList errors = new ArrayList();
// SSL specific check - not all certificates can be
// used to server-side SSL some rules applies after
// all ;-)
if (!checkCertificateUsage (leaf))
{
// WinError.h CERT_E_PURPOSE 0x800B0106
errors.Add ((int)-2146762490);
}
// SSL specific check - does the certificate match
// the host ?
if (!checkServerIdentity (leaf))
{
// WinError.h CERT_E_CN_NO_MATCH 0x800B010F
errors.Add ((int)-2146762481);
}
// Note: building and verifying a chain can take much time
// so we do it last (letting simple things fails first)
// Note: In TLS the certificates MUST be in order (and
// optionally include the root certificate) so we're not
// building the chain using LoadCertificate (it's faster)
// Note: IIS doesn't seem to send the whole certificate chain
// but only the server certificate :-( it's assuming that you
// already have this chain installed on your computer. duh!
// http://groups.google.ca/groups?q=IIS+server+certificate+chain&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=85058s%24avd%241%40nnrp1.deja.com&rnum=3
// we must remove the leaf certificate from the chain
X509CertificateCollection chain = new X509CertificateCollection (certificates);
chain.Remove (leaf);
X509Chain verify = new X509Chain (chain);
bool result = false;
try
{
result = verify.Build (leaf);
}
catch (Exception)
{
result = false;
}
if (!result)
{
switch (verify.Status)
{
case X509ChainStatusFlags.InvalidBasicConstraints:
// WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019
errors.Add ((int)-2146869223);
break;
case X509ChainStatusFlags.NotSignatureValid:
// WinError.h TRUST_E_BAD_DIGEST 0x80096010
errors.Add ((int)-2146869232);
break;
case X509ChainStatusFlags.NotTimeNested:
// WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102
errors.Add ((int)-2146762494);
break;
case X509ChainStatusFlags.NotTimeValid:
// WinError.h CERT_E_EXPIRED 0x800B0101
description = AlertDescription.CertificateExpired;
errors.Add ((int)-2146762495);
break;
case X509ChainStatusFlags.PartialChain:
// WinError.h CERT_E_CHAINING 0x800B010A
description = AlertDescription.UnknownCA;
errors.Add ((int)-2146762486);
break;
case X509ChainStatusFlags.UntrustedRoot:
// WinError.h CERT_E_UNTRUSTEDROOT 0x800B0109
description = AlertDescription.UnknownCA;
errors.Add ((int)-2146762487);
break;
default:
// unknown error
description = AlertDescription.CertificateUnknown;
errors.Add ((int)verify.Status);
break;
}
}
int[] certificateErrors = (int[])errors.ToArray(typeof(int));
if (!context.SslStream.RaiseServerCertificateValidation(
cert,
certificateErrors))
{
throw new TlsException(
description,
"Invalid certificate received from server.");
}
}
// RFC2818 - HTTP Over TLS, Section 3.1
// http://www.ietf.org/rfc/rfc2818.txt
//
// 1. if present MUST use subjectAltName dNSName as identity
// 1.1. if multiples entries a match of any one is acceptable
// 1.2. wildcard * is acceptable
// 2. URI may be an IP address -> subjectAltName.iPAddress
// 2.1. exact match is required
// 3. Use of the most specific Common Name (CN=) in the Subject
// 3.1 Existing practice but DEPRECATED
private bool checkServerIdentity (X509Certificate cert)
{
ClientContext context = (ClientContext)this.Context;
string targetHost = context.ClientSettings.TargetHost;
X509Extension ext = cert.Extensions ["2.5.29.17"];
// 1. subjectAltName
if (ext != null)
{
SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext);
// 1.1 - multiple dNSName
foreach (string dns in subjectAltName.DNSNames)
{
// 1.2 TODO - wildcard support
if (Match (targetHost, dns))
return true;
}
// 2. ipAddress
foreach (string ip in subjectAltName.IPAddresses)
{
// 2.1. Exact match required
if (ip == targetHost)
return true;
}
}
// 3. Common Name (CN=)
return checkDomainName (cert.SubjectName);
}
private bool checkDomainName(string subjectName)
{
ClientContext context = (ClientContext)this.Context;
string domainName = String.Empty;
Regex search = new Regex(@"CN\s*=\s*([^,]*)");
MatchCollection elements = search.Matches(subjectName);
if (elements.Count == 1)
{
if (elements[0].Success)
{
domainName = elements[0].Groups[1].Value.ToString();
}
}
return Match (context.ClientSettings.TargetHost, domainName);
}
// ensure the pattern is valid wrt to RFC2595 and RFC2818
// http://www.ietf.org/rfc/rfc2595.txt
// http://www.ietf.org/rfc/rfc2818.txt
static bool Match (string hostname, string pattern)
{
// check if this is a pattern
int index = pattern.IndexOf ('*');
if (index == -1) {
// not a pattern, do a direct case-insensitive comparison
return (String.Compare (hostname, pattern, true, CultureInfo.InvariantCulture) == 0);
}
// check pattern validity
// A "*" wildcard character MAY be used as the left-most name component in the certificate.
// unless this is the last char (valid)
if (index != pattern.Length - 1) {
// then the next char must be a dot .'.
if (pattern [index + 1] != '.')
return false;
}
// only one (A) wildcard is supported
int i2 = pattern.IndexOf ('*', index + 1);
if (i2 != -1)
return false;
// match the end of the pattern
string end = pattern.Substring (index + 1);
int length = hostname.Length - end.Length;
// no point to check a pattern that is longer than the hostname
if (length <= 0)
return false;
if (String.Compare (hostname, length, end, 0, end.Length, true, CultureInfo.InvariantCulture) != 0)
return false;
// special case, we start with the wildcard
if (index == 0) {
// ensure we hostname non-matched part (start) doesn't contain a dot
int i3 = hostname.IndexOf ('.');
return ((i3 == -1) || (i3 >= (hostname.Length - end.Length)));
}
// match the start of the pattern
string start = pattern.Substring (0, index);
return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableSortedSetTest : ImmutableSetTest
{
private enum Operation
{
Add,
Union,
Remove,
Except,
Last,
}
protected override bool IncludesGetHashCodeDerivative
{
get { return false; }
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedSet<int>();
var actual = ImmutableSortedSet<int>.Empty;
int seed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Debug.WriteLine("Adding \"{0}\" to the set.", value);
expected.Add(value);
actual = actual.Add(value);
break;
case Operation.Union:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Debug.WriteLine("Adding {0} elements to the set.", inputLength);
expected.UnionWith(values);
actual = actual.Union(values);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
int element = expected.Skip(position).First();
Debug.WriteLine("Removing element \"{0}\" from the set.", element);
Assert.True(expected.Remove(element));
actual = actual.Remove(element);
}
break;
case Operation.Except:
var elements = expected.Where(el => random.Next(2) == 0).ToArray();
Debug.WriteLine("Removing {0} elements from the set.", elements.Length);
expected.ExceptWith(elements);
actual = actual.Except(elements);
break;
}
Assert.Equal<int>(expected.ToList(), actual.ToList());
}
}
[Fact]
[ActiveIssue(780)]
public void EmptyTest()
{
this.EmptyTestHelper(Empty<int>(), 5, null);
this.EmptyTestHelper(Empty<string>().ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.Ordinal),
true,
new[] { "apple", "APPLE" },
new[] { "APPLE", "apple" });
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase),
true,
new[] { "apple", "APPLE" },
new[] { "apple" });
}
[Fact]
public void ChangeSortComparer()
{
var ordinalSet = ImmutableSortedSet<string>.Empty
.WithComparer(StringComparer.Ordinal)
.Add("apple")
.Add("APPLE");
Assert.Equal(2, ordinalSet.Count); // claimed count
Assert.False(ordinalSet.Contains("aPpLe"));
var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, ignoreCaseSet.Count);
Assert.True(ignoreCaseSet.Contains("aPpLe"));
}
[Fact]
public void ToUnorderedTest()
{
var result = ImmutableSortedSet<int>.Empty.Add(3).ToImmutableHashSet();
Assert.True(result.Contains(3));
}
[Fact]
public void ToImmutableSortedSetFromArrayTest()
{
var set = new[] { 1, 2, 2 }.ToImmutableSortedSet();
Assert.Same(Comparer<int>.Default, set.KeyComparer);
Assert.Equal(2, set.Count);
}
[Theory]
[InlineData(new int[] { }, new int[] { })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })]
[InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })]
public void ToImmutableSortedSetFromEnumerableTest(int[] input, int[] expectedOutput)
{
IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces
var set = enumerableInput.ToImmutableSortedSet();
Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray());
}
[Theory]
[InlineData(new int[] { }, new int[] { 1 })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })]
[InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })]
public void UnionWithEnumerableTest(int[] input, int[] expectedOutput)
{
IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces
var set = ImmutableSortedSet.Create(1).Union(enumerableInput);
Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray());
}
[Fact]
public void IndexOfTest()
{
var set = ImmutableSortedSet<int>.Empty;
Assert.Equal(~0, set.IndexOf(5));
set = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
Assert.Equal(0, set.IndexOf(10));
Assert.Equal(1, set.IndexOf(20));
Assert.Equal(4, set.IndexOf(50));
Assert.Equal(8, set.IndexOf(90));
Assert.Equal(9, set.IndexOf(100));
Assert.Equal(~0, set.IndexOf(5));
Assert.Equal(~1, set.IndexOf(15));
Assert.Equal(~2, set.IndexOf(25));
Assert.Equal(~5, set.IndexOf(55));
Assert.Equal(~9, set.IndexOf(95));
Assert.Equal(~10, set.IndexOf(105));
}
[Fact]
public void IndexGetTest()
{
var set = ImmutableSortedSet<int>.Empty
.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
int i = 0;
foreach (var item in set)
{
AssertAreSame(item, set[i++]);
}
Assert.Throws<ArgumentOutOfRangeException>(() => set[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => set[set.Count]);
}
[Fact]
public void ReverseTest()
{
var range = Enumerable.Range(1, 10);
var set = ImmutableSortedSet<int>.Empty.Union(range);
var expected = range.Reverse().ToList();
var actual = set.Reverse().ToList();
Assert.Equal<int>(expected, actual);
}
[Fact]
public void MaxTest()
{
Assert.Equal(5, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Max);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Max);
}
[Fact]
public void MinTest()
{
Assert.Equal(1, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Min);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Min);
}
[Fact]
public void InitialBulkAdd()
{
Assert.Equal(1, Empty<int>().Union(new[] { 1, 1 }).Count);
Assert.Equal(2, Empty<int>().Union(new[] { 1, 2 }).Count);
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> set = ImmutableSortedSet.Create<string>();
Assert.Throws<NotSupportedException>(() => set.Add("a"));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove("a"));
Assert.True(set.IsReadOnly);
}
[Fact]
public void IListOfTMethods()
{
IList<string> set = ImmutableSortedSet.Create<string>("b");
Assert.Throws<NotSupportedException>(() => set.Insert(0, "a"));
Assert.Throws<NotSupportedException>(() => set.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => set[0] = "a");
Assert.Equal("b", set[0]);
Assert.True(set.IsReadOnly);
}
[Fact]
public void UnionOptimizationsTest()
{
var set = ImmutableSortedSet.Create(1, 2, 3);
var builder = set.ToBuilder();
Assert.Same(set, ImmutableSortedSet.Create<int>().Union(builder));
Assert.Same(set, set.Union(ImmutableSortedSet.Create<int>()));
var smallSet = ImmutableSortedSet.Create(1);
var unionSet = smallSet.Union(set);
Assert.Same(set, unionSet); // adding a larger set to a smaller set is reversed, and then the smaller in this case has nothing unique
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
var set = ImmutableSortedSet.Create<string>();
Assert.Equal(0, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create<string>(comparer);
Assert.Equal(0, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a");
Assert.Equal(1, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a");
Assert.Equal(1, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a", "b");
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a", "b");
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
}
[Fact]
public void IListMethods()
{
IList list = ImmutableSortedSet.Create("a", "b");
Assert.True(list.Contains("a"));
Assert.Equal("a", list[0]);
Assert.Equal("b", list[1]);
Assert.Equal(0, list.IndexOf("a"));
Assert.Equal(1, list.IndexOf("b"));
Assert.Throws<NotSupportedException>(() => list.Add("b"));
Assert.Throws<NotSupportedException>(() => list[3] = "c");
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, "b"));
Assert.Throws<NotSupportedException>(() => list.Remove("a"));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.True(list.IsFixedSize);
Assert.True(list.IsReadOnly);
}
[Fact]
public void TryGetValueTest()
{
this.TryGetValueTestHelper(ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedSet.Create<int>();
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedSet.Create<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableSortedSet.Create<string>("1", "2", "3"));
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSortedSet.Create<object>(), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
}
protected override IImmutableSet<T> Empty<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected ImmutableSortedSet<T> EmptyTyped<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected override ISet<T> EmptyMutable<T>()
{
return new SortedSet<T>();
}
internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
{
return ((ImmutableSortedSet<T>)set).Root;
}
/// <summary>
/// Tests various aspects of a sorted set.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
/// <param name="value">A value that could be placed in the set.</param>
/// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IComparer<T> comparer)
{
Contract.Requires(emptySet != null);
this.EmptyTestHelper(emptySet);
Assert.Same(emptySet, emptySet.ToImmutableSortedSet(comparer));
Assert.Same(comparer ?? Comparer<T>.Default, ((ISortKeyCollection<T>)emptySet).KeyComparer);
var reemptied = emptySet.Add(value).Clear();
Assert.Same(reemptied, reemptied.ToImmutableSortedSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
}
}
}
| |
using System.Linq;
using WebSharper.UI.Next;
using WebSharper.UI.Next.Client;
using WebSharper.UI.Next.CSharp;
using WebSharper.UI.Next.CSharp.Client;
using static WebSharper.UI.Next.CSharp.Client.Html;
using WebSharper;
using WebSharper.Sitelets;
using WebSharper.JavaScript;
using Microsoft.FSharp.Core;
//using CDoc = WebSharper.UI.Next.Client.Doc;
//using CAttr = WebSharper.UI.Next.Client.Attr;
using System.Threading.Tasks;
using System;
namespace WebSharper.UI.Next.CSharp.Tests
{
[JavaScript]
public class App
{
public class Name
{
public string First;
public string Last;
private Name() { }
public Name(string first, string last)
{
First = first;
Last = last;
}
}
[EndPoint("/person")]
public class Person
{
public Name Name;
[Query]
public int? Age;
private Person() { }
public Person(Name name, int? age)
{
Name = name;
Age = age;
}
}
[EndPoint("/people")]
public class People
{
public Name[] people;
}
[EndPoint("/")]
public class Home { }
public class LoginData
{
public string Username { get; set; }
public string Password { get; set; }
}
//void Animating()
//{
// // define animations that can be parametrized by start and end times
// Func<double, double, Anim<double>> linearAnim =
// (start, end) => Anim.Simple(Interpolation.Double, new Easing(x => x), 300, start, end);
// Func<double, double, Anim<double>> cubicAnim =
// (start, end) => Anim.Simple(Interpolation.Double, Easing.CubicInOut, 300, start, end);
// // define the transition with a cubic in and out and linear in between
// var swipeTransition =
// new Trans<double>(linearAnim, x => cubicAnim(x - 100, x), x => cubicAnim(x, x + 100));
// var rvLeftPos = Var.Create<double>(0);
// var animatedDoc =
// div(
// style("position", "relative"),
// // TODO + with object and string
// style("left", swipeTransition, rvLeftPos.View, pos => pos + "%"),
// "content"
// );
//}
void DocConstruction()
{
//var rvUsername = Var.Create("");
//var rvPassword = Var.Create("");
//var vLoginData =
// rvUsername.View.Map2(rvPassword.View, (username, password) =>
// new LoginData { Username = username, Password = password });
//var sLoginData = Submitter.Create(vLoginData, null);
//var vLoginResult = sLoginData.View.MapAsync(async login => await Rpc.Login(login));
//div(
// input(rvUsername),
// passwordBox(rvPassword),
// button("Log in", sLoginData.Trigger),
// vLoginResult.Map(res => Doc.Empty)
//);
//{
// Doc myDoc = Doc.TextNode("WebSharper");
// //WebSharper.UI.Next.Client.Doc
// // myDoc HTML equivalent is now: WebSharper
//}
//{
// var myDoc = Doc.SvgElement("rect",
// new[] {
// Attr.Create("width", "150"),
// Attr.Create("height", "120")
// }, Enumerable.Empty<Doc>());
//}
//{
// var myDoc =
// Doc.Append(
// text("Visit "),
// a(attr.href("http://websharper.com"), "WebSharper"));
//}
//WebSharper.UI.Next.CSharp.Client.Html.textarea
//inputArea();
}
static async Task<string> LoginUser(string u, string p)
{
await Task.Delay(500);
return "Done";
}
void LoginForm()
{
//type LoginData = { Username: string; Password: string }
//var rvSubmit = Var.Create<object>(null);
//var rvUsername = Var.Create("");
//var rvPassword = Var.Create("");
//var vLoginResult =
// rvUsername.View.Bind(u =>
// rvPassword.View.Map(p =>
// new { Username = u, Password = p }
// )
// ).SnapshotOn(null, rvSubmit.View).MapAsync(async res => LoginUser)
}
[SPAEntryPoint]
public static void Main()
{
var people = ListModel.FromSeq(new[] { "John", "Paul" });
var newName = Var.Create("");
var routed = new RouteMapBuilder()
.With<Home>((go, _) => {
var first = Var.Create("John");
var last = Var.Create("Doe");
var age = Var.Create(20);
return div(
input(first),
input(last),
input(age),
button("Go", () =>
go(new Person(new Name(first.Value, last.Value),
age.Value == 0 ? null : (int?) age.Value)))
);
})
.With<Person>((go, p) =>
div(p.Name.First, " ", p.Name.Last,
p.Age == null ? " won't tell their age!" : $" is {p.Age} years old!",
button("Back", () => go(new Home()))
)
)
.With<People>((go, p) =>
ul(p.people.Select(x => li(x.First, " ", x.Last)).ToArray())
)
.Install();
div(
h1("My list of unique people"),
ul(people.View.DocSeqCached((string x) => li(x))),
div(
input(newName, attr.placeholder("Name")),
button("Add", () =>
{
people.Add(newName.Value);
newName.Value = "";
}),
div(newName.View)
),
h1("Routed element:"),
routed
).RunById("main");
}
public class TaskItem
{
public string Name { get; private set; }
public Var<bool> Done { get; private set; }
public TaskItem(string name, bool done)
{
Name = name;
Done = Var.Create(done);
}
}
public void TodoApp()
{
var Tasks =
new ListModel<string, TaskItem>(task => task.Name) {
new TaskItem("Have breakfast", true),
new TaskItem("Have lunch", false)
};
var NewTaskName = Var.Create("");
Template.Template.Main.Doc(
ListContainer: Tasks.View.DocSeqCached((TaskItem task) =>
Template.Template.ListItem.Doc(
Task: task.Name,
Clear: (el, ev) => Tasks.RemoveByKey(task.Name),
Done: task.Done,
ShowDone: attr.@class("checked", task.Done.View, x => x)
)
),
NewTaskName: NewTaskName,
Add: (el, ev) =>
{
Tasks.Add(new TaskItem(NewTaskName.Value, false));
NewTaskName.Value = "";
},
ClearCompleted: (el, ev) => Tasks.RemoveBy(task => task.Done.Value)
).RunById("tasks");
}
}
}
| |
//
// CustomScrollViewPort.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using SWC = System.Windows.Controls;
using WSize = System.Windows.Size;
namespace Xwt.WPFBackend
{
internal class CustomScrollViewPort
: SWC.Panel, IScrollInfo
{
internal CustomScrollViewPort (object widget, SWC.ScrollViewer scrollOwner, ScrollAdjustmentBackend verticalBackend, ScrollAdjustmentBackend horizontalBackend)
{
if (widget == null)
throw new ArgumentNullException ("widget");
ScrollOwner = scrollOwner;
((FrameworkElement)widget).RenderTransform = this.transform;
if (verticalBackend != null) {
usingCustomScrolling = true;
verticalBackend.TargetViewport = this;
this.verticalBackend = verticalBackend;
horizontalBackend.TargetViewport = this;
this.horizontalBackend = horizontalBackend;
UpdateCustomExtent ();
}
Children.Add ((UIElement) widget);
}
public bool CanHorizontallyScroll
{
get;
set;
}
public bool CanVerticallyScroll
{
get;
set;
}
public double ExtentHeight
{
get { return this.extent.Height; }
}
public double ExtentWidth
{
get { return this.extent.Width; }
}
public double ViewportHeight
{
get { return this.viewport.Height; }
}
public double ViewportWidth
{
get { return this.viewport.Width; }
}
public double VerticalOffset
{
get { return this.contentOffset.Y; }
}
public double HorizontalOffset
{
get { return this.contentOffset.X; }
}
public void LineDown()
{
SetVerticalOffset (VerticalOffset + VerticalStepIncrement);
}
public void LineLeft()
{
SetHorizontalOffset (HorizontalOffset - HorizontalStepIncrement);
}
public void LineRight()
{
SetHorizontalOffset (HorizontalOffset + HorizontalStepIncrement);
}
public void LineUp()
{
SetVerticalOffset (VerticalOffset - VerticalStepIncrement);
}
public Rect MakeVisible (Visual visual, Rect rectangle)
{
// This is the area which is currently visible
var visibleRect = new Rect (HorizontalOffset, VerticalOffset, ViewportWidth, ViewportHeight);
// This is the area we wish to be visible
rectangle = visual.TransformToAncestor (this).TransformBounds (rectangle);
if (visibleRect == rectangle)
return rectangle;
// The co-ordinates are relative to the visible area, so we need to add the visible area offset
// to convert to values we can use in VerticalOffset/HorizontalOffset
rectangle.X += visibleRect.X;
rectangle.Y += visibleRect.Y;
SetHorizontalOffset (ClampOffset (visibleRect.Left, visibleRect.Right, rectangle.Left, rectangle.Right));
SetVerticalOffset (ClampOffset (visibleRect.Top, visibleRect.Bottom, rectangle.Top, rectangle.Bottom));
return rectangle;
}
private double ClampOffset (double lowerVisible, double upperVisible, double desiredLower, double desiredUpper)
{
// This is not entirely correct. The 'else' statement needs to be improved
// so we scroll the minimum required distance as opposed to just jumping
// to 'desiredLower' if our element doesn't already fit perfectly
if (desiredLower >= lowerVisible && desiredUpper < upperVisible)
return lowerVisible;
else
return desiredLower;
}
public void MouseWheelDown()
{
SetVerticalOffset (VerticalOffset + 60);
}
public void MouseWheelLeft()
{
SetHorizontalOffset (HorizontalOffset - 60);
}
public void MouseWheelRight()
{
SetHorizontalOffset (HorizontalOffset + 60);
}
public void MouseWheelUp()
{
SetVerticalOffset (VerticalOffset - 60);
}
public void PageDown()
{
SetVerticalOffset (VerticalOffset + VerticalPageIncrement);
}
public void PageLeft()
{
SetHorizontalOffset (HorizontalOffset - HorizontalPageIncrement);
}
public void PageRight()
{
SetHorizontalOffset (HorizontalOffset + HorizontalPageIncrement);
}
public void PageUp()
{
SetVerticalOffset (VerticalOffset - VerticalPageIncrement);
}
public SWC.ScrollViewer ScrollOwner
{
get;
set;
}
public void SetHorizontalOffset (double offset) => SetOffset (x: offset);
public void SetVerticalOffset (double offset) => SetOffset (y: offset);
public void SetOffset (ScrollAdjustmentBackend scroller, double offset)
{
if (scroller == verticalBackend)
SetVerticalOffset (offset);
else
SetHorizontalOffset (offset);
}
void SetOffset (double? x = null, double? y = null)
{
var offset = this.contentOffset;
if (x.HasValue)
offset.X = x.Value;
if (y.HasValue)
offset.Y = y.Value;
// Clamp horizontal
if (offset.X < 0 || this.viewport.Width >= this.extent.Width)
offset.X = 0;
else if (offset.X + this.viewport.Width >= this.extent.Width)
offset.X = this.extent.Width - this.viewport.Width;
// Clamp vertical
if (offset.Y < 0 || this.viewport.Height >= this.extent.Height)
offset.Y = 0;
else if (offset.Y + this.viewport.Height >= this.extent.Height)
offset.Y = this.extent.Height - this.viewport.Height;
if (offset != this.contentOffset) {
this.contentOffset = offset;
if (usingCustomScrolling) {
this.horizontalBackend.SetOffset (offset.X);
this.verticalBackend.SetOffset (offset.Y);
} else {
this.transform.X = -offset.X;
this.transform.Y = -offset.Y;
}
if (ScrollOwner != null)
ScrollOwner.InvalidateScrollInfo ();
}
}
public void UpdateCustomExtent ()
{
// Updates the extent and the viewport, based on the scrollbar properties
var newExtent = new WSize (horizontalBackend.UpperValue - horizontalBackend.LowerValue, verticalBackend.UpperValue - verticalBackend.LowerValue);
var newViewport = new WSize (horizontalBackend.PageSize, verticalBackend.PageSize);
if (newViewport.Width > newExtent.Width)
newViewport.Width = newExtent.Width;
if (newViewport.Height > newExtent.Height)
newViewport.Height = newExtent.Height;
if (extent != newExtent || viewport != newViewport) {
extent = newExtent;
viewport = newViewport;
if (!viewportAdjustmentQueued) {
viewportAdjustmentQueued = true;
Application.MainLoop.QueueExitAction (delegate
{
// Adjust the position, if it now falls outside the extents.
// Doing it in an exit action to make sure the adjustement
// is made only once for all changes in the scrollbar properties
viewportAdjustmentQueued = false;
if (contentOffset.X + viewport.Width > extent.Width)
SetHorizontalOffset (extent.Width - viewport.Width);
if (contentOffset.Y + viewport.Height > extent.Height)
SetVerticalOffset (extent.Height - viewport.Height);
if (ScrollOwner != null)
ScrollOwner.InvalidateScrollInfo ();
});
}
}
}
private readonly TranslateTransform transform = new TranslateTransform();
private readonly ScrollAdjustmentBackend verticalBackend;
private readonly ScrollAdjustmentBackend horizontalBackend;
private readonly bool usingCustomScrolling;
private bool viewportAdjustmentQueued;
private Point contentOffset;
private WSize extent = new WSize (0, 0);
private WSize viewport = new WSize (0, 0);
private static readonly WSize InfiniteSize
= new System.Windows.Size (Double.PositiveInfinity, Double.PositiveInfinity);
protected double VerticalPageIncrement
{
get { return (this.verticalBackend != null) ? this.verticalBackend.PageIncrement : ViewportHeight; }
}
protected double HorizontalPageIncrement
{
get { return (this.horizontalBackend != null) ? this.horizontalBackend.PageIncrement : ViewportWidth; }
}
protected double VerticalStepIncrement
{
get { return (this.verticalBackend != null) ? this.verticalBackend.StepIncrement : VerticalPageIncrement / 10; }
}
protected double HorizontalStepIncrement
{
get { return (this.horizontalBackend != null) ? this.horizontalBackend.StepIncrement : HorizontalPageIncrement / 10; }
}
protected override WSize MeasureOverride (WSize constraint)
{
FrameworkElement child = (FrameworkElement) InternalChildren [0];
if (usingCustomScrolling) {
// Measure the child using the constraint because when using custom scrolling,
// the child is not really scrolled (its contents are) and its size is whatever
// the scroll view decides to assign to the viewport, so the constraint
// must be satisfied
child.Measure (constraint);
return child.DesiredSize;
}
else {
// We only use child size for the dimensions that scrolling is disabled. This
// allows the child to properly influence the measure of the scroll view in that
// case.
child.Measure (InfiniteSize);
var sz = child.DesiredSize;
return new WSize (CanHorizontallyScroll? 0 : sz.Width, CanVerticallyScroll? 0 : sz.Height);
}
}
protected override System.Windows.Size ArrangeOverride (System.Windows.Size finalSize)
{
FrameworkElement child = (FrameworkElement)InternalChildren [0];
WSize childSize = child.DesiredSize;
// The child has to fill all the available space in the ScrollView
// if the ScrollView happens to be bigger than the space required by the child
if (childSize.Height < finalSize.Height)
childSize.Height = finalSize.Height;
if (childSize.Width < finalSize.Width)
childSize.Width = finalSize.Width;
if (!usingCustomScrolling) {
// The viewport and extent doesn't have to be set when using custom scrolling, since they
// are fully controlled by the child widget through the scroll adjustments
if (this.extent != childSize) {
this.extent = childSize;
ScrollOwner.InvalidateScrollInfo ();
}
if (this.viewport != finalSize) {
this.viewport = finalSize;
ScrollOwner.InvalidateScrollInfo ();
}
// It's possible our child is now smaller than our viewport, in which case we need to
// update the content offset, otherwise the child may be scrolled entirely out of view.
SetOffset ();
}
child.Arrange (new Rect (0, 0, childSize.Width, childSize.Height));
child.UpdateLayout ();
if (child is IWpfWidget)
((IWidgetSurface)(((IWpfWidget)child).Backend.Frontend)).Reallocate ();
return finalSize;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
namespace Umbraco.Core
{
/// <summary>
/// The XmlHelper class contains general helper methods for working with xml in umbraco.
/// </summary>
public class XmlHelper
{
/// <summary>
/// Gets a value indicating whether a specified string contains only xml whitespace characters.
/// </summary>
/// <param name="s">The string.</param>
/// <returns><c>true</c> if the string contains only xml whitespace characters.</returns>
/// <remarks>As per XML 1.1 specs, space, \t, \r and \n.</remarks>
public static bool IsXmlWhitespace(string s)
{
// as per xml 1.1 specs - anything else is significant whitespace
s = s.Trim(' ', '\t', '\r', '\n');
return s.Length == 0;
}
/// <summary>
/// Creates a new <c>XPathDocument</c> from an xml string.
/// </summary>
/// <param name="xml">The xml string.</param>
/// <returns>An <c>XPathDocument</c> created from the xml string.</returns>
public static XPathDocument CreateXPathDocument(string xml)
{
return new XPathDocument(new XmlTextReader(new StringReader(xml)));
}
/// <summary>
/// Tries to create a new <c>XPathDocument</c> from an xml string.
/// </summary>
/// <param name="xml">The xml string.</param>
/// <param name="doc">The XPath document.</param>
/// <returns>A value indicating whether it has been possible to create the document.</returns>
public static bool TryCreateXPathDocument(string xml, out XPathDocument doc)
{
try
{
doc = CreateXPathDocument(xml);
return true;
}
catch (Exception)
{
doc = null;
return false;
}
}
/// <summary>
/// Tries to create a new <c>XPathDocument</c> from a property value.
/// </summary>
/// <param name="value">The value of the property.</param>
/// <param name="doc">The XPath document.</param>
/// <returns>A value indicating whether it has been possible to create the document.</returns>
/// <remarks>The value can be anything... Performance-wise, this is bad.</remarks>
public static bool TryCreateXPathDocumentFromPropertyValue(object value, out XPathDocument doc)
{
// DynamicNode.ConvertPropertyValueByDataType first cleans the value by calling
// XmlHelper.StripDashesInElementOrAttributeName - this is because the XML is
// to be returned as a DynamicXml and element names such as "value-item" are
// invalid and must be converted to "valueitem". But we don't have that sort of
// problem here - and we don't need to bother with dashes nor dots, etc.
doc = null;
var xml = value as string;
if (xml == null) return false; // no a string
if (CouldItBeXml(xml) == false) return false; // string does not look like it's xml
if (IsXmlWhitespace(xml)) return false; // string is whitespace, xml-wise
if (TryCreateXPathDocument(xml, out doc) == false) return false; // string can't be parsed into xml
var nav = doc.CreateNavigator();
if (nav.MoveToFirstChild())
{
var name = nav.LocalName; // must not match an excluded tag
if (UmbracoConfig.For.UmbracoSettings().Scripting.NotDynamicXmlDocumentElements.All(x => x.Element.InvariantEquals(name) == false)) return true;
}
doc = null;
return false;
}
/// <summary>
/// Tries to create a new <c>XElement</c> from a property value.
/// </summary>
/// <param name="value">The value of the property.</param>
/// <param name="elt">The Xml element.</param>
/// <returns>A value indicating whether it has been possible to create the element.</returns>
/// <remarks>The value can be anything... Performance-wise, this is bad.</remarks>
public static bool TryCreateXElementFromPropertyValue(object value, out XElement elt)
{
// see note above in TryCreateXPathDocumentFromPropertyValue...
elt = null;
var xml = value as string;
if (xml == null) return false; // not a string
if (CouldItBeXml(xml) == false) return false; // string does not look like it's xml
if (IsXmlWhitespace(xml)) return false; // string is whitespace, xml-wise
try
{
elt = XElement.Parse(xml, LoadOptions.None);
}
catch
{
elt = null;
return false; // string can't be parsed into xml
}
var name = elt.Name.LocalName; // must not match an excluded tag
if (UmbracoConfig.For.UmbracoSettings().Scripting.NotDynamicXmlDocumentElements.All(x => x.Element.InvariantEquals(name) == false)) return true;
elt = null;
return false;
}
/// <summary>
/// Sorts the children of a parentNode.
/// </summary>
/// <param name="parentNode">The parent node.</param>
/// <param name="childNodesXPath">An XPath expression to select children of <paramref name="parentNode"/> to sort.</param>
/// <param name="orderBy">A function returning the value to order the nodes by.</param>
internal static void SortNodes(
XmlNode parentNode,
string childNodesXPath,
Func<XmlNode, int> orderBy)
{
var sortedChildNodes = parentNode.SelectNodes(childNodesXPath).Cast<XmlNode>()
.OrderBy(orderBy)
.ToArray();
// append child nodes to last position, in sort-order
// so all child nodes will go after the property nodes
foreach (var node in sortedChildNodes)
parentNode.AppendChild(node); // moves the node to the last position
}
/// <summary>
/// Sorts the children of a parentNode if needed.
/// </summary>
/// <param name="parentNode">The parent node.</param>
/// <param name="childNodesXPath">An XPath expression to select children of <paramref name="parentNode"/> to sort.</param>
/// <param name="orderBy">A function returning the value to order the nodes by.</param>
/// <returns>A value indicating whether sorting was needed.</returns>
/// <remarks>same as SortNodes but will do nothing if nodes are already sorted - should improve performances.</remarks>
internal static bool SortNodesIfNeeded(
XmlNode parentNode,
string childNodesXPath,
Func<XmlNode, int> orderBy)
{
// ensure orderBy runs only once per node
// checks whether nodes are already ordered
// and actually sorts only if needed
var childNodesAndOrder = parentNode.SelectNodes(childNodesXPath).Cast<XmlNode>()
.Select(x => Tuple.Create(x, orderBy(x))).ToArray();
var a = 0;
foreach (var x in childNodesAndOrder)
{
if (a > x.Item2)
{
a = -1;
break;
}
a = x.Item2;
}
if (a >= 0)
return false;
// append child nodes to last position, in sort-order
// so all child nodes will go after the property nodes
foreach (var x in childNodesAndOrder.OrderBy(x => x.Item2))
parentNode.AppendChild(x.Item1); // moves the node to the last position
return true;
}
/// <summary>
/// Sorts a single child node of a parentNode.
/// </summary>
/// <param name="parentNode">The parent node.</param>
/// <param name="childNodesXPath">An XPath expression to select children of <paramref name="parentNode"/> to sort.</param>
/// <param name="node">The child node to sort.</param>
/// <param name="orderBy">A function returning the value to order the nodes by.</param>
/// <returns>A value indicating whether sorting was needed.</returns>
/// <remarks>Assuming all nodes but <paramref name="node"/> are sorted, this will move the node to
/// the right position without moving all the nodes (as SortNodes would do) - should improve perfs.</remarks>
internal static bool SortNode(
XmlNode parentNode,
string childNodesXPath,
XmlNode node,
Func<XmlNode, int> orderBy)
{
var nodeSortOrder = orderBy(node);
var childNodesAndOrder = parentNode.SelectNodes(childNodesXPath).Cast<XmlNode>()
.Select(x => Tuple.Create(x, orderBy(x))).ToArray();
// find the first node with a sortOrder > node.sortOrder
var i = 0;
while (i < childNodesAndOrder.Length && childNodesAndOrder[i].Item2 <= nodeSortOrder)
i++;
// if one was found
if (i < childNodesAndOrder.Length)
{
// and node is just before, we're done already
// else we need to move it right before the node that was found
if (i > 0 && childNodesAndOrder[i - 1].Item1 != node)
{
parentNode.InsertBefore(node, childNodesAndOrder[i].Item1);
return true;
}
}
else
{
// and node is the last one, we're done already
// else we need to append it as the last one
if (i > 0 && childNodesAndOrder[i - 1].Item1 != node)
{
parentNode.AppendChild(node);
return true;
}
}
return false;
}
// used by DynamicNode only, see note in TryCreateXPathDocumentFromPropertyValue
public static string StripDashesInElementOrAttributeNames(string xml)
{
using (var outputms = new MemoryStream())
{
using (TextWriter outputtw = new StreamWriter(outputms))
{
using (var ms = new MemoryStream())
{
using (var tw = new StreamWriter(ms))
{
tw.Write(xml);
tw.Flush();
ms.Position = 0;
using (var tr = new StreamReader(ms))
{
bool IsInsideElement = false, IsInsideQuotes = false;
int ic = 0;
while ((ic = tr.Read()) != -1)
{
if (ic == (int)'<' && !IsInsideQuotes)
{
if (tr.Peek() != (int)'!')
{
IsInsideElement = true;
}
}
if (ic == (int)'>' && !IsInsideQuotes)
{
IsInsideElement = false;
}
if (ic == (int)'"')
{
IsInsideQuotes = !IsInsideQuotes;
}
if (!IsInsideElement || ic != (int)'-' || IsInsideQuotes)
{
outputtw.Write((char)ic);
}
}
}
}
}
outputtw.Flush();
outputms.Position = 0;
using (TextReader outputtr = new StreamReader(outputms))
{
return outputtr.ReadToEnd();
}
}
}
}
/// <summary>
/// Imports a XML node from text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="xmlDoc">The XML doc.</param>
/// <returns></returns>
public static XmlNode ImportXmlNodeFromText(string text, ref XmlDocument xmlDoc)
{
xmlDoc.LoadXml(text);
return xmlDoc.FirstChild;
}
/// <summary>
/// Opens a file as a XmlDocument.
/// </summary>
/// <param name="filePath">The relative file path. ei. /config/umbraco.config</param>
/// <returns>Returns a XmlDocument class</returns>
public static XmlDocument OpenAsXmlDocument(string filePath)
{
var reader = new XmlTextReader(IOHelper.MapPath(filePath)) {WhitespaceHandling = WhitespaceHandling.All};
var xmlDoc = new XmlDocument();
//Load the file into the XmlDocument
xmlDoc.Load(reader);
//Close off the connection to the file.
reader.Close();
return xmlDoc;
}
/// <summary>
/// creates a XmlAttribute with the specified name and value
/// </summary>
/// <param name="xd">The xmldocument.</param>
/// <param name="name">The name of the attribute.</param>
/// <param name="value">The value of the attribute.</param>
/// <returns>a XmlAttribute</returns>
public static XmlAttribute AddAttribute(XmlDocument xd, string name, string value)
{
var temp = xd.CreateAttribute(name);
temp.Value = value;
return temp;
}
/// <summary>
/// Creates a text XmlNode with the specified name and value
/// </summary>
/// <param name="xd">The xmldocument.</param>
/// <param name="name">The node name.</param>
/// <param name="value">The node value.</param>
/// <returns>a XmlNode</returns>
public static XmlNode AddTextNode(XmlDocument xd, string name, string value)
{
var temp = xd.CreateNode(XmlNodeType.Element, name, "");
temp.AppendChild(xd.CreateTextNode(value));
return temp;
}
/// <summary>
/// Creates a cdata XmlNode with the specified name and value
/// </summary>
/// <param name="xd">The xmldocument.</param>
/// <param name="name">The node name.</param>
/// <param name="value">The node value.</param>
/// <returns>A XmlNode</returns>
public static XmlNode AddCDataNode(XmlDocument xd, string name, string value)
{
var temp = xd.CreateNode(XmlNodeType.Element, name, "");
temp.AppendChild(xd.CreateCDataSection(value));
return temp;
}
/// <summary>
/// Gets the value of a XmlNode
/// </summary>
/// <param name="n">The XmlNode.</param>
/// <returns>the value as a string</returns>
public static string GetNodeValue(XmlNode n)
{
var value = string.Empty;
if (n == null || n.FirstChild == null)
return value;
value = n.FirstChild.Value ?? n.InnerXml;
return value.Replace("<!--CDATAOPENTAG-->", "<![CDATA[").Replace("<!--CDATACLOSETAG-->", "]]>");
}
/// <summary>
/// Determines whether the specified string appears to be XML.
/// </summary>
/// <param name="xml">The XML string.</param>
/// <returns>
/// <c>true</c> if the specified string appears to be XML; otherwise, <c>false</c>.
/// </returns>
public static bool CouldItBeXml(string xml)
{
if (string.IsNullOrEmpty(xml)) return false;
xml = xml.Trim();
return xml.StartsWith("<") && xml.EndsWith(">") && xml.Contains('/');
}
/// <summary>
/// Splits the specified delimited string into an XML document.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="separator">The separator.</param>
/// <param name="rootName">Name of the root.</param>
/// <param name="elementName">Name of the element.</param>
/// <returns>Returns an <c>System.Xml.XmlDocument</c> representation of the delimited string data.</returns>
public static XmlDocument Split(string data, string[] separator, string rootName, string elementName)
{
return Split(new XmlDocument(), data, separator, rootName, elementName);
}
/// <summary>
/// Splits the specified delimited string into an XML document.
/// </summary>
/// <param name="xml">The XML document.</param>
/// <param name="data">The delimited string data.</param>
/// <param name="separator">The separator.</param>
/// <param name="rootName">Name of the root node.</param>
/// <param name="elementName">Name of the element node.</param>
/// <returns>Returns an <c>System.Xml.XmlDocument</c> representation of the delimited string data.</returns>
public static XmlDocument Split(XmlDocument xml, string data, string[] separator, string rootName, string elementName)
{
// load new XML document.
xml.LoadXml(string.Concat("<", rootName, "/>"));
// get the data-value, check it isn't empty.
if (!string.IsNullOrEmpty(data))
{
// explode the values into an array
var values = data.Split(separator, StringSplitOptions.None);
// loop through the array items.
foreach (string value in values)
{
// add each value to the XML document.
var xn = XmlHelper.AddTextNode(xml, elementName, value);
xml.DocumentElement.AppendChild(xn);
}
}
// return the XML node.
return xml;
}
/// <summary>
/// Return a dictionary of attributes found for a string based tag
/// </summary>
/// <param name="tag"></param>
/// <returns></returns>
public static Dictionary<string, string> GetAttributesFromElement(string tag)
{
var m =
Regex.Matches(tag, "(?<attributeName>\\S*)=\"(?<attributeValue>[^\"]*)\"",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
// fix for issue 14862: return lowercase attributes for case insensitive matching
var d = m.Cast<Match>().ToDictionary(attributeSet => attributeSet.Groups["attributeName"].Value.ToString().ToLower(), attributeSet => attributeSet.Groups["attributeValue"].Value.ToString());
return d;
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using DotSpatial.Data;
using DotSpatial.Serialization;
using DotSpatial.Symbology;
using GeoAPI.Geometries;
namespace DotSpatial.Controls
{
/// <summary>
/// This is a specialized FeatureLayer that specifically handles line drawing.
/// </summary>
public class MapLineLayer : LineLayer, IMapLineLayer
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MapLineLayer"/> class that is empty with a line feature set that has no members.
/// </summary>
public MapLineLayer()
: base(new FeatureSet(FeatureType.Line))
{
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="MapLineLayer"/> class.
/// </summary>
/// <param name="inFeatureSet">The line feature set used as data source.</param>
public MapLineLayer(IFeatureSet inFeatureSet)
: base(inFeatureSet)
{
Configure();
OnFinishedLoading();
}
/// <summary>
/// Initializes a new instance of the <see cref="MapLineLayer"/> class.
/// </summary>
/// <param name="featureSet">A featureset that contains lines</param>
/// <param name="container">An IContainer that the line layer should be created in</param>
public MapLineLayer(IFeatureSet featureSet, ICollection<ILayer> container)
: base(featureSet, container, null)
{
Configure();
OnFinishedLoading();
}
/// <summary>
/// Initializes a new instance of the <see cref="MapLineLayer"/> class, but passes the boolean
/// notFinished variable to indicate whether or not this layer should fire the FinishedLoading event.
/// </summary>
/// <param name="featureSet">The line feature set used as data source.</param>
/// <param name="container">An IContainer that the line layer should be created in.</param>
/// <param name="notFinished">Indicates whether the OnFinishedLoading event should be suppressed after loading finished.</param>
public MapLineLayer(IFeatureSet featureSet, ICollection<ILayer> container, bool notFinished)
: base(featureSet, container, null)
{
Configure();
if (notFinished == false) OnFinishedLoading();
}
#endregion
#region Events
/// <summary>
/// Fires an event that indicates to the parent map-frame that it should first
/// redraw the specified clip
/// </summary>
public event EventHandler<ClipArgs> BufferChanged;
#endregion
#region Properties
/// <summary>
/// Gets or sets the back buffer that will be drawn to as part of the initialization process.
/// </summary>
[ShallowCopy]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Image BackBuffer { get; set; }
/// <summary>
/// Gets or sets the current buffer.
/// </summary>
[ShallowCopy]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Image Buffer { get; set; }
/// <summary>
/// Gets or sets the geographic region represented by the buffer
/// Calling Initialize will set this automatically.
/// </summary>
[ShallowCopy]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Envelope BufferEnvelope { get; set; }
/// <summary>
/// Gets or sets the rectangle in pixels to use as the back buffer.
/// Calling Initialize will set this automatically.
/// </summary>
[ShallowCopy]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Rectangle BufferRectangle { get; set; }
/// <summary>
/// Gets or sets the label layer that is associated with this line layer.
/// </summary>
[ShallowCopy]
public new IMapLabelLayer LabelLayer
{
get
{
return base.LabelLayer as IMapLabelLayer;
}
set
{
base.LabelLayer = value;
}
}
/// <summary>
/// Gets an integer number of chunks for this layer.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int NumChunks
{
get
{
if (DrawingFilter == null) return 0;
return DrawingFilter.NumChunks;
}
}
#endregion
#region Methods
/// <summary>
/// Call StartDrawing before using this.
/// </summary>
/// <param name="rectangles">The rectangular region in pixels to clear.</param>
/// <param name= "color">The color to use when clearing. Specifying transparent
/// will replace content with transparent pixels.</param>
public void Clear(List<Rectangle> rectangles, Color color)
{
if (BackBuffer == null) return;
Graphics g = Graphics.FromImage(BackBuffer);
foreach (Rectangle r in rectangles)
{
if (r.IsEmpty == false)
{
g.Clip = new Region(r);
g.Clear(color);
}
}
g.Dispose();
}
/// <summary>
/// This is testing the idea of using an input parameter type that is marked as out
/// instead of a return type.
/// </summary>
/// <param name="result">The result of the creation</param>
/// <returns>Boolean, true if a layer can be created</returns>
public override bool CreateLayerFromSelectedFeatures(out IFeatureLayer result)
{
MapLineLayer temp;
bool resultOk = CreateLayerFromSelectedFeatures(out temp);
result = temp;
return resultOk;
}
/// <summary>
/// This is the strong typed version of the same process that is specific to geo point layers.
/// </summary>
/// <param name="result">The new GeoPointLayer to be created</param>
/// <returns>Boolean, true if there were any values in the selection</returns>
public virtual bool CreateLayerFromSelectedFeatures(out MapLineLayer result)
{
result = null;
if (Selection == null || Selection.Count == 0) return false;
FeatureSet fs = Selection.ToFeatureSet();
result = new MapLineLayer(fs);
return true;
}
/// <summary>
/// If EditMode is true, then this method is used for feature drawing.
/// </summary>
/// <param name="args">The GeoArgs that control how these features should be drawn.</param>
/// <param name="features">The features that should be drawn.</param>
/// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param>
/// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param>
/// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param>
public virtual void DrawFeatures(MapArgs args, List<IFeature> features, List<Rectangle> clipRectangles, bool useChunks, bool selected)
{
if (!useChunks)
{
DrawFeatures(args, features, selected);
return;
}
int count = features.Count;
int numChunks = (int)Math.Ceiling(count / (double)ChunkSize);
for (int chunk = 0; chunk < numChunks; chunk++)
{
int numFeatures = ChunkSize;
if (chunk == numChunks - 1) numFeatures = features.Count - (chunk * ChunkSize);
DrawFeatures(args, features.GetRange(chunk * ChunkSize, numFeatures), selected);
if (numChunks > 0 && chunk < numChunks - 1)
{
OnBufferChanged(clipRectangles);
Application.DoEvents();
}
}
}
/// <summary>
/// If EditMode is false, then this method is used for feature drawing.
/// </summary>
/// <param name="args">The GeoArgs that control how these features should be drawn.</param>
/// <param name="indices">The features that should be drawn.</param>
/// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param>
/// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param>
/// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param>
public virtual void DrawFeatures(MapArgs args, List<int> indices, List<Rectangle> clipRectangles, bool useChunks, bool selected)
{
if (!useChunks)
{
DrawFeatures(args, indices, selected);
return;
}
int count = indices.Count;
int numChunks = (int)Math.Ceiling(count / (double)ChunkSize);
for (int chunk = 0; chunk < numChunks; chunk++)
{
int numFeatures = ChunkSize;
if (chunk == numChunks - 1) numFeatures = indices.Count - (chunk * ChunkSize);
DrawFeatures(args, indices.GetRange(chunk * ChunkSize, numFeatures), selected);
if (numChunks > 0 && chunk < numChunks - 1)
{
OnBufferChanged(clipRectangles);
Application.DoEvents();
}
}
}
/// <summary>
/// This will draw any features that intersect this region. To specify the features
/// directly, use OnDrawFeatures. This will not clear existing buffer content.
/// For that call Initialize instead.
/// </summary>
/// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param>
/// <param name="regions">The geographic regions to draw</param>
/// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param>
public virtual void DrawRegions(MapArgs args, List<Extent> regions, bool selected)
{
// First determine the number of features we are talking about based on region.
List<Rectangle> clipRects = args.ProjToPixel(regions);
if (EditMode)
{
List<IFeature> drawList = new List<IFeature>();
foreach (Extent region in regions)
{
if (region != null)
{
// Use union to prevent duplicates. No sense in drawing more than we have to.
drawList = drawList.Union(DataSet.Select(region)).ToList();
}
}
DrawFeatures(args, drawList, clipRects, true, selected);
}
else
{
List<int> drawList = new List<int>();
List<ShapeRange> shapes = DataSet.ShapeIndices;
for (int shp = 0; shp < shapes.Count; shp++)
{
foreach (Extent region in regions)
{
if (!shapes[shp].Extent.Intersects(region)) continue;
drawList.Add(shp);
break;
}
}
DrawFeatures(args, drawList, clipRects, true, selected);
}
}
/// <summary>
/// Builds a linestring into the graphics path, using minX, maxY, dx and dy for the transformations.
/// </summary>
/// <param name="path">Graphics path to add the line string to.</param>
/// <param name="ls">LineString that gets added.</param>
/// <param name="args">The map arguments.</param>
/// <param name="clipRect">The clip rectangle.</param>
internal static void BuildLineString(GraphicsPath path, ILineString ls, MapArgs args, Rectangle clipRect)
{
double minX = args.MinX;
double maxY = args.MaxY;
double dx = args.Dx;
double dy = args.Dy;
var points = new List<double[]>();
double[] previousPoint = null;
foreach (Coordinate c in ls.Coordinates)
{
var pt = new[] { (c.X - minX) * dx, (maxY - c.Y) * dy};
if (previousPoint == null || previousPoint.Length < 2 || pt[0] != previousPoint[0] || pt[1] != previousPoint[1])
{
points.Add(pt);
}
previousPoint = pt;
}
AddLineStringToPath(path, args, ls.EnvelopeInternal.ToExtent(), points, clipRect);
}
/// <summary>
/// Adds the line string to the path.
/// </summary>
/// <param name="path">Path to add the line string to.</param>
/// <param name="vertices">Vertices of the line string.</param>
/// <param name="shpx">Shape range of the line string.</param>
/// <param name="args">The map arguments.</param>
/// <param name="clipRect">The clip rectangle.</param>
internal static void BuildLineString(GraphicsPath path, double[] vertices, ShapeRange shpx, MapArgs args, Rectangle clipRect)
{
double minX = args.MinX;
double maxY = args.MaxY;
double dx = args.Dx;
double dy = args.Dy;
for (int prt = 0; prt < shpx.Parts.Count; prt++)
{
PartRange prtx = shpx.Parts[prt];
int start = prtx.StartIndex;
int end = prtx.EndIndex;
var points = new List<double[]>(end - start + 1);
for (int i = start; i <= end; i++)
{
var pt = new[] { (vertices[i * 2] - minX) * dx, (maxY - vertices[(i * 2) + 1]) * dy };
points.Add(pt);
}
AddLineStringToPath(path, args, shpx.Extent, points, clipRect);
}
}
/// <summary>
/// Fires the OnBufferChanged event
/// </summary>
/// <param name="clipRectangles">The Rectangle in pixels</param>
protected virtual void OnBufferChanged(List<Rectangle> clipRectangles)
{
if (BufferChanged != null)
{
ClipArgs e = new ClipArgs(clipRectangles);
BufferChanged(this, e);
}
}
/// <summary>
/// A default method to generate a label layer.
/// </summary>
protected override void OnCreateLabels()
{
LabelLayer = new MapLabelLayer(this);
}
/// <summary>
/// Indiciates that whatever drawing is going to occur has finished and the contents
/// are about to be flipped forward to the front buffer.
/// </summary>
protected virtual void OnFinishDrawing()
{
}
/// <summary>
/// Occurs when a new drawing is started, but after the BackBuffer has been established.
/// </summary>
protected virtual void OnStartDrawing()
{
}
/// <summary>
/// Adds the given points to the given path.
/// </summary>
/// <param name="path">Path the points get added to.</param>
/// <param name="args">MapArgs used for clipping.</param>
/// <param name="extent">Extent of the feature used for clipping.</param>
/// <param name="points">Points that get added to the path.</param>
/// <param name="clipRect">The clipping rectangle.</param>
private static void AddLineStringToPath(GraphicsPath path, MapArgs args, Extent extent, List<double[]> points, Rectangle clipRect)
{
List<List<double[]>> multiLinestrings;
if (!DotSpatial.Symbology.Core.Constants.IsPrinting && !extent.Within(args.GeographicExtents))
{
multiLinestrings = CohenSutherland.ClipLinestring(points, clipRect.Left, clipRect.Top, clipRect.Right, clipRect.Bottom);
}
else
{
multiLinestrings = new List<List<double[]>>
{
points
};
}
foreach (List<double[]> linestring in multiLinestrings)
{
var intPoints = DuplicationPreventer.Clean(linestring).ToArray();
if (intPoints.Length < 2)
{
continue;
}
path.StartFigure();
path.AddLines(intPoints);
}
}
private static Rectangle ComputeClippingRectangle(MapArgs args, ILineSymbolizer ls)
{
// Compute a clipping rectangle that accounts for symbology
int maxLineWidth = 2 * (int)Math.Ceiling(ls.GetWidth());
Rectangle clipRect = args.ProjToPixel(args.GeographicExtents); // use GeographicExtent for clipping because ImageRect clips to much
clipRect.Inflate(maxLineWidth, maxLineWidth);
return clipRect;
}
// CGX, n'est plus static
/// <summary>
/// Gets the indices of the features that get drawn.
/// </summary>
/// <param name="indices">Indices of all the features that could be drawn.</param>
/// <param name="states">FastDrawnStates of the features.</param>
/// <param name="category">Category the features must have to get drawn.</param>
/// <param name="selected">Indicates whether only the selected features get drawn.</param>
/// <returns>List of the indices of the features that get drawn.</returns>
private List<int> GetFeatures(IList<int> indices, FastDrawnState[] states, ILineCategory category, bool selected)
{
List<int> drawnFeatures = new List<int>();
foreach (int index in indices)
{
if (index >= states.Length) break;
FastDrawnState state = states[index];
if (selected)
{
if (state.Category == category && state.Visible && state.Selected)
{
// CGX
if (Visibility != null && Visibility.Length > 0 && index < Visibility.Length)
{
bool visi = Visibility[index].Visible;
if (!visi) continue;
} // CGX END
drawnFeatures.Add(index);
}
}
else
{
if (state.Category == category && state.Visible)
{
drawnFeatures.Add(index);
}
}
}
return drawnFeatures;
}
private void Configure()
{
BufferRectangle = new Rectangle(0, 0, 3000, 3000);
ChunkSize = 50000;
}
private void DrawFeatures(MapArgs e, IEnumerable<int> indices, bool selected)
{
if (selected && !DrawnStatesNeeded) return;
Graphics g = e.Device ?? Graphics.FromImage(BackBuffer);
g.SetClip(new Rectangle(0, 0, e.ImageRectangle.Width, e.ImageRectangle.Height));
var indiceList = indices as IList<int> ?? indices.ToList();
Action<GraphicsPath, Rectangle, IEnumerable<int>> drawFeature = (graphPath, clipRect, features) =>
{
foreach (int shp in features)
{
ShapeRange shape = DataSet.ShapeIndices[shp];
BuildLineString(graphPath, DataSet.Vertex, shape, e, clipRect);
}
};
if (DrawnStatesNeeded)
{
FastDrawnState[] states = DrawnStates;
if (indiceList.Max() >= states.Length)
{
AssignFastDrawnStates();
states = DrawnStates;
}
Rectangle rTest = Rectangle.Empty;
DotSpatial.Controls.Core.CGX_Mask cgxMask = DotSpatial.Controls.Core.CGX_Mask_List.GetMasks(this.Name);
if (cgxMask != null)
{
foreach (DotSpatial.Controls.Core.CGX_MaskBounds mask in cgxMask.Masks)
{
RectangleF rectBounds = mask.Bounds;
if (rectBounds.IsEmpty)
{
if (mask.Center != null)
{
Point pTest1 = e.ProjToPixel(mask.Center);
pTest1.X -= (int)(mask.Width / 2);
pTest1.Y -= (int)(mask.Height / 2);
rectBounds = new RectangleF(pTest1, new SizeF((float)mask.Width, (float)mask.Height));
}
}
if (!rectBounds.IsEmpty)
{
float cx = rectBounds.X + (int)(mask.Width / 2);
float cy = rectBounds.Y + +(int)(mask.Height / 2);
System.Drawing.Drawing2D.Matrix oldTrans = g.Transform.Clone();
g.ResetTransform();
g.TranslateTransform(-cx, -cy, MatrixOrder.Append);
g.RotateTransform((float)mask.Rotation, MatrixOrder.Append);
g.TranslateTransform(cx, cy, MatrixOrder.Append);
RectangleF rectWithMargin = new RectangleF(
(float)((rectBounds.Location.X - cgxMask.OffsetLeft + 1)),
(float)((rectBounds.Location.Y - cgxMask.OffsetTop + 1)),
(float)((rectBounds.Width + cgxMask.OffsetLeft + cgxMask.OffsetRight)),
(float)((rectBounds.Height + cgxMask.OffsetTop + cgxMask.OffsetBottom)));
g.ExcludeClip(Rectangle.Round(rectWithMargin));
g.Transform = oldTrans;
}
}
cgxMask.ResetBounds();
}
if (selected && !states.Any(_ => _.Selected)) return;
foreach (ILineCategory category in Symbology.Categories)
{
// Define the symbology based on the category and selection state
ILineSymbolizer ls = selected ? category.SelectionSymbolizer : category.Symbolizer;
var features = GetFeatures(indiceList, states, category, selected);
DrawPath(g, ls, e, drawFeature, features);
}
g.ResetClip();
}
else
{
// Selection state is disabled and there is only one category
ILineSymbolizer ls = Symbology.Categories[0].Symbolizer;
DrawPath(g, ls, e, drawFeature, indiceList);
}
if (e.Device == null) g.Dispose();
}
/// <summary>
/// Draws the path that results from the given indices.
/// </summary>
/// <typeparam name="T">Type of the elements in the list.</typeparam>
/// <param name="g">Graphics object used for drawing.</param>
/// <param name="ls">LineSymbolizer used for drawing.</param>
/// <param name="e">MapArgs needed for computation.</param>
/// <param name="action">Action that is used to add the elements to the graphics path that gets drawn.</param>
/// <param name="list">List that contains the elements that get drawn.</param>
private void DrawPath<T>(Graphics g, ILineSymbolizer ls, MapArgs e, Action<GraphicsPath, Rectangle, IEnumerable<T>> action, IEnumerable<T> list)
{
g.SmoothingMode = ls.GetSmoothingMode();
Rectangle clipRect = ComputeClippingRectangle(e, ls);
// Determine the subset of the specified features that are visible and match the category
using (GraphicsPath graphPath = new GraphicsPath())
{
action(graphPath, clipRect, list);
double scale = ls.GetScale(e);
// CGX
if (MapFrame != null && (MapFrame as IMapFrame).ReferenceScale > 1.0 && (MapFrame as IMapFrame).CurrentScale > 0.0)
{
double dReferenceScale = (MapFrame as IMapFrame).ReferenceScale;
double dCurrentScale = (MapFrame as IMapFrame).CurrentScale;
scale = dReferenceScale / dCurrentScale;
} // Fin CGX
foreach (IStroke stroke in ls.Strokes)
{
stroke.DrawPath(g, graphPath, scale);
}
}
}
// This draws the individual line features
private void DrawFeatures(MapArgs e, IEnumerable<IFeature> features, bool selected)
{
if (selected && !DrawingFilter.DrawnStates.Any(_ => _.Value.IsSelected)) return;
Graphics g = e.Device ?? Graphics.FromImage(BackBuffer);
var featureList = features as IList<IFeature> ?? features.ToList();
Action<GraphicsPath, Rectangle, IEnumerable<IFeature>> drawFeature = (graphPath, clipRect, featList) =>
{
foreach (IFeature f in featList)
{
BuildLineString(graphPath, f.Geometry as ILineString, e, clipRect);
}
};
foreach (ILineCategory category in Symbology.Categories)
{
// Define the symbology based on the category and selection state
ILineSymbolizer ls = selected ? category.SelectionSymbolizer : category.Symbolizer;
// Determine the subset of the specified features that are visible and match the category
ILineCategory lineCategory = category;
Func<IDrawnState, bool> isMember;
if (selected)
{
// get only selected features
isMember = state => state.SchemeCategory == lineCategory && state.IsVisible && state.IsSelected;
}
else
{
// get all features
isMember = state => state.SchemeCategory == lineCategory && state.IsVisible;
}
var drawnFeatures = from feature in featureList where isMember(DrawingFilter[feature]) select feature;
DrawPath(g, ls, e, drawFeature, drawnFeatures);
}
if (e.Device == null) g.Dispose();
}
#endregion
#region CGX
/// <summary>
/// Constructor
/// </summary>
/// <param name="inFeatureSet"></param>
public MapLineLayer(IFeatureSet inFeatureSet, FastDrawnState[] inVisibility)
: base(inFeatureSet)
{
Configure();
OnFinishedLoading();
Visibility = inVisibility;
}
FastDrawnState[] _Visibility = null;
[Serialize("FastDrawnState", ConstructorArgumentIndex = 1)]
public FastDrawnState[] Visibility
{
get
{
return _Visibility;
}
set
{
_Visibility = value;
}
}
public void StoreVisibility()
{
Visibility = DrawnStates;
}
public void SetVisibility()
{
DrawnStatesNeeded = true;
if (_Visibility != null && DrawnStates != null
&& _Visibility.Length == DrawnStates.Length)
{
for (int i = 0; i < _Visibility.Length; i++)
{
DrawnStates[i].Visible = _Visibility[i].Visible;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using FacetedWorlds.Reversi.Client.NavigationModels;
using FacetedWorlds.Reversi.GameLogic;
using FacetedWorlds.Reversi.Model;
using FacetedWorlds.Reversi.NavigationModels;
using UpdateControls.XAML;
using UpdateControls;
namespace FacetedWorlds.Reversi.ViewModels
{
public abstract class PlayerGameViewModel : IGameViewModel
{
private MainNavigationModel _mainNavigation;
private RemoteGameState _gameState;
private Dependent _depGameState;
protected PlayerGameViewModel(MainNavigationModel mainNavigation)
{
_mainNavigation = mainNavigation;
_depGameState = new Dependent(() =>
{
_gameState = Player == null
? null
: new RemoteGameState(Player, _mainNavigation);
});
}
protected abstract Player Player { get; }
protected MainNavigationModel MainNavigation
{
get { return _mainNavigation; }
}
private RemoteGameState GameState
{
get
{
_depGameState.OnGet();
return _gameState;
}
}
public string Name
{
get
{
return
MyColor == PieceColor.Empty
? "Waiting for opponent" :
MyColor == PieceColor.Black
? string.Format("you vs. {0}", OtherPlayerName)
: String.Format("{0} vs. you", OtherPlayerName);
}
}
public bool HasNewMessages
{
get
{
return GetOtherPlayer() == null ? false : GetOtherPlayer().NewMessages.Any();
}
}
public bool CanChat
{
get { return Player != null; }
}
public bool CanResign
{
get { return Player != null && Player.Game.Outcome == null; }
}
public ICommand Resign
{
get
{
return MakeCommand
.When(() => Player != null)
.Do(() => Player.Game.DeclareWinner(GetOtherPlayer(), true));
}
}
public PieceColor MyColor
{
get { return GameState == null ? PieceColor.Empty : GameState.MyColor; }
}
public PieceColor OpponentColor
{
get { return GameState == null ? PieceColor.Empty : GameState.MyColor.Opposite(); }
}
public bool MyTurn
{
get { return GameState != null && GameState.MyTurn && !GameState.IsMovePending; }
}
public string Outcome
{
get
{
return
GameState == null ? "Waiting for opponent..." :
GameState.IWon ? "You Won" :
GameState.ILost ? "You Lost" :
GameState.IDrew ? "You Drew" :
GameState.IResigned ? "You Resigned" :
GameState.HeResigned ? "Opponent Resigned" :
string.Empty;
}
}
public bool ILost
{
get { return GameState != null && GameState.ILost; }
}
public bool IDrew
{
get { return GameState != null && GameState.IDrew; }
}
public IEnumerable<IRowViewModel> Rows
{
get
{
return GetRows();
}
}
private IEnumerable<IRowViewModel> GetRows()
{
if (GameState != null)
for (int row = 0; row < Square.NumberOfRows; row++)
yield return new RemoteRowViewModel(GameState, row);
}
public bool IsMovePending
{
get { return GameState != null && GameState.IsMovePending; }
}
public bool PreviewMove(int row, int column)
{
return GameState != null && GameState.SetPreviewMove(Square.FromCoordinates(row, column));
}
public void ClearPreviewMove()
{
if (GameState != null)
GameState.SetPreviewMove(null);
}
public void MakeMove(int row, int column)
{
if (GameState != null)
GameState.MakeMove(Square.FromCoordinates(row, column));
}
public void CommitMove()
{
if (GameState != null)
GameState.CommitMove();
}
public void CancelMove()
{
if (GameState != null)
GameState.CancelMove();
}
private string OtherPlayerName
{
get
{
return GetOtherPlayer() == null ? "nobody" : GetOtherPlayer().User.UserName;
}
}
private Player GetOtherPlayer()
{
if (Player == null)
return null;
List<Player> players = Player.Game.Players.ToList();
return players.FirstOrDefault(p => p != Player);
}
public abstract void ClearSelectedPlayer();
public abstract bool IsWaiting { get; }
public void AcknowledgeOutcome()
{
if (Player != null)
{
IEnumerable<Outcome> outcomes = Player.Game.Outcomes;
foreach (Outcome outcome in outcomes)
{
Player.Acknowledge(outcome);
}
}
}
public bool IsChatEnabled
{
get { return Player != null && Player.User.IsChatEnabled.Any(); }
}
public void EnableChat()
{
if (Player != null)
Player.User.EnableChat();
}
public int BlackCount
{
get { return GameState == null ? 0 : GameState.BlackCount; }
}
public int WhiteCount
{
get { return GameState == null ? 0 : GameState.WhiteCount; }
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: money/rpc/card_processing_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.Money.RPC {
public static partial class CardProcessingSvc
{
static readonly string __ServiceName = "holms.types.money.rpc.CardProcessingSvc";
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest> __Marshaller_CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse> __Marshaller_CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.CardMerchantIndicator> __Marshaller_CardMerchantIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.CardMerchantIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse> __Marshaller_GetOpenBatchStateResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchHistoricalBatchesRequest> __Marshaller_CardProcessingSvcSearchHistoricalBatchesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchHistoricalBatchesRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.MerchantBatchEnumResponse> __Marshaller_MerchantBatchEnumResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.MerchantBatchEnumResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.Transactions.ClosedMerchantBatch> __Marshaller_ClosedMerchantBatch = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.Transactions.ClosedMerchantBatch.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator> __Marshaller_PaymentCardSaleIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse> __Marshaller_CardProcessingSvcVoidTransactionResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator> __Marshaller_PaymentCardRefundIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchOpenClosedBatchesRequest> __Marshaller_CardProcessingSvcSearchOpenClosedBatchesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchOpenClosedBatchesRequest.Parser.ParseFrom);
static readonly grpc::Method<global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest, global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse> __Method_VerifyAndTokenizeNotPresentCard = new grpc::Method<global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest, global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse>(
grpc::MethodType.Unary,
__ServiceName,
"VerifyAndTokenizeNotPresentCard",
__Marshaller_CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest,
__Marshaller_CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse);
static readonly grpc::Method<global::HOLMS.Types.Money.Cards.CardMerchantIndicator, global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse> __Method_GetCurrentBatchState = new grpc::Method<global::HOLMS.Types.Money.Cards.CardMerchantIndicator, global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetCurrentBatchState",
__Marshaller_CardMerchantIndicator,
__Marshaller_GetOpenBatchStateResponse);
static readonly grpc::Method<global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchHistoricalBatchesRequest, global::HOLMS.Types.Money.RPC.MerchantBatchEnumResponse> __Method_SearchHistoricalBatches = new grpc::Method<global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchHistoricalBatchesRequest, global::HOLMS.Types.Money.RPC.MerchantBatchEnumResponse>(
grpc::MethodType.Unary,
__ServiceName,
"SearchHistoricalBatches",
__Marshaller_CardProcessingSvcSearchHistoricalBatchesRequest,
__Marshaller_MerchantBatchEnumResponse);
static readonly grpc::Method<global::HOLMS.Types.Money.Cards.CardMerchantIndicator, global::HOLMS.Types.Money.Cards.Transactions.ClosedMerchantBatch> __Method_CloseProcessorBatch = new grpc::Method<global::HOLMS.Types.Money.Cards.CardMerchantIndicator, global::HOLMS.Types.Money.Cards.Transactions.ClosedMerchantBatch>(
grpc::MethodType.Unary,
__ServiceName,
"CloseProcessorBatch",
__Marshaller_CardMerchantIndicator,
__Marshaller_ClosedMerchantBatch);
static readonly grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator, global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse> __Method_VoidSale = new grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator, global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse>(
grpc::MethodType.Unary,
__ServiceName,
"VoidSale",
__Marshaller_PaymentCardSaleIndicator,
__Marshaller_CardProcessingSvcVoidTransactionResponse);
static readonly grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator, global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse> __Method_VoidRefund = new grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator, global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse>(
grpc::MethodType.Unary,
__ServiceName,
"VoidRefund",
__Marshaller_PaymentCardRefundIndicator,
__Marshaller_CardProcessingSvcVoidTransactionResponse);
static readonly grpc::Method<global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchOpenClosedBatchesRequest, global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse> __Method_GetOpenClosedBatchState = new grpc::Method<global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchOpenClosedBatchesRequest, global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetOpenClosedBatchState",
__Marshaller_CardProcessingSvcSearchOpenClosedBatchesRequest,
__Marshaller_GetOpenBatchStateResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.Money.RPC.CardProcessingSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of CardProcessingSvc</summary>
public abstract partial class CardProcessingSvcBase
{
/// <summary>
/// Tokenize a new card
/// TODO (DRA): Move this onto the reservation folio svc endpoint
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse> VerifyAndTokenizeNotPresentCard(global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Batches
/// Get info about batches
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse> GetCurrentBatchState(global::HOLMS.Types.Money.Cards.CardMerchantIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.RPC.MerchantBatchEnumResponse> SearchHistoricalBatches(global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchHistoricalBatchesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Request batch closure
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.Cards.Transactions.ClosedMerchantBatch> CloseProcessorBatch(global::HOLMS.Types.Money.Cards.CardMerchantIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Post-creation card transaction management
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse> VoidSale(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse> VoidRefund(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse> GetOpenClosedBatchState(global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchOpenClosedBatchesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for CardProcessingSvc</summary>
public partial class CardProcessingSvcClient : grpc::ClientBase<CardProcessingSvcClient>
{
/// <summary>Creates a new client for CardProcessingSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public CardProcessingSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for CardProcessingSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public CardProcessingSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected CardProcessingSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected CardProcessingSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Tokenize a new card
/// TODO (DRA): Move this onto the reservation folio svc endpoint
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse VerifyAndTokenizeNotPresentCard(global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return VerifyAndTokenizeNotPresentCard(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Tokenize a new card
/// TODO (DRA): Move this onto the reservation folio svc endpoint
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse VerifyAndTokenizeNotPresentCard(global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_VerifyAndTokenizeNotPresentCard, null, options, request);
}
/// <summary>
/// Tokenize a new card
/// TODO (DRA): Move this onto the reservation folio svc endpoint
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse> VerifyAndTokenizeNotPresentCardAsync(global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return VerifyAndTokenizeNotPresentCardAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Tokenize a new card
/// TODO (DRA): Move this onto the reservation folio svc endpoint
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardResponse> VerifyAndTokenizeNotPresentCardAsync(global::HOLMS.Types.Money.RPC.CardProcessingSvcVerifyAndTokenizeNotPresentCardRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_VerifyAndTokenizeNotPresentCard, null, options, request);
}
/// <summary>
/// Batches
/// Get info about batches
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse GetCurrentBatchState(global::HOLMS.Types.Money.Cards.CardMerchantIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetCurrentBatchState(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Batches
/// Get info about batches
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse GetCurrentBatchState(global::HOLMS.Types.Money.Cards.CardMerchantIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetCurrentBatchState, null, options, request);
}
/// <summary>
/// Batches
/// Get info about batches
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse> GetCurrentBatchStateAsync(global::HOLMS.Types.Money.Cards.CardMerchantIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetCurrentBatchStateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Batches
/// Get info about batches
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse> GetCurrentBatchStateAsync(global::HOLMS.Types.Money.Cards.CardMerchantIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetCurrentBatchState, null, options, request);
}
public virtual global::HOLMS.Types.Money.RPC.MerchantBatchEnumResponse SearchHistoricalBatches(global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchHistoricalBatchesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SearchHistoricalBatches(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.RPC.MerchantBatchEnumResponse SearchHistoricalBatches(global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchHistoricalBatchesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SearchHistoricalBatches, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.MerchantBatchEnumResponse> SearchHistoricalBatchesAsync(global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchHistoricalBatchesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SearchHistoricalBatchesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.MerchantBatchEnumResponse> SearchHistoricalBatchesAsync(global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchHistoricalBatchesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SearchHistoricalBatches, null, options, request);
}
/// <summary>
/// Request batch closure
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Money.Cards.Transactions.ClosedMerchantBatch CloseProcessorBatch(global::HOLMS.Types.Money.Cards.CardMerchantIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CloseProcessorBatch(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Request batch closure
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Money.Cards.Transactions.ClosedMerchantBatch CloseProcessorBatch(global::HOLMS.Types.Money.Cards.CardMerchantIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CloseProcessorBatch, null, options, request);
}
/// <summary>
/// Request batch closure
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.ClosedMerchantBatch> CloseProcessorBatchAsync(global::HOLMS.Types.Money.Cards.CardMerchantIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CloseProcessorBatchAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Request batch closure
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.ClosedMerchantBatch> CloseProcessorBatchAsync(global::HOLMS.Types.Money.Cards.CardMerchantIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CloseProcessorBatch, null, options, request);
}
/// <summary>
/// Post-creation card transaction management
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse VoidSale(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return VoidSale(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Post-creation card transaction management
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse VoidSale(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_VoidSale, null, options, request);
}
/// <summary>
/// Post-creation card transaction management
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse> VoidSaleAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return VoidSaleAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Post-creation card transaction management
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse> VoidSaleAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_VoidSale, null, options, request);
}
public virtual global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse VoidRefund(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return VoidRefund(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse VoidRefund(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_VoidRefund, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse> VoidRefundAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return VoidRefundAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.CardProcessingSvcVoidTransactionResponse> VoidRefundAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_VoidRefund, null, options, request);
}
public virtual global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse GetOpenClosedBatchState(global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchOpenClosedBatchesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetOpenClosedBatchState(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse GetOpenClosedBatchState(global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchOpenClosedBatchesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetOpenClosedBatchState, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse> GetOpenClosedBatchStateAsync(global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchOpenClosedBatchesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetOpenClosedBatchStateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse> GetOpenClosedBatchStateAsync(global::HOLMS.Types.Money.RPC.CardProcessingSvcSearchOpenClosedBatchesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetOpenClosedBatchState, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override CardProcessingSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new CardProcessingSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(CardProcessingSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_VerifyAndTokenizeNotPresentCard, serviceImpl.VerifyAndTokenizeNotPresentCard)
.AddMethod(__Method_GetCurrentBatchState, serviceImpl.GetCurrentBatchState)
.AddMethod(__Method_SearchHistoricalBatches, serviceImpl.SearchHistoricalBatches)
.AddMethod(__Method_CloseProcessorBatch, serviceImpl.CloseProcessorBatch)
.AddMethod(__Method_VoidSale, serviceImpl.VoidSale)
.AddMethod(__Method_VoidRefund, serviceImpl.VoidRefund)
.AddMethod(__Method_GetOpenClosedBatchState, serviceImpl.GetOpenClosedBatchState).Build();
}
}
}
#endregion
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Dns
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// RecordSetsOperations operations.
/// </summary>
public partial interface IRecordSetsOperations
{
/// <summary>
/// Updates a RecordSet within a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA',
/// 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<RecordSet>> UpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or Updates a RecordSet within a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA',
/// 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Recordset.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<RecordSet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes a RecordSet from a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA',
/// 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='ifMatch'>
/// Defines the If-Match condition. The delete operation will be
/// performed only if the ETag of the zone on the server matches this
/// value.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. The delete operation will be
/// performed only if the ETag of the zone on the server does not
/// match this value.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a RecordSet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA',
/// 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<RecordSet>> GetWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// The name of the zone from which to enumerate RecordsSets.
/// </param>
/// <param name='recordType'>
/// The type of record sets to enumerate. Possible values include:
/// 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of
/// zones.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<RecordSet>>> ListByTypeWithHttpMessagesAsync(string resourceGroupName, string zoneName, RecordType recordType, string top = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// The name of the zone from which to enumerate RecordSets.
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of
/// zones.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<RecordSet>>> ListAllInResourceGroupWithHttpMessagesAsync(string resourceGroupName, string zoneName, string top = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<RecordSet>>> ListByTypeNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<RecordSet>>> ListAllInResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// IFDTag.cs: Basic Tag-class to handle an IFD (Image File Directory) with
// its image-tags.
//
// Author:
// Ruben Vermeersch (ruben@savanne.be)
// Mike Gemuende (mike@gemuende.de)
// Paul Lange (palango@gmx.de)
//
// Copyright (C) 2009 Ruben Vermeersch
// Copyright (C) 2009 Mike Gemuende
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// 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
//
using System;
using System.Collections.Generic;
using System.IO;
using TagLib.Image;
using TagLib.IFD.Entries;
using TagLib.IFD.Tags;
namespace TagLib.IFD
{
/// <summary>
/// Contains the metadata for one IFD (Image File Directory).
/// </summary>
public class IFDTag : ImageTag
{
#region Private Fields
/// <summary>
/// A reference to the Exif IFD (which can be found by following the
/// pointer in IFD0, ExifIFD tag). This variable should not be used
/// directly, use the <see cref="ExifIFD"/> property instead.
/// </summary>
private IFDStructure exif_ifd = null;
/// <summary>
/// A reference to the GPS IFD (which can be found by following the
/// pointer in IFD0, GPSIFD tag). This variable should not be used
/// directly, use the <see cref="GPSIFD"/> property instead.
/// </summary>
private IFDStructure gps_ifd = null;
#endregion
#region Public Properties
/// <value>
/// The IFD structure referenced by the current instance
/// </value>
public IFDStructure Structure { get; private set; }
/// <summary>
/// The Exif IFD. Will create one if the file doesn't alread have it.
/// </summary>
/// <remarks>
/// <para>Note how this also creates an empty IFD for exif, even if
/// you don't set a value. That's okay, empty nested IFDs get ignored
/// when rendering.</para>
/// </remarks>
public IFDStructure ExifIFD {
get {
if (exif_ifd == null) {
var entry = Structure.GetEntry (0, IFDEntryTag.ExifIFD) as SubIFDEntry;
if (entry == null) {
exif_ifd = new IFDStructure ();
entry = new SubIFDEntry ((ushort) IFDEntryTag.ExifIFD, (ushort) IFDEntryType.Long, 1, exif_ifd);
Structure.SetEntry (0, entry);
}
exif_ifd = entry.Structure;
}
return exif_ifd;
}
}
/// <summary>
/// The GPS IFD. Will create one if the file doesn't alread have it.
/// </summary>
/// <remarks>
/// <para>Note how this also creates an empty IFD for GPS, even if
/// you don't set a value. That's okay, empty nested IFDs get ignored
/// when rendering.</para>
/// </remarks>
public IFDStructure GPSIFD {
get {
if (gps_ifd == null) {
var entry = Structure.GetEntry (0, IFDEntryTag.GPSIFD) as SubIFDEntry;
if (entry == null) {
gps_ifd = new IFDStructure ();
entry = new SubIFDEntry ((ushort) IFDEntryTag.GPSIFD, (ushort) IFDEntryType.Long, 1, gps_ifd);
Structure.SetEntry (0, entry);
}
gps_ifd = entry.Structure;
}
return gps_ifd;
}
}
/// <summary>
/// Gets the tag types contained in the current instance.
/// </summary>
/// <value>
/// Always <see cref="TagTypes.TiffIFD" />.
/// </value>
public override TagTypes TagTypes {
get { return TagTypes.TiffIFD; }
}
#endregion
#region Constructors
/// <summary>
/// Constructor. Creates an empty IFD tag. Can be populated manually, or via
/// <see cref="IFDReader"/>.
/// </summary>
public IFDTag ()
{
Structure = new IFDStructure ();
}
#endregion
#region Public Methods
/// <summary>
/// Clears the values stored in the current instance.
/// </summary>
public override void Clear ()
{
throw new NotImplementedException ();
}
#endregion
#region Metadata fields
/// <summary>
/// Gets or sets the comment for the image described
/// by the current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the comment of the
/// current instace.
/// </value>
public override string Comment {
get {
var comment_entry = ExifIFD.GetEntry (0, (ushort) ExifEntryTag.UserComment) as UserCommentIFDEntry;
if (comment_entry == null) {
var description = Structure.GetEntry (0, IFDEntryTag.ImageDescription) as StringIFDEntry;
return description == null ? null : description.Value;
}
return comment_entry.Value;
}
set {
if (value == null) {
ExifIFD.RemoveTag (0, (ushort) ExifEntryTag.UserComment);
Structure.RemoveTag (0, (ushort) IFDEntryTag.ImageDescription);
return;
}
ExifIFD.SetEntry (0, new UserCommentIFDEntry ((ushort) ExifEntryTag.UserComment, value));
Structure.SetEntry (0, new StringIFDEntry ((ushort) IFDEntryTag.ImageDescription, value));
}
}
/// <summary>
/// Gets and sets the copyright information for the media
/// represented by the current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> object containing the copyright
/// information for the media represented by the current
/// instance or <see langword="null" /> if no value present.
/// </value>
public override string Copyright {
get {
return Structure.GetStringValue (0, (ushort) IFDEntryTag.Copyright);
}
set {
if (value == null) {
Structure.RemoveTag (0, (ushort) IFDEntryTag.Copyright);
return;
}
Structure.SetEntry (0, new StringIFDEntry ((ushort) IFDEntryTag.Copyright, value));
}
}
/// <summary>
/// Gets or sets the creator of the image.
/// </summary>
/// <value>
/// A <see cref="string" /> with the name of the creator.
/// </value>
public override string Creator {
get {
return Structure.GetStringValue (0, (ushort) IFDEntryTag.Artist);
}
set {
Structure.SetStringValue (0, (ushort) IFDEntryTag.Artist, value);
}
}
/// <summary>
/// Gets or sets the software the image, the current instance
/// belongs to, was created with.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the name of the
/// software the current instace was created with.
/// </value>
public override string Software {
get {
return Structure.GetStringValue (0, (ushort) IFDEntryTag.Software);
}
set {
Structure.SetStringValue (0, (ushort) IFDEntryTag.Software, value);
}
}
/// <summary>
/// Gets or sets the time when the image, the current instance
/// belongs to, was taken.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the time the image was taken.
/// </value>
public override DateTime? DateTime {
get { return DateTimeOriginal; }
set { DateTimeOriginal = value; }
}
/// <summary>
/// The time of capturing.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the time of capturing.
/// </value>
public DateTime? DateTimeOriginal {
get {
return ExifIFD.GetDateTimeValue (0, (ushort) ExifEntryTag.DateTimeOriginal);
}
set {
if (value == null) {
ExifIFD.RemoveTag (0, (ushort) ExifEntryTag.DateTimeOriginal);
return;
}
ExifIFD.SetDateTimeValue (0, (ushort) ExifEntryTag.DateTimeOriginal, value.Value);
}
}
/// <summary>
/// The time of digitization.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the time of digitization.
/// </value>
public DateTime? DateTimeDigitized {
get {
return ExifIFD.GetDateTimeValue (0, (ushort) ExifEntryTag.DateTimeDigitized);
}
set {
if (value == null) {
ExifIFD.RemoveTag (0, (ushort) ExifEntryTag.DateTimeDigitized);
return;
}
ExifIFD.SetDateTimeValue (0, (ushort) ExifEntryTag.DateTimeDigitized, value.Value);
}
}
/// <summary>
/// Gets or sets the latitude of the GPS coordinate the current
/// image was taken.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the latitude ranging from -90.0
/// to +90.0 degrees.
/// </value>
public override double? Latitude {
get {
var gps_ifd = GPSIFD;
var degree_entry = gps_ifd.GetEntry (0, (ushort) GPSEntryTag.GPSLatitude) as RationalArrayIFDEntry;
var degree_ref = gps_ifd.GetStringValue (0, (ushort) GPSEntryTag.GPSLatitudeRef);
if (degree_entry == null || degree_ref == null)
return null;
Rational [] values = degree_entry.Values;
if (values.Length != 3)
return null;
double deg = values[0] + values[1] / 60.0d + values[2] / 3600.0d;
if (degree_ref == "S")
deg *= -1.0d;
return Math.Max (Math.Min (deg, 90.0d), -90.0d);
}
set {
var gps_ifd = GPSIFD;
if (value == null) {
gps_ifd.RemoveTag (0, (ushort) GPSEntryTag.GPSLatitudeRef);
gps_ifd.RemoveTag (0, (ushort) GPSEntryTag.GPSLatitude);
return;
}
double angle = value.Value;
if (angle < -90.0d || angle > 90.0d)
throw new ArgumentException ("value");
InitGpsDirectory ();
gps_ifd.SetStringValue (0, (ushort) GPSEntryTag.GPSLatitudeRef, angle < 0 ? "S" : "N");
var entry =
new RationalArrayIFDEntry ((ushort) GPSEntryTag.GPSLatitude,
DegreeToRationals (Math.Abs (angle)));
gps_ifd.SetEntry (0, entry);
}
}
/// <summary>
/// Gets or sets the longitude of the GPS coordinate the current
/// image was taken.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the longitude ranging from -180.0
/// to +180.0 degrees.
/// </value>
public override double? Longitude {
get {
var gps_ifd = GPSIFD;
var degree_entry = gps_ifd.GetEntry (0, (ushort) GPSEntryTag.GPSLongitude) as RationalArrayIFDEntry;
var degree_ref = gps_ifd.GetStringValue (0, (ushort) GPSEntryTag.GPSLongitudeRef);
if (degree_entry == null || degree_ref == null)
return null;
Rational [] values = degree_entry.Values;
if (values.Length != 3)
return null;
double deg = values[0] + values[1] / 60.0d + values[2] / 3600.0d;
if (degree_ref == "W")
deg *= -1.0d;
return Math.Max (Math.Min (deg, 180.0d), -180.0d);
}
set {
var gps_ifd = GPSIFD;
if (value == null) {
gps_ifd.RemoveTag (0, (ushort) GPSEntryTag.GPSLongitudeRef);
gps_ifd.RemoveTag (0, (ushort) GPSEntryTag.GPSLongitude);
return;
}
double angle = value.Value;
if (angle < -180.0d || angle > 180.0d)
throw new ArgumentException ("value");
InitGpsDirectory ();
gps_ifd.SetStringValue (0, (ushort) GPSEntryTag.GPSLongitudeRef, angle < 0 ? "W" : "E");
var entry =
new RationalArrayIFDEntry ((ushort) GPSEntryTag.GPSLongitude,
DegreeToRationals (Math.Abs (angle)));
gps_ifd.SetEntry (0, entry);
}
}
/// <summary>
/// Gets or sets the altitude of the GPS coordinate the current
/// image was taken. The unit is meter.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the altitude. A positive value
/// is above sea level, a negative one below sea level. The unit is meter.
/// </value>
public override double? Altitude {
get {
var gps_ifd = GPSIFD;
var altitude = gps_ifd.GetRationalValue (0, (ushort) GPSEntryTag.GPSAltitude);
var ref_entry = gps_ifd.GetByteValue (0, (ushort) GPSEntryTag.GPSAltitudeRef);
if (altitude == null || ref_entry == null)
return null;
if (ref_entry.Value == 1)
altitude *= -1.0d;
return altitude;
}
set {
var gps_ifd = GPSIFD;
if (value == null) {
gps_ifd.RemoveTag (0, (ushort) GPSEntryTag.GPSAltitudeRef);
gps_ifd.RemoveTag (0, (ushort) GPSEntryTag.GPSAltitude);
return;
}
double altitude = value.Value;
InitGpsDirectory ();
gps_ifd.SetByteValue (0, (ushort) GPSEntryTag.GPSAltitudeRef, (byte)(altitude < 0 ? 1 : 0));
gps_ifd.SetRationalValue (0, (ushort) GPSEntryTag.GPSAltitude, Math.Abs (altitude));
}
}
/// <summary>
/// Gets the exposure time the image, the current instance belongs
/// to, was taken with.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the exposure time in seconds.
/// </value>
public override double? ExposureTime {
get {
return ExifIFD.GetRationalValue (0, (ushort) ExifEntryTag.ExposureTime);
}
set {
ExifIFD.SetRationalValue (0, (ushort) ExifEntryTag.ExposureTime, value.HasValue ? (double) value : 0);
}
}
/// <summary>
/// Gets the FNumber the image, the current instance belongs
/// to, was taken with.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the FNumber.
/// </value>
public override double? FNumber {
get {
return ExifIFD.GetRationalValue (0, (ushort) ExifEntryTag.FNumber);
}
set {
ExifIFD.SetRationalValue (0, (ushort) ExifEntryTag.FNumber, value.HasValue ? (double) value : 0);
}
}
/// <summary>
/// Gets the ISO speed the image, the current instance belongs
/// to, was taken with.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the ISO speed as defined in ISO 12232.
/// </value>
public override uint? ISOSpeedRatings {
get {
return ExifIFD.GetLongValue (0, (ushort) ExifEntryTag.ISOSpeedRatings);
}
set {
ExifIFD.SetLongValue (0, (ushort) ExifEntryTag.ISOSpeedRatings, value.HasValue ? (uint) value : 0);
}
}
/// <summary>
/// Gets the focal length the image, the current instance belongs
/// to, was taken with.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the focal length in millimeters.
/// </value>
public override double? FocalLength {
get {
return ExifIFD.GetRationalValue (0, (ushort) ExifEntryTag.FocalLength);
}
set {
ExifIFD.SetRationalValue (0, (ushort) ExifEntryTag.FocalLength, value.HasValue ? (double) value : 0);
}
}
/// <summary>
/// Gets the focal length the image, the current instance belongs
/// to, was taken with, assuming a 35mm film camera.
/// </summary>
/// <value>
/// A <see cref="System.Nullable"/> with the focal length in 35mm equivalent in millimeters.
/// </value>
public override uint? FocalLengthIn35mmFilm {
get {
return ExifIFD.GetLongValue (0, (ushort) ExifEntryTag.FocalLengthIn35mmFilm);
}
set {
if (value.HasValue) {
ExifIFD.SetLongValue (0, (ushort) ExifEntryTag.FocalLengthIn35mmFilm, (uint) value);
} else {
ExifIFD.RemoveTag (0, (ushort) ExifEntryTag.FocalLengthIn35mmFilm);
}
}
}
/// <summary>
/// Gets or sets the orientation of the image described
/// by the current instance.
/// </summary>
/// <value>
/// A <see cref="TagLib.Image.ImageOrientation" /> containing the orientation of the
/// image
/// </value>
public override ImageOrientation Orientation {
get {
var orientation = Structure.GetLongValue (0, (ushort) IFDEntryTag.Orientation);
if (orientation.HasValue)
return (ImageOrientation) orientation;
return ImageOrientation.None;
}
set {
if ((uint) value < 1U || (uint) value > 8U) {
Structure.RemoveTag (0, (ushort) IFDEntryTag.Orientation);
return;
}
Structure.SetLongValue (0, (ushort) IFDEntryTag.Orientation, (uint) value);
}
}
/// <summary>
/// Gets the manufacture of the recording equipment the image, the
/// current instance belongs to, was taken with.
/// </summary>
/// <value>
/// A <see cref="string" /> with the manufacture name.
/// </value>
public override string Make {
get {
return Structure.GetStringValue (0, (ushort) IFDEntryTag.Make);
}
set {
Structure.SetStringValue (0, (ushort) IFDEntryTag.Make, value);
}
}
/// <summary>
/// Gets the model name of the recording equipment the image, the
/// current instance belongs to, was taken with.
/// </summary>
/// <value>
/// A <see cref="string" /> with the model name.
/// </value>
public override string Model {
get {
return Structure.GetStringValue (0, (ushort) IFDEntryTag.Model);
}
set {
Structure.SetStringValue (0, (ushort) IFDEntryTag.Model, value);
}
}
#endregion
#region Private Methods
/// <summary>
/// Initilazies the GPS IFD with some basic entries.
/// </summary>
private void InitGpsDirectory ()
{
GPSIFD.SetStringValue (0, (ushort) GPSEntryTag.GPSVersionID, "2 0 0 0");
GPSIFD.SetStringValue (0, (ushort) GPSEntryTag.GPSMapDatum, "WGS-84");
}
/// <summary>
/// Converts a given (positive) angle value to three rationals like they
/// are used to store an angle for GPS data.
/// </summary>
/// <param name="angle">
/// A <see cref="System.Double"/> between 0.0d and 180.0d with the angle
/// in degrees
/// </param>
/// <returns>
/// A <see cref="Rational"/> representing the same angle by degree, minutes
/// and seconds of the angle.
/// </returns>
private Rational[] DegreeToRationals (double angle)
{
if (angle < 0.0 || angle > 180.0)
throw new ArgumentException ("angle");
uint deg = (uint) Math.Floor (angle);
uint min = (uint) ((angle - Math.Floor (angle)) * 60.0);
uint sec = (uint) ((angle - Math.Floor (angle) - (min / 60.0)) * 360000000.0);
Rational[] rationals = new Rational [] {
new Rational (deg, 1),
new Rational (min, 1),
new Rational (sec, 100000)
};
return rationals;
}
#endregion
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <michaldominik@gmail.com> //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included //
// in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE. //
// //
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Runtime.InteropServices;
using GLib;
namespace Gdv {
public delegate bool InspectorHandler ();
public class Inspector : GLib.Object {
public struct MediaTags {
public int TrackNumber;
public string Title;
public string Artist;
public string Album;
public string Genre;
public string Comment;
public bool HasTrackNumber { get { return (TrackNumber != -1); }}
public bool HasTitle { get { return (Title != null &&
Title != String.Empty); }}
public bool HasArtist { get { return (Artist != null &&
Artist != String.Empty); }}
public bool HasAlbum { get { return (Album != null &&
Album != String.Empty); }}
public bool HasGenre { get { return (Genre != null &&
Genre != String.Empty); }}
public bool HasComment { get { return (Comment != null &&
Comment != String.Empty); }}
public bool HasAnyTag {
get {
if (HasTrackNumber ||
HasTitle ||
HasArtist ||
HasAlbum ||
HasGenre ||
HasComment)
return true;
else
return false;
}
}
}
// Imports ////////////////////////////////////////////////////
[DllImport ("gdv")]
internal static extern IntPtr gdv_inspector_new
(IntPtr filename);
[DllImport ("gdv")]
internal static extern int gdv_inspector_get_tag_type
(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string tag);
[DllImport ("gdv")]
internal static extern bool gdv_inspector_get_int_tag
(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string tag, out Int64 val);
[DllImport ("gdv")]
internal static extern bool gdv_inspector_get_uint_tag
(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string tag, out UInt64 val);
[DllImport ("gdv")]
internal static extern bool gdv_inspector_set_done_func
(IntPtr obj, InspectorHandler handlerc);
[DllImport ("gdv")]
internal static extern bool gdv_inspector_set_error_func
(IntPtr obj, InspectorHandler handlerc);
[DllImport ("gdv")]
internal static extern bool gdv_inspector_start
(IntPtr obj);
[DllImport ("gdv")]
internal static extern bool gdv_inspector_abort
(IntPtr obj);
[DllImport ("gdv")]
internal static extern bool gdv_inspector_get_string_tag
(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string tag,
[MarshalAs(UnmanagedType.LPStr)] out string val);
// Propeties //////////////////////////////////////////////////
public string Url {
get { return (string) GetProperty ("url"); }
}
public string Mime {
get { return (string) GetProperty ("mime"); }
}
public bool HasVideo {
get { return (bool) GetProperty ("hasvideo"); }
}
public bool HasAudio {
get { return (bool) GetProperty ("hasaudio"); }
}
public VideoFormat VideoFormat {
get { return (VideoFormat) GetProperty ("videoformat"); }
}
public AudioFormat AudioFormat {
get { return (AudioFormat) GetProperty ("audioformat"); }
}
public Time Length {
get { return (Time) GetProperty ("length"); }
}
public string Error {
get {
IntPtr ptr = (IntPtr) GetProperty ("error");
return Glue.GErrorGetString (ptr);
}
}
public MediaTags Tags {
get {
MediaTags t = new MediaTags();
gdv_inspector_get_string_tag (this.Handle, "title", out t.Title);
gdv_inspector_get_string_tag (this.Handle, "artist", out t.Artist);
gdv_inspector_get_string_tag (this.Handle, "album", out t.Album);
gdv_inspector_get_string_tag (this.Handle, "genre", out t.Genre);
gdv_inspector_get_string_tag (this.Handle, "comment", out t.Comment);
Int64 tmp;
if (gdv_inspector_get_int_tag (this.Handle, "track-number", out tmp))
t.TrackNumber = (int) tmp;
else
t.TrackNumber = -1;
return t;
}
}
// Public methods /////////////////////////////////////////////
public Inspector (IntPtr ptr) : base (ptr)
{
}
public Inspector (string fileName) : base (IntPtr.Zero)
{
IntPtr fileNamePtr = Marshaller.StringToPtrGStrdup (fileName);
IntPtr raw = gdv_inspector_new (fileNamePtr);
Marshaller.Free (fileNamePtr);
this.Raw = raw;
}
public void SetDoneFunc (InspectorHandler handler)
{
gdv_inspector_set_done_func (Handle, handler);
}
public void SetErrorFunc (InspectorHandler handler)
{
gdv_inspector_set_error_func (Handle, handler);
}
public void Start ()
{
gdv_inspector_start (Handle);
}
public void Abort ()
{
gdv_inspector_abort (Handle);
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2014 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 12.20Release
// Tag = $Name$
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Diagnostics;
using System.IO;
namespace FitFilePreviewer.Decode.Fit
{
/// <summary>
/// This class will decode a .fit file reading the file header and any definition or data messages.
/// </summary>
public class Decode
{
private readonly MesgDefinition[] localMesgDefs = new MesgDefinition[Fit.MaxLocalMesgs];
private Header fileHeader;
private int lastTimeOffset;
private uint timestamp;
/// <summary>
/// Reads the file header to check if the file is FIT.
/// Does not check CRC.
/// Returns true if file is FIT.
/// </summary>
/// <param name="fitStream"> Seekable (file)stream to parse</param>
public bool IsFIT(Stream fitStream)
{
try
{
// Does the header contain the flag string ".FIT"?
var header = new Header(fitStream);
return header.IsValid();
}
// If the header is malformed the ctor could throw an exception
catch (FitException)
{
return false;
}
}
/// <summary>
/// Reads the FIT binary file header and crc to check compatibility and integrity.
/// Also checks data reords size.
/// Returns true if file is ok (not corrupt).
/// </summary>
/// <param name="fitStream">Seekable (file)stream to parse.</param>
public bool CheckIntegrity(Stream fitStream)
{
bool isValid;
try
{
// Is there a valid header?
var header = new Header(fitStream);
isValid = header.IsValid();
// Are there as many data bytes as the header claims?
isValid &= ((header.Size + header.DataSize + 2) == fitStream.Length);
// Is the file CRC ok?
var data = new byte[fitStream.Length];
fitStream.Position = 0;
fitStream.Read(data, 0, data.Length);
isValid &= (CRC.Calc16(data, data.Length) == 0x0000);
return isValid;
}
catch (FitException)
{
return false;
}
}
/// <summary>
/// Reads a FIT binary file.
/// </summary>
/// <param name="fitStream">Seekable (file)stream to parse.</param>
/// <returns>
/// Returns true if reading finishes successfully.
/// </returns>
public bool Read(Stream fitStream)
{
bool readOK = true;
try
{
// Attempt to read header
fileHeader = new Header(fitStream);
readOK &= fileHeader.IsValid();
if ((fileHeader.ProtocolVersion & Fit.ProtocolVersionMajorMask) >
(Fit.ProtocolMajorVersion << Fit.ProtocolVersionMajorShift))
{
// The decoder does not support decode accross protocol major revisions
throw new FitException(
String.Format(
"FIT decode error: Protocol Version {0}.X not supported by SDK Protocol Ver{1}.{2} ",
(fileHeader.ProtocolVersion & Fit.ProtocolVersionMajorMask) >> Fit.ProtocolVersionMajorShift,
Fit.ProtocolMajorVersion, Fit.ProtocolMinorVersion));
}
// Read data messages and definitions
while (fitStream.Position < fitStream.Length - 2)
{
DecodeNextMessage(fitStream);
}
// Is the file CRC ok?
var data = new byte[fitStream.Length];
fitStream.Position = 0;
fitStream.Read(data, 0, data.Length);
readOK &= (CRC.Calc16(data, data.Length) == 0x0000);
}
catch (EndOfStreamException e)
{
readOK = false;
Console.WriteLine("{0} caught and ignored. ", e.GetType().Name);
throw new FitException("Decode:Read - Unexpected End of File", e);
}
return readOK;
}
public void DecodeNextMessage(Stream fitStream)
{
var br = new BinaryReader(fitStream);
byte nextByte = br.ReadByte();
// Is it a compressed timestamp mesg?
if ((nextByte & Fit.CompressedHeaderMask) == Fit.CompressedHeaderMask)
{
var mesgBuffer = new MemoryStream();
int timeOffset = nextByte & Fit.CompressedTimeMask;
timestamp += (uint)((timeOffset - lastTimeOffset) & Fit.CompressedTimeMask);
lastTimeOffset = timeOffset;
var timestampField = new Field(Profile.mesgs[Profile.RecordIndex].GetField("Timestamp"));
timestampField.SetValue(timestamp);
var localMesgNum = (byte)((nextByte & Fit.CompressedLocalMesgNumMask) >> 5);
mesgBuffer.WriteByte(localMesgNum);
if (localMesgDefs[localMesgNum] == null)
{
throw new FitException(
"Decode:DecodeNextMessage - FIT decode error: Missing message definition for local message number " + localMesgNum +
".");
}
int fieldsSize = localMesgDefs[localMesgNum].GetMesgSize() - 1;
try
{
mesgBuffer.Write(br.ReadBytes(fieldsSize), 0, fieldsSize);
}
catch (IOException e)
{
throw new FitException(
"Decode:DecodeNextMessage - Compressed Data Message unexpected end of file. Wanted " + fieldsSize +
" bytes at stream position " + fitStream.Position, e);
}
var newMesg = new Mesg(mesgBuffer, localMesgDefs[localMesgNum]);
newMesg.InsertField(0, timestampField);
if (MesgEvent != null)
{
MesgEvent(this, new MesgEventArgs(newMesg));
}
}
// Is it a mesg def?
else if ((nextByte & Fit.HeaderTypeMask) == Fit.MesgDefinitionMask)
{
var mesgDefBuffer = new MemoryStream();
// Figure out number of fields (length) of our defn and build buffer
mesgDefBuffer.WriteByte(nextByte);
mesgDefBuffer.Write(br.ReadBytes(4), 0, 4);
byte numfields = br.ReadByte();
mesgDefBuffer.WriteByte(numfields);
try
{
mesgDefBuffer.Write(br.ReadBytes(numfields*3), 0, numfields*3);
}
catch (IOException e)
{
throw new FitException(
"Decode:DecodeNextMessage - Defn Message unexpected end of file. Wanted " + (numfields*3) +
" bytes at stream position " + fitStream.Position, e);
}
var newMesgDef = new MesgDefinition(mesgDefBuffer);
localMesgDefs[newMesgDef.LocalMesgNum] = newMesgDef;
if (MesgDefinitionEvent != null)
{
MesgDefinitionEvent(this, new MesgDefinitionEventArgs(newMesgDef));
}
}
// Is it a data mesg?
else if ((nextByte & Fit.HeaderTypeMask) == Fit.MesgHeaderMask)
{
var mesgBuffer = new MemoryStream();
var localMesgNum = (byte) (nextByte & Fit.LocalMesgNumMask);
mesgBuffer.WriteByte(localMesgNum);
if (localMesgDefs[localMesgNum] == null)
{
throw new FitException(
"Decode:DecodeNextMessage - FIT decode error: Missing message definition for local message number " + localMesgNum +
".");
}
int fieldsSize = localMesgDefs[localMesgNum].GetMesgSize() - 1;
try
{
mesgBuffer.Write(br.ReadBytes(fieldsSize), 0, fieldsSize);
}
catch (Exception e)
{
throw new FitException(
"Decode:DecodeNextMessage - Data Message unexpected end of file. Wanted " + fieldsSize +
" bytes at stream position " + fitStream.Position, e);
}
var newMesg = new Mesg(mesgBuffer, localMesgDefs[localMesgNum]);
// If the new message contains a timestamp field, record the value to use as
// a reference for compressed timestamp headers
Field timestampField = newMesg.GetField("Timestamp");
if (timestampField != null)
{
timestamp = (uint) timestampField.GetValue();
lastTimeOffset = (int) timestamp & Fit.CompressedTimeMask;
}
// Now that the entire message is decoded we can evaluate subfields and expand any components
newMesg.ExpandComponents();
if (MesgEvent != null)
{
MesgEvent(this, new MesgEventArgs(newMesg));
}
}
else
{
throw new FitException("Decode:Read - FIT decode error: Unexpected Record Header Byte 0x" + nextByte.ToString("X"));
}
}
public event MesgEventHandler MesgEvent;
public event MesgDefinitionEventHandler MesgDefinitionEvent;
} // class
} // namespace
| |
/****************************************************************************
* Class Name : ErrorWarnInfoProvider.cs
* Author : Kenneth J. Koteles
* Created : 10/04/2007 2:14 PM
* C# Version : .NET 2.0
* Description : This code is designed to create a new provider object to
* work specifically with CSLA BusinessBase objects. In
* addition to providing the red error icon for items in the
* BrokenRulesCollection with Csla.Validation.RuleSeverity.Error,
* this object also provides a yellow warning icon for items
* with Csla.Validation.RuleSeverity.Warning and a blue
* information icon for items with
* Csla.Validation.RuleSeverity.Information. Since warnings
* and information type items do not need to be fixed /
* corrected prior to the object being saved, the tooltip
* displayed when hovering over the respective icon contains
* all the control's associated (by severity) broken rules.
* Revised : 11/20/2007 8:32 AM
* Change : Warning and information icons were not being updated for
* dependant properties (controls without the focus) when
* changes were being made to a related property (control with
* the focus). Added a list of controls to be recursed
* through each time a change was made to any control. This
* obviously could result in performance issues; however,
* there is no consistent way to question the BusinessObject
* in order to get a list of dependant properties based on a
* property name. It can be exposed to the UI (using
* ValidationRules.GetRuleDescriptions()); however, it is up
* to each developer to implement their own public method on
* on the Business Object to do so. To make this generic for
* all CSLA Business Objects, I cannot assume the developer
* always exposes the dependant properties (nor do I know what
* they'll call the method); therefore, this is the best I can
* do right now.
* Revised : 11/23/2007 9:02 AM
* Change : Added new property ProcessDependantProperties to allow for
* controlling when all controls are recursed through (for
* dependant properties or not). Default value is 'false'.
* This allows the developer to ba able to choose whether or
* not to use the control in this manner (which could have
* performance implications).
* Revised : 10/05/2009, Jonny Bekkum
* Change: Added initialization of controls list (controls attached to BindingSource)
* and will update errors on all controls. Optimized retrieval of error, warn, info
* messages and setting these on the controls.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace MyCsla.Windows
{
/// <summary>
/// Windows Forms extender control that automatically
/// displays error, warning, or information icons and
/// text for the form controls based on the
/// BrokenRulesCollection from a CSLA .NET business object.
/// </summary>
[DesignerCategory("")]
[ToolboxItem(true), ToolboxBitmap(typeof(ErrorWarnInfoProvider), "ErrorWarnInfoProvider.bmp")]
public partial class ErrorWarnInfoProvider : ErrorProvider, IExtenderProvider, ISupportInitialize
{
#region internal variables
private int _blinkRateInformation;
private int _blinkRateWarning;
private ErrorBlinkStyle _blinkStyleInformation = ErrorBlinkStyle.BlinkIfDifferentError;
private ErrorBlinkStyle _blinkStyleWarning = ErrorBlinkStyle.BlinkIfDifferentError;
private List<Control> _controls = new List<Control>();
private const int _defaultBlinkRate = 0;
private const int _defaultBlinkRateInformation = 0;
private const int _defaultBlinkRateWarning = 0;
private static Icon _defaultIconInformation;
private static Icon _defaultIconWarning;
private Icon _iconInformation;
private Icon _iconWarning;
private int _offsetInformation = 32;
private int _offsetWarning = 16;
private bool _visibleInformation = true;
private bool _visibleWarning = true;
private bool _showMostSevereOnly = true;
private Dictionary<string, string> _errorList = new Dictionary<string, string>();
private Dictionary<string, string> _warningList = new Dictionary<string, string>();
private Dictionary<string, string> _infoList = new Dictionary<string, string>();
private bool _isInitializing = false;
#endregion
#region Constructors
/// <summary>
/// Creates an instance of the object.
/// </summary>
/// <param name="container">The container of the control.</param>
public ErrorWarnInfoProvider(IContainer container)
{
container.Add(this);
InitializeComponent();
base.BlinkRate = 0;
_blinkRateInformation = _defaultBlinkRateInformation;
_iconInformation = DefaultIconInformation;
errorProviderInfo.BlinkRate = _blinkRateInformation;
errorProviderInfo.Icon = _iconInformation;
_blinkRateWarning = _defaultBlinkRateWarning;
_iconWarning = DefaultIconWarning;
errorProviderWarn.BlinkRate = _blinkRateWarning;
errorProviderWarn.Icon = _iconWarning;
}
#endregion
#region IExtenderProvider Members
/// <summary>
/// Gets a value indicating whether the extender control
/// can extend the specified control.
/// </summary>
/// <param name="extendee">The control to be extended.</param>
/// <remarks>
/// Any control implementing either a ReadOnly property or
/// Enabled property can be extended.
/// </remarks>
bool IExtenderProvider.CanExtend(object extendee)
{
//if (extendee is ErrorProvider)
//{
// return true;
//}
if ((extendee is Control && !(extendee is Form)))
{
return !(extendee is ToolBar);
}
else
{
return false;
}
}
#endregion
#region Public properties
/// <summary>
/// Gets or sets the blink rate information.
/// </summary>
/// <value>The blink rate information.</value>
[DefaultValue(_defaultBlinkRate), Description("The rate in milliseconds at which the error icon blinks.")]
public new int BlinkRate
{
get
{
return base.BlinkRate;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("BlinkRate", value, "Blink rate must be zero or more");
}
base.BlinkRate = value;
if (value == 0)
{
BlinkStyle = ErrorBlinkStyle.NeverBlink;
}
}
}
/// <summary>
/// Gets or sets the blink rate information.
/// </summary>
/// <value>The blink rate information.</value>
[DefaultValue(_defaultBlinkRateInformation), Description("The rate in milliseconds at which the information icon blinks.")]
public int BlinkRateInformation
{
get
{
return _blinkRateInformation;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("BlinkRateInformation", value, "Blink rate must be zero or more");
}
_blinkRateInformation = value;
errorProviderInfo.BlinkRate = _blinkRateInformation;
if (_blinkRateInformation == 0)
{
BlinkStyleInformation = ErrorBlinkStyle.NeverBlink;
}
}
}
/// <summary>
/// Gets or sets the blink rate warning.
/// </summary>
/// <value>The blink rate warning.</value>
[DefaultValue(_defaultBlinkRateWarning), Description("The rate in milliseconds at which the warning icon blinks.")]
public int BlinkRateWarning
{
get
{
return _blinkRateWarning;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("BlinkRateWarning", value, "Blink rate must be zero or more");
}
_blinkRateWarning = value;
errorProviderWarn.BlinkRate = _blinkRateWarning;
if (_blinkRateWarning == 0)
{
BlinkStyleWarning = ErrorBlinkStyle.NeverBlink;
}
}
}
/// <summary>
/// Gets or sets the blink style information.
/// </summary>
/// <value>The blink style information.</value>
[Description("Controls whether the information icon blinks when information is set.")]
public ErrorBlinkStyle BlinkStyleInformation
{
get
{
if (_blinkRateInformation == 0)
{
return ErrorBlinkStyle.NeverBlink;
}
return _blinkStyleInformation;
}
set
{
if (_blinkRateInformation == 0)
{
value = ErrorBlinkStyle.NeverBlink;
}
if (_blinkStyleInformation != value)
{
_blinkStyleInformation = value;
errorProviderInfo.BlinkStyle = _blinkStyleInformation;
}
}
}
/// <summary>
/// Gets or sets the blink style warning.
/// </summary>
/// <value>The blink style warning.</value>
[Description("Controls whether the warning icon blinks when a warning is set.")]
public ErrorBlinkStyle BlinkStyleWarning
{
get
{
if (_blinkRateWarning == 0)
{
return ErrorBlinkStyle.NeverBlink;
}
return _blinkStyleWarning;
}
set
{
if (_blinkRateWarning == 0)
{
value = ErrorBlinkStyle.NeverBlink;
}
if (_blinkStyleWarning != value)
{
_blinkStyleWarning = value;
errorProviderWarn.BlinkStyle = _blinkStyleWarning;
}
}
}
/// <summary>
/// Gets or sets the data source that the <see cref="T:System.Windows.Forms.ErrorProvider"></see> monitors.
/// </summary>
/// <value></value>
/// <returns>A data source based on the <see cref="T:System.Collections.IList"></see> interface to be monitored for errors. Typically, this is a <see cref="T:System.Data.DataSet"></see> to be monitored for errors.</returns>
/// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
[DefaultValue((string)null)]
public new object DataSource
{
get
{
return base.DataSource;
}
set
{
if (base.DataSource != value)
{
var bs1 = base.DataSource as BindingSource;
if (bs1 != null)
{
bs1.DataSourceChanged -= DataSource_DataSourceChanged;
bs1.CurrentItemChanged -= DataSource_CurrentItemChanged;
//bs1.BindingComplete -= DataSource_BindingComplete;
}
}
base.DataSource = value;
var bs = value as BindingSource;
if (bs != null)
{
bs.DataSourceChanged += DataSource_DataSourceChanged;
bs.CurrentItemChanged += DataSource_CurrentItemChanged;
//bs.BindingComplete += DataSource_BindingComplete;
//if (bs.DataSource != null) {
// UpdateBindingsAndProcessAllControls();
//}
}
}
}
private void DataSource_BindingComplete(object sender, BindingCompleteEventArgs e)
{
UpdateBindingsAndProcessAllControls();
}
private void UpdateBindingsAndProcessAllControls()
{
if (ContainerControl != null)
{
InitializeAllControls(ContainerControl.Controls);
}
ProcessAllControls();
}
/// <summary>
/// Gets or sets the icon information.
/// </summary>
/// <value>The icon information.</value>
[Description("The icon used to indicate information.")]
public Icon IconInformation
{
get
{
return _iconInformation;
}
set
{
if (value == null)
{
value = DefaultIconInformation;
}
_iconInformation = value;
errorProviderInfo.Icon = _iconInformation;
}
}
/// <summary>
/// Gets or sets the icon warning.
/// </summary>
/// <value>The icon warning.</value>
[Description("The icon used to indicate a warning.")]
public Icon IconWarning
{
get
{
return _iconWarning;
}
set
{
if (value == null)
{
value = DefaultIconWarning;
}
_iconWarning = value;
errorProviderWarn.Icon = _iconWarning;
}
}
/// <summary>
/// Gets or sets the offset information.
/// </summary>
/// <value>The offset information.</value>
[DefaultValue(32), Description("The number of pixels the information icon will be offset from the error icon.")]
public int OffsetInformation
{
get
{
return _offsetInformation;
}
set
{
if (_offsetInformation != value)
{
_offsetInformation = value;
}
}
}
/// <summary>
/// Gets or sets the offset warning.
/// </summary>
/// <value>The offset warning.</value>
[DefaultValue(16), Description("The number of pixels the warning icon will be offset from the error icon.")]
public int OffsetWarning
{
get
{
return _offsetWarning;
}
set
{
if (_offsetWarning != value)
{
_offsetWarning = value;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether broken rules with severity Infomation should be visible.
/// </summary>
/// <value><c>true</c> if Infomation is visible; otherwise, <c>false</c>.</value>
[DefaultValue(true), Description("Determines if the information icon should be displayed when information exists.")]
public bool VisibleInformation
{
get
{
return _visibleInformation;
}
set
{
if (_visibleInformation != value)
{
_visibleInformation = value;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether broken rules with severity Warning should be visible.
/// </summary>
/// <value><c>true</c> if Warning is visible; otherwise, <c>false</c>.</value>
[DefaultValue(true), Description("Determines if the warning icon should be displayed when warnings exist.")]
public bool VisibleWarning
{
get
{
return _visibleWarning;
}
set
{
if (_visibleWarning != value)
{
_visibleWarning = value;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether show only most severe broken rules message.
/// </summary>
/// <value><c>true</c> if show only most severe; otherwise, <c>false</c>.</value>
[DefaultValue(true), Description("Determines if the broken rules are show by severity - if true only most severe level is shown.")]
public bool ShowOnlyMostSevere
{
get
{
return _showMostSevereOnly;
}
set
{
if (_showMostSevereOnly != value)
{
_showMostSevereOnly = value;
//Refresh controls
ProcessAllControls();
}
}
}
#endregion
#region Private properties
private Icon DefaultIconInformation
{
get
{
if (_defaultIconInformation == null)
{
lock (typeof(ErrorWarnInfoProvider))
{
if (_defaultIconInformation == null)
{
Bitmap bitmap = (Bitmap)imageList1.Images[2];
_defaultIconInformation = Icon.FromHandle(bitmap.GetHicon());
}
}
}
return _defaultIconInformation;
}
}
private Icon DefaultIconWarning
{
get
{
if (_defaultIconWarning == null)
{
lock (typeof(ErrorWarnInfoProvider))
{
if (_defaultIconWarning == null)
{
Bitmap bitmap = (Bitmap)imageList1.Images[1];
_defaultIconWarning = Icon.FromHandle(bitmap.GetHicon());
}
}
}
return _defaultIconWarning;
}
}
#endregion
#region Methods
/// <summary>
/// Clears all errors associated with this component.
/// </summary>
/// <PermissionSet><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
public new void Clear()
{
base.Clear();
errorProviderInfo.Clear();
errorProviderWarn.Clear();
}
/// <summary>
/// Gets the information.
/// </summary>
/// <param name="control">The control.</param>
/// <returns></returns>
public string GetInformation(Control control)
{
return errorProviderInfo.GetError(control);
}
/// <summary>
/// Gets the warning.
/// </summary>
/// <param name="control">The control.</param>
/// <returns></returns>
public string GetWarning(Control control)
{
return errorProviderWarn.GetError(control);
}
private void InitializeAllControls(Control.ControlCollection controls)
{
// clear internal
_controls.Clear();
// run recursive initialize of controls
Initialize(controls);
}
private void Initialize(Control.ControlCollection controls)
{
//We don't provide an extended property, so if the control is
// not a Label then 'hook' the validating event here!
foreach (Control control in controls)
{
if (control is Label) continue;
// Initialize bindings
foreach (Binding binding in control.DataBindings)
{
// get the Binding if appropriate
if (binding.DataSource == DataSource)
{
_controls.Add(control);
}
}
// Initialize any subcontrols
if (control.Controls.Count > 0)
{
Initialize(control.Controls);
}
}
}
void DataSource_CurrentItemChanged(object sender, EventArgs e)
{
ProcessAllControls();
}
void DataSource_DataSourceChanged(object sender, EventArgs e)
{
//InitializeAllControls(ContainerControl.Controls);
//ProcessAllControls();
}
private void ProcessAllControls()
{
if (_isInitializing) return;
// get error/warn/info list from bussiness object
GetWarnInfoList();
// process controls in window
ProcessControls();
}
private void GetWarnInfoList()
{
_infoList.Clear();
_warningList.Clear();
_errorList.Clear();
BindingSource bs = (BindingSource)DataSource;
if (bs == null) return;
if (bs.Position == -1) return;
// we can only deal with CSLA BusinessBase objects
if (bs.Current is Csla.Core.BusinessBase)
{
// get the BusinessBase object
Csla.Core.BusinessBase bb = bs.Current as Csla.Core.BusinessBase;
if (bb != null)
{
foreach (Csla.Validation.BrokenRule br in bb.BrokenRulesCollection)
{
switch (br.Severity)
{
case Csla.Validation.RuleSeverity.Error:
if (_errorList.ContainsKey(br.Property))
{
_errorList[br.Property] =
String.Concat(_errorList[br.Property], Environment.NewLine, br.Description);
}
else
{
_errorList.Add(br.Property, br.Description);
}
break;
case Csla.Validation.RuleSeverity.Warning:
if (_warningList.ContainsKey(br.Property))
{
_warningList[br.Property] =
String.Concat(_warningList[br.Property], Environment.NewLine, br.Description);
}
else
{
_warningList.Add(br.Property, br.Description);
}
break;
default: // consider it an Info
if (_infoList.ContainsKey(br.Property))
{
_infoList[br.Property] =
String.Concat(_infoList[br.Property], Environment.NewLine, br.Description);
}
else
{
_infoList.Add(br.Property, br.Description);
}
break;
}
}
}
}
}
private void ProcessControls()
{
foreach (Control control in _controls)
{
ProcessControl(control);
}
}
/// <summary>
/// Processes the control.
/// </summary>
/// <param name="control">The control.</param>
private void ProcessControl(IBindableComponent control)
{
if (control == null) throw new ArgumentNullException("control");
bool hasWarning = false;
bool hasInfo = false;
foreach (Binding binding in control.DataBindings)
{
// get the Binding if appropriate
if (binding.DataSource == DataSource)
{
string propertyName = binding.BindingMemberInfo.BindingField;
bool bError = _errorList.ContainsKey(propertyName);
bool bWarn = _warningList.ContainsKey(propertyName);
bool bInfo = _infoList.ContainsKey(propertyName);
// set flags to indicat if Warning or Info is highest severity; else false
if (_showMostSevereOnly)
{
bInfo = bInfo && !bWarn && !bError;
bWarn = bWarn && !bError;
}
int offsetInformation = _offsetInformation;
int offsetWarning = _offsetWarning;
// Set / fix offsets
// by default the setting are correct for Error (0), Warning and Info
if (!bError)
{
if (bWarn)
{
// warning and possibly info, no error
offsetInformation = _offsetInformation - _offsetWarning;
offsetWarning = 0;
}
else
{
// Info only
offsetInformation = 0;
}
}
else if (!bWarn)
{
offsetInformation = _offsetInformation - _offsetWarning;
}
// should warning be visible
if (_visibleWarning && bWarn)
{
errorProviderWarn.SetError(binding.Control, _warningList[propertyName]);
errorProviderWarn.SetIconPadding(binding.Control,
base.GetIconPadding(binding.Control) +
offsetWarning);
errorProviderWarn.SetIconAlignment(binding.Control,
base.GetIconAlignment(binding.Control));
hasWarning = true;
}
// should info be shown
if (_visibleInformation && bInfo)
{
errorProviderInfo.SetError(binding.Control, _infoList[propertyName]);
errorProviderInfo.SetIconPadding(binding.Control,
base.GetIconPadding(binding.Control) +
offsetInformation);
errorProviderInfo.SetIconAlignment(binding.Control,
base.GetIconAlignment(binding.Control));
hasInfo = true;
}
}
}
if (!hasWarning) errorProviderWarn.SetError((Control)control, string.Empty);
if (!hasInfo) errorProviderInfo.SetError((Control)control, string.Empty);
}
private void ResetBlinkStyleInformation()
{
BlinkStyleInformation = ErrorBlinkStyle.BlinkIfDifferentError;
}
private void ResetBlinkStyleWarning()
{
BlinkStyleWarning = ErrorBlinkStyle.BlinkIfDifferentError;
}
private void ResetIconInformation()
{
IconInformation = DefaultIconInformation;
}
private void ResetIconWarning()
{
IconWarning = DefaultIconWarning;
}
/// <summary>
/// Sets the information.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="value">The value.</param>
public void SetInformation(Control control, string value)
{
errorProviderInfo.SetError(control, value);
}
/// <summary>
/// Sets the warning.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="value">The value.</param>
public void SetWarning(Control control, string value)
{
errorProviderWarn.SetError(control, value);
}
private bool ShouldSerializeIconInformation()
{
return (IconInformation != DefaultIconInformation);
}
private bool ShouldSerializeIconWarning()
{
return (IconWarning != DefaultIconWarning);
}
private bool ShouldSerializeBlinkStyleInformation()
{
return (BlinkStyleInformation != ErrorBlinkStyle.BlinkIfDifferentError);
}
private bool ShouldSerializeBlinkStyleWarning()
{
return (BlinkStyleWarning != ErrorBlinkStyle.BlinkIfDifferentError);
}
/// <summary>
/// Provides a method to update the bindings of the <see cref="P:System.Windows.Forms.ErrorProvider.DataSource"></see>, <see cref="P:System.Windows.Forms.ErrorProvider.DataMember"></see>, and the error text.
/// </summary>
/// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
public new void UpdateBinding()
{
base.UpdateBinding();
errorProviderInfo.UpdateBinding();
errorProviderWarn.UpdateBinding();
}
#endregion
#region ISupportInitialize Members
void ISupportInitialize.BeginInit()
{
_isInitializing = true;
}
void ISupportInitialize.EndInit()
{
_isInitializing = false;
if (this.ContainerControl != null)
{
InitializeAllControls(this.ContainerControl.Controls);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// A class that provides a simple, lightweight implementation of thread-local lazy-initialization, where a value is initialized once per accessing
// thread; this provides an alternative to using a ThreadStatic static variable and having
// to check the variable prior to every access to see if it's been initialized.
//
//
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Threading
{
/// <summary>
/// Provides thread-local storage of data.
/// </summary>
/// <typeparam name="T">Specifies the type of data stored per-thread.</typeparam>
/// <remarks>
/// <para>
/// With the exception of <see cref="Dispose()"/>, all public and protected members of
/// <see cref="ThreadLocal{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(SystemThreading_ThreadLocalDebugView<>))]
[DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")]
public class ThreadLocal<T> : IDisposable
{
// a delegate that returns the created value, if null the created value will be default(T)
private Func<T> m_valueFactory;
//
// ts_slotArray is a table of thread-local values for all ThreadLocal<T> instances
//
// So, when a thread reads ts_slotArray, it gets back an array of *all* ThreadLocal<T> values for this thread and this T.
// The slot relevant to this particular ThreadLocal<T> instance is determined by the m_idComplement instance field stored in
// the ThreadLocal<T> instance.
//
[ThreadStatic]
private static LinkedSlotVolatile[] ts_slotArray;
[ThreadStatic]
private static FinalizationHelper ts_finalizationHelper;
// Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish
// between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or
// possibly due to a memory model issue in user code.
private int m_idComplement;
// This field is set to true when the constructor completes. That is helpful for recognizing whether a constructor
// threw an exception - either due to invalid argument or due to a thread abort. Finally, the field is set to false
// when the instance is disposed.
private volatile bool m_initialized;
// IdManager assigns and reuses slot IDs. Additionally, the object is also used as a global lock.
private static IdManager s_idManager = new IdManager();
// A linked list of all values associated with this ThreadLocal<T> instance.
// We create a dummy head node. That allows us to remove any (non-dummy) node without having to locate the m_linkedSlot field.
private LinkedSlot m_linkedSlot = new LinkedSlot(null);
// Whether the Values property is supported
private bool m_trackAllValues;
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance.
/// </summary>
public ThreadLocal()
{
Initialize(null, false);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance.
/// </summary>
/// <param name="trackAllValues">Whether to track all values set on the instance and expose them through the Values property.</param>
public ThreadLocal(bool trackAllValues)
{
Initialize(null, trackAllValues);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the
/// specified <paramref name="valueFactory"/> function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when
/// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic).
/// </exception>
public ThreadLocal(Func<T> valueFactory)
{
if (valueFactory == null)
throw new ArgumentNullException(nameof(valueFactory));
Initialize(valueFactory, false);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the
/// specified <paramref name="valueFactory"/> function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when
/// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized.
/// </param>
/// <param name="trackAllValues">Whether to track all values set on the instance and expose them via the Values property.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic).
/// </exception>
public ThreadLocal(Func<T> valueFactory, bool trackAllValues)
{
if (valueFactory == null)
throw new ArgumentNullException(nameof(valueFactory));
Initialize(valueFactory, trackAllValues);
}
private void Initialize(Func<T> valueFactory, bool trackAllValues)
{
m_valueFactory = valueFactory;
m_trackAllValues = trackAllValues;
// Assign the ID and mark the instance as initialized. To avoid leaking IDs, we assign the ID and set m_initialized
// in a finally block, to avoid a thread abort in between the two statements.
try { }
finally
{
m_idComplement = ~s_idManager.GetId();
// As the last step, mark the instance as fully initialized. (Otherwise, if m_initialized=false, we know that an exception
// occurred in the constructor.)
m_initialized = true;
}
}
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
~ThreadLocal()
{
// finalizer to return the type combination index to the pool
Dispose(false);
}
#region IDisposable Members
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
/// <param name="disposing">
/// A Boolean value that indicates whether this method is being called due to a call to <see cref="Dispose()"/>.
/// </param>
/// <remarks>
/// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
int id;
using (LockHolder.Hold(s_idManager.m_lock))
{
id = ~m_idComplement;
m_idComplement = 0;
if (id < 0 || !m_initialized)
{
Debug.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized");
// Handle double Dispose calls or disposal of an instance whose constructor threw an exception.
return;
}
m_initialized = false;
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
LinkedSlotVolatile[] slotArray = linkedSlot.SlotArray;
if (slotArray == null)
{
// The thread that owns this slotArray has already finished.
continue;
}
// Remove the reference from the LinkedSlot to the slot table.
linkedSlot.SlotArray = null;
// And clear the references from the slot table to the linked slot and the value so that
// both can get garbage collected.
slotArray[id].Value.Value = default(T);
slotArray[id].Value = null;
}
}
m_linkedSlot = null;
s_idManager.ReturnId(id);
}
#endregion
/// <summary>Creates and returns a string representation of this instance for the current thread.</summary>
/// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see cref="Value"/>.</returns>
/// <exception cref="T:System.NullReferenceException">
/// The <see cref="Value"/> for the current thread is a null reference (Nothing in Visual Basic).
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// The initialization function referenced <see cref="Value"/> in an improper manner.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
/// <remarks>
/// Calling this method forces initialization for the current thread, as is the
/// case with accessing <see cref="Value"/> directly.
/// </remarks>
public override string ToString()
{
return Value.ToString();
}
/// <summary>
/// Gets or sets the value of this instance for the current thread.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The initialization function referenced <see cref="Value"/> in an improper manner.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
/// <remarks>
/// If this instance was not previously initialized for the current thread,
/// accessing <see cref="Value"/> will attempt to initialize it. If an initialization function was
/// supplied during the construction, that initialization will happen by invoking the function
/// to retrieve the initial value for <see cref="Value"/>. Otherwise, the default value of
/// <typeparamref name="T"/> will be used.
/// </remarks>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Value
{
get
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
LinkedSlot slot;
int id = ~m_idComplement;
//
// Attempt to get the value using the fast path
//
if (slotArray != null // Has the slot array been initialized?
&& id >= 0 // Is the ID non-negative (i.e., instance is not disposed)?
&& id < slotArray.Length // Is the table large enough?
&& (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID?
&& m_initialized // Has the instance *still* not been disposed (important for races with Dispose)?
)
{
// We verified that the instance has not been disposed *after* we got a reference to the slot.
// This guarantees that we have a reference to the right slot.
//
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// will not be reordered before the read of slotArray[id].
return slot.Value;
}
return GetValueSlow();
}
set
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
LinkedSlot slot;
int id = ~m_idComplement;
//
// Attempt to set the value using the fast path
//
if (slotArray != null // Has the slot array been initialized?
&& id >= 0 // Is the ID non-negative (i.e., instance is not disposed)?
&& id < slotArray.Length // Is the table large enough?
&& (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID?
&& m_initialized // Has the instance *still* not been disposed (important for races with Dispose)?
)
{
// We verified that the instance has not been disposed *after* we got a reference to the slot.
// This guarantees that we have a reference to the right slot.
//
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// will not be reordered before the read of slotArray[id].
slot.Value = value;
}
else
{
SetValueSlow(value, slotArray);
}
}
}
private T GetValueSlow()
{
// If the object has been disposed, the id will be -1.
int id = ~m_idComplement;
if (id < 0)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
//Debugger.NotifyOfCrossThreadDependency();
// Determine the initial value
T value;
if (m_valueFactory == null)
{
value = default(T);
}
else
{
value = m_valueFactory();
if (IsValueCreated)
{
throw new InvalidOperationException(SR.ThreadLocal_Value_RecursiveCallsToValue);
}
}
// Since the value has been previously uninitialized, we also need to set it (according to the ThreadLocal semantics).
Value = value;
return value;
}
private void SetValueSlow(T value, LinkedSlotVolatile[] slotArray)
{
int id = ~m_idComplement;
// If the object has been disposed, id will be -1.
if (id < 0)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
// If a slot array has not been created on this thread yet, create it.
if (slotArray == null)
{
slotArray = new LinkedSlotVolatile[GetNewTableSize(id + 1)];
ts_finalizationHelper = new FinalizationHelper(slotArray, m_trackAllValues);
ts_slotArray = slotArray;
}
// If the slot array is not big enough to hold this ID, increase the table size.
if (id >= slotArray.Length)
{
GrowTable(ref slotArray, id + 1);
ts_finalizationHelper.SlotArray = slotArray;
ts_slotArray = slotArray;
}
// If we are using the slot in this table for the first time, create a new LinkedSlot and add it into
// the linked list for this ThreadLocal instance.
if (slotArray[id].Value == null)
{
CreateLinkedSlot(slotArray, id, value);
}
else
{
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// that follows will not be reordered before the read of slotArray[id].
LinkedSlot slot = slotArray[id].Value;
// It is important to verify that the ThreadLocal instance has not been disposed. The check must come
// after capturing slotArray[id], but before assigning the value into the slot. This ensures that
// if this ThreadLocal instance was disposed on another thread and another ThreadLocal instance was
// created, we definitely won't assign the value into the wrong instance.
if (!m_initialized)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
slot.Value = value;
}
}
/// <summary>
/// Creates a LinkedSlot and inserts it into the linked list for this ThreadLocal instance.
/// </summary>
private void CreateLinkedSlot(LinkedSlotVolatile[] slotArray, int id, T value)
{
// Create a LinkedSlot
var linkedSlot = new LinkedSlot(slotArray);
// Insert the LinkedSlot into the linked list maintained by this ThreadLocal<> instance and into the slot array
using (LockHolder.Hold(s_idManager.m_lock))
{
// Check that the instance has not been disposed. It is important to check this under a lock, since
// Dispose also executes under a lock.
if (!m_initialized)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
LinkedSlot firstRealNode = m_linkedSlot.Next;
//
// Insert linkedSlot between nodes m_linkedSlot and firstRealNode.
// (m_linkedSlot is the dummy head node that should always be in the front.)
//
linkedSlot.Next = firstRealNode;
linkedSlot.Previous = m_linkedSlot;
linkedSlot.Value = value;
if (firstRealNode != null)
{
firstRealNode.Previous = linkedSlot;
}
m_linkedSlot.Next = linkedSlot;
// Assigning the slot under a lock prevents a race with Dispose (dispose also acquires the lock).
// Otherwise, it would be possible that the ThreadLocal instance is disposed, another one gets created
// with the same ID, and the write would go to the wrong instance.
slotArray[id].Value = linkedSlot;
}
}
/// <summary>
/// Gets a list for all of the values currently stored by all of the threads that have accessed this instance.
/// </summary>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
public IList<T> Values
{
get
{
if (!m_trackAllValues)
{
throw new InvalidOperationException(SR.ThreadLocal_ValuesNotAvailable);
}
var list = GetValuesAsList(); // returns null if disposed
if (list == null) throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
return list;
}
}
/// <summary>Gets all of the threads' values in a list.</summary>
private LowLevelListWithIList<T> GetValuesAsList()
{
LowLevelListWithIList<T> valueList = new LowLevelListWithIList<T>();
int id = ~m_idComplement;
if (id == -1)
{
return null;
}
// Walk over the linked list of slots and gather the values associated with this ThreadLocal instance.
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
// We can safely read linkedSlot.Value. Even if this ThreadLocal has been disposed in the meantime, the LinkedSlot
// objects will never be assigned to another ThreadLocal instance.
valueList.Add(linkedSlot.Value);
}
return valueList;
}
/// <summary>Gets the number of threads that have data in this instance.</summary>
private int ValuesCountForDebugDisplay
{
get
{
int count = 0;
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
count++;
}
return count;
}
}
/// <summary>
/// Gets whether <see cref="Value"/> is initialized on the current thread.
/// </summary>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
public bool IsValueCreated
{
get
{
int id = ~m_idComplement;
if (id < 0)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
LinkedSlotVolatile[] slotArray = ts_slotArray;
return slotArray != null && id < slotArray.Length && slotArray[id].Value != null;
}
}
/// <summary>Gets the value of the ThreadLocal<T> for debugging display purposes. It takes care of getting
/// the value for the current thread in the ThreadLocal mode.</summary>
internal T ValueForDebugDisplay
{
get
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
int id = ~m_idComplement;
LinkedSlot slot;
if (slotArray == null || id >= slotArray.Length || (slot = slotArray[id].Value) == null || !m_initialized)
return default(T);
return slot.Value;
}
}
/// <summary>Gets the values of all threads that accessed the ThreadLocal<T>.</summary>
internal IList<T> ValuesForDebugDisplay // same as Values property, but doesn't throw if disposed
{
get { return GetValuesAsList(); }
}
/// <summary>
/// Resizes a table to a certain length (or larger).
/// </summary>
private void GrowTable(ref LinkedSlotVolatile[] table, int minLength)
{
Debug.Assert(table.Length < minLength);
// Determine the size of the new table and allocate it.
int newLen = GetNewTableSize(minLength);
LinkedSlotVolatile[] newTable = new LinkedSlotVolatile[newLen];
//
// The lock is necessary to avoid a race with ThreadLocal.Dispose. GrowTable has to point all
// LinkedSlot instances referenced in the old table to reference the new table. Without locking,
// Dispose could use a stale SlotArray reference and clear out a slot in the old array only, while
// the value continues to be referenced from the new (larger) array.
//
using (LockHolder.Hold(s_idManager.m_lock))
{
for (int i = 0; i < table.Length; i++)
{
LinkedSlot linkedSlot = table[i].Value;
if (linkedSlot != null && linkedSlot.SlotArray != null)
{
linkedSlot.SlotArray = newTable;
newTable[i] = table[i];
}
}
}
table = newTable;
}
private const int MaxArrayLength = int.MaxValue;
/// <summary>
/// Chooses the next larger table size
/// </summary>
private static int GetNewTableSize(int minSize)
{
if ((uint)minSize > MaxArrayLength)
{
// Intentionally return a value that will result in an OutOfMemoryException
return int.MaxValue;
}
Debug.Assert(minSize > 0);
//
// Round up the size to the next power of 2
//
// The algorithm takes three steps:
// input -> subtract one -> propagate 1-bits to the right -> add one
//
// Let's take a look at the 3 steps in both interesting cases: where the input
// is (Example 1) and isn't (Example 2) a power of 2.
//
// Example 1: 100000 -> 011111 -> 011111 -> 100000
// Example 2: 011010 -> 011001 -> 011111 -> 100000
//
int newSize = minSize;
// Step 1: Decrement
newSize--;
// Step 2: Propagate 1-bits to the right.
newSize |= newSize >> 1;
newSize |= newSize >> 2;
newSize |= newSize >> 4;
newSize |= newSize >> 8;
newSize |= newSize >> 16;
// Step 3: Increment
newSize++;
// Don't set newSize to more than Array.MaxArrayLength
if ((uint)newSize > MaxArrayLength)
{
newSize = MaxArrayLength;
}
return newSize;
}
/// <summary>
/// A wrapper struct used as LinkedSlotVolatile[] - an array of LinkedSlot instances, but with volatile semantics
/// on array accesses.
/// </summary>
internal struct LinkedSlotVolatile
{
internal volatile LinkedSlot Value;
}
/// <summary>
/// A node in the doubly-linked list stored in the ThreadLocal instance.
///
/// The value is stored in one of two places:
///
/// 1. If SlotArray is not null, the value is in SlotArray.Table[id]
/// 2. If SlotArray is null, the value is in FinalValue.
/// </summary>
internal sealed class LinkedSlot
{
internal LinkedSlot(LinkedSlotVolatile[] slotArray)
{
SlotArray = slotArray;
}
// The next LinkedSlot for this ThreadLocal<> instance
internal volatile LinkedSlot Next;
// The previous LinkedSlot for this ThreadLocal<> instance
internal volatile LinkedSlot Previous;
// The SlotArray that stores this LinkedSlot at SlotArray.Table[id].
internal volatile LinkedSlotVolatile[] SlotArray;
// The value for this slot.
internal T Value;
}
/// <summary>
/// A manager class that assigns IDs to ThreadLocal instances
/// </summary>
private class IdManager
{
// The next ID to try
private int m_nextIdToTry = 0;
// Stores whether each ID is free or not. Additionally, the object is also used as a lock for the IdManager.
private LowLevelList<bool> m_freeIds = new LowLevelList<bool>();
internal Lock m_lock = new Lock();
internal int GetId()
{
using (LockHolder.Hold(m_lock))
{
int availableId = m_nextIdToTry;
while (availableId < m_freeIds.Count)
{
if (m_freeIds[availableId]) { break; }
availableId++;
}
if (availableId == m_freeIds.Count)
{
m_freeIds.Add(false);
}
else
{
m_freeIds[availableId] = false;
}
m_nextIdToTry = availableId + 1;
return availableId;
}
}
// Return an ID to the pool
internal void ReturnId(int id)
{
using (LockHolder.Hold(m_lock))
{
m_freeIds[id] = true;
if (id < m_nextIdToTry) m_nextIdToTry = id;
}
}
}
/// <summary>
/// A class that facilitates ThreadLocal cleanup after a thread exits.
///
/// After a thread with an associated thread-local table has exited, the FinalizationHelper
/// is reponsible for removing back-references to the table. Since an instance of FinalizationHelper
/// is only referenced from a single thread-local slot, the FinalizationHelper will be GC'd once
/// the thread has exited.
///
/// The FinalizationHelper then locates all LinkedSlot instances with back-references to the table
/// (all those LinkedSlot instances can be found by following references from the table slots) and
/// releases the table so that it can get GC'd.
/// </summary>
internal class FinalizationHelper
{
internal LinkedSlotVolatile[] SlotArray;
private bool m_trackAllValues;
internal FinalizationHelper(LinkedSlotVolatile[] slotArray, bool trackAllValues)
{
SlotArray = slotArray;
m_trackAllValues = trackAllValues;
}
~FinalizationHelper()
{
LinkedSlotVolatile[] slotArray = SlotArray;
Debug.Assert(slotArray != null);
for (int i = 0; i < slotArray.Length; i++)
{
LinkedSlot linkedSlot = slotArray[i].Value;
if (linkedSlot == null)
{
// This slot in the table is empty
continue;
}
if (m_trackAllValues)
{
// Set the SlotArray field to null to release the slot array.
linkedSlot.SlotArray = null;
}
else
{
// Remove the LinkedSlot from the linked list. Once the FinalizationHelper is done, all back-references to
// the table will be have been removed, and so the table can get GC'd.
using (LockHolder.Hold(s_idManager.m_lock))
{
if (linkedSlot.Next != null)
{
linkedSlot.Next.Previous = linkedSlot.Previous;
}
// Since the list uses a dummy head node, the Previous reference should never be null.
Debug.Assert(linkedSlot.Previous != null);
linkedSlot.Previous.Next = linkedSlot.Next;
}
}
}
}
}
}
/// <summary>A debugger view of the ThreadLocal<T> to surface additional debugging properties and
/// to ensure that the ThreadLocal<T> does not become initialized if it was not already.</summary>
internal sealed class SystemThreading_ThreadLocalDebugView<T>
{
//The ThreadLocal object being viewed.
private readonly ThreadLocal<T> m_tlocal;
/// <summary>Constructs a new debugger view object for the provided ThreadLocal object.</summary>
/// <param name="tlocal">A ThreadLocal object to browse in the debugger.</param>
public SystemThreading_ThreadLocalDebugView(ThreadLocal<T> tlocal)
{
m_tlocal = tlocal;
}
/// <summary>Returns whether the ThreadLocal object is initialized or not.</summary>
public bool IsValueCreated
{
get { return m_tlocal.IsValueCreated; }
}
/// <summary>Returns the value of the ThreadLocal object.</summary>
public T Value
{
get
{
return m_tlocal.ValueForDebugDisplay;
}
}
/// <summary>Return all values for all threads that have accessed this instance.</summary>
public IList<T> Values
{
get
{
return m_tlocal.ValuesForDebugDisplay;
}
}
}
}
| |
// 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.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
public class ImageConverterTest
{
private readonly Image _image;
private readonly ImageConverter _imgConv;
private readonly ImageConverter _imgConvFrmTD;
private readonly string _imageStr;
private readonly byte[] _imageBytes;
public ImageConverterTest()
{
_image = Image.FromFile(Path.Combine("bitmaps", "TestImage.bmp"));
_imageStr = _image.ToString();
using (MemoryStream destStream = new MemoryStream())
{
_image.Save(destStream, _image.RawFormat);
_imageBytes = destStream.ToArray();
}
_imgConv = new ImageConverter();
_imgConvFrmTD = (ImageConverter)TypeDescriptor.GetConverter(_image);
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void TestCanConvertFrom()
{
Assert.True(_imgConv.CanConvertFrom(typeof(byte[])), "byte[] (no context)");
Assert.True(_imgConv.CanConvertFrom(null, typeof(byte[])), "byte[]");
Assert.True(_imgConv.CanConvertFrom(null, _imageBytes.GetType()), "_imageBytes.GetType()");
Assert.False(_imgConv.CanConvertFrom(null, typeof(string)), "string");
Assert.False(_imgConv.CanConvertFrom(null, typeof(Rectangle)), "Rectangle");
Assert.False(_imgConv.CanConvertFrom(null, typeof(Point)), "Point");
Assert.False(_imgConv.CanConvertFrom(null, typeof(PointF)), "PointF");
Assert.False(_imgConv.CanConvertFrom(null, typeof(Size)), "Size");
Assert.False(_imgConv.CanConvertFrom(null, typeof(SizeF)), "SizeF");
Assert.False(_imgConv.CanConvertFrom(null, typeof(object)), "object");
Assert.False(_imgConv.CanConvertFrom(null, typeof(int)), "int");
Assert.False(_imgConv.CanConvertFrom(null, typeof(Metafile)), "Mefafile");
Assert.True(_imgConvFrmTD.CanConvertFrom(typeof(byte[])), "TD byte[] (no context)");
Assert.True(_imgConvFrmTD.CanConvertFrom(null, typeof(byte[])), "TD byte[]");
Assert.True(_imgConvFrmTD.CanConvertFrom(null, _imageBytes.GetType()), "TD _imageBytes.GetType()");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(string)), "TD string");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(Rectangle)), "TD Rectangle");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(Point)), "TD Point");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(PointF)), "TD PointF");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(Size)), "TD Size");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(SizeF)), "TD SizeF");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(object)), "TD object");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(int)), "TD int");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(Metafile)), "TD Metafile");
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void TestCanConvertTo()
{
Assert.True(_imgConv.CanConvertTo(typeof(string)), "stirng (no context)");
Assert.True(_imgConv.CanConvertTo(null, typeof(string)), "string");
Assert.True(_imgConv.CanConvertTo(null, _imageStr.GetType()), "_imageStr.GetType()");
Assert.True(_imgConv.CanConvertTo(typeof(byte[])), "byte[] (no context)");
Assert.True(_imgConv.CanConvertTo(null, typeof(byte[])), "byte[]");
Assert.True(_imgConv.CanConvertTo(null, _imageBytes.GetType()), "_imageBytes.GetType()");
Assert.False(_imgConv.CanConvertTo(null, typeof(Rectangle)), "Rectangle");
Assert.False(_imgConv.CanConvertTo(null, typeof(Point)), "Point");
Assert.False(_imgConv.CanConvertTo(null, typeof(PointF)), "PointF");
Assert.False(_imgConv.CanConvertTo(null, typeof(Size)), "Size");
Assert.False(_imgConv.CanConvertTo(null, typeof(SizeF)), "SizeF");
Assert.False(_imgConv.CanConvertTo(null, typeof(object)), "object");
Assert.False(_imgConv.CanConvertTo(null, typeof(int)), "int");
Assert.True(_imgConvFrmTD.CanConvertTo(typeof(string)), "TD string (no context)");
Assert.True(_imgConvFrmTD.CanConvertTo(null, typeof(string)), "TD string");
Assert.True(_imgConvFrmTD.CanConvertTo(null, _imageStr.GetType()), "TD _imageStr.GetType()");
Assert.True(_imgConvFrmTD.CanConvertTo(typeof(byte[])), "TD byte[] (no context)");
Assert.True(_imgConvFrmTD.CanConvertTo(null, typeof(byte[])), "TD byte[]");
Assert.True(_imgConvFrmTD.CanConvertTo(null, _imageBytes.GetType()), "TD _imageBytes.GetType()");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(Rectangle)), "TD Rectangle");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(Point)), "TD Point");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(PointF)), "TD PointF");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(Size)), "TD Size");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(SizeF)), "TD SizeF");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(object)), "TD object");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(int)), "TD int");
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertFrom()
{
Image newImage = (Image)_imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, _imageBytes);
Assert.Equal(_image.Height, newImage.Height);
Assert.Equal(_image.Width, newImage.Width);
Assert.Equal("(none)", _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, null, typeof(string)));
newImage = (Image)_imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, _imageBytes);
Assert.Equal(_image.Height, newImage.Height);
Assert.Equal(_image.Width, newImage.Width);
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertFrom_ThrowsNotSupportedException()
{
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom("System.Drawing.String"));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, "System.Drawing.String"));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, new Bitmap(20, 20)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, new Point(10, 10)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, new SizeF(10, 10)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, new object()));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom("System.Drawing.String"));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, "System.Drawing.String"));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, new Bitmap(20, 20)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, new Point(10, 10)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, new SizeF(10, 10)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, new object()));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertTo_String()
{
Assert.Equal(_imageStr, (string)_imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(string)));
Assert.Equal(_imageStr, (string)_imgConv.ConvertTo(_image, typeof(string)));
Assert.Equal(_imageStr, (string)_imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(string)));
Assert.Equal(_imageStr, (string)_imgConvFrmTD.ConvertTo(_image, typeof(string)));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertTo_ByteArray()
{
byte[] newImageBytes = (byte[])_imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, _imageBytes.GetType());
Assert.Equal(_imageBytes, newImageBytes);
newImageBytes = (byte[])_imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, _imageBytes.GetType());
Assert.Equal(_imageBytes, newImageBytes);
newImageBytes = (byte[])_imgConvFrmTD.ConvertTo(_image, _imageBytes.GetType());
Assert.Equal(_imageBytes, newImageBytes);
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertTo_ThrowsNotSupportedException()
{
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Rectangle)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, _image.GetType()));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Size)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Bitmap)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Point)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Metafile)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(object)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(int)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Rectangle)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, _image.GetType()));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Size)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Bitmap)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Point)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Metafile)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(object)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(int)));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void TestGetPropertiesSupported()
{
Assert.True(_imgConv.GetPropertiesSupported(), "GetPropertiesSupported()");
Assert.True(_imgConv.GetPropertiesSupported(null), "GetPropertiesSupported(null)");
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void TestGetProperties()
{
const int allPropertiesCount = 14; // Count of all properties in Image class.
const int browsablePropertiesCount = 7; // Count of browsable properties in Image class (BrowsableAttribute.Yes).
PropertyDescriptorCollection propsColl;
// Internally calls TypeDescriptor.GetProperties(typeof(Image), null), which returns all properties.
propsColl = _imgConv.GetProperties(null, _image, null);
Assert.Equal(allPropertiesCount, propsColl.Count);
// Internally calls TypeDescriptor.GetProperties(typeof(Image), new Attribute[] { BrowsableAttribute.Yes }).
propsColl = _imgConv.GetProperties(null, _image);
Assert.Equal(browsablePropertiesCount, propsColl.Count);
propsColl = _imgConv.GetProperties(_image);
Assert.Equal(browsablePropertiesCount, propsColl.Count);
// Returns all properties of Image class.
propsColl = TypeDescriptor.GetProperties(typeof(Image));
Assert.Equal(allPropertiesCount, propsColl.Count);
// Internally calls TypeDescriptor.GetProperties(typeof(Image), null), which returns all properties.
propsColl = _imgConvFrmTD.GetProperties(null, _image, null);
Assert.Equal(allPropertiesCount, propsColl.Count);
// Internally calls TypeDescriptor.GetProperties(typeof(Image), new Attribute[] { BrowsableAttribute.Yes }).
propsColl = _imgConvFrmTD.GetProperties(null, _image);
Assert.Equal(browsablePropertiesCount, propsColl.Count);
propsColl = _imgConvFrmTD.GetProperties(_image);
Assert.Equal(browsablePropertiesCount, propsColl.Count);
}
}
}
| |
// 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.Runtime.CompilerServices;
namespace UninitializedHighWord
{
public struct StackFiller
{
public Int32 Field00;
public Int32 Field01;
public Int32 Field02;
public Int32 Field03;
public Int32 Field04;
public Int32 Field05;
public Int32 Field06;
public Int32 Field07;
public Int32 Field08;
public Int32 Field09;
public Int32 Field10;
public Int32 Field11;
public Int32 Field12;
public Int32 Field13;
public Int32 Field14;
public Int32 Field15;
[MethodImpl(MethodImplOptions.NoInlining)]
public static void FillWithFFPattern(ref StackFiller target)
{
target.Field00 = -1;
target.Field01 = -1;
target.Field02 = -1;
target.Field03 = -1;
target.Field04 = -1;
target.Field05 = -1;
target.Field06 = -1;
target.Field07 = -1;
target.Field08 = -1;
target.Field09 = -1;
target.Field10 = -1;
target.Field11 = -1;
target.Field12 = -1;
target.Field13 = -1;
target.Field14 = -1;
target.Field15 = -1;
return;
}
}
public struct SystemTime
{
public short Year;
public short Month;
public short DayOfWeek;
public short Day;
public short Hour;
public short Minute;
public short Second;
public short Milliseconds;
}
public struct RegistryTimeZoneInformation
{
public Int32 Bias;
public Int32 StandardBias;
public Int32 DaylightBias;
public SystemTime StandardDate;
public SystemTime DaylightDate;
}
internal static class App
{
private static bool s_fArgumentCheckPassed = false;
private static bool s_fPreparingMethods = false;
[MethodImpl(MethodImplOptions.NoInlining)]
private static
void CheckArguments(
Int32 fill,
Int32 year,
Int32 month,
Int32 day,
Int32 hour,
Int32 minute,
Int32 second,
Int32 milliseconds
)
{
if (App.s_fPreparingMethods)
{
return;
}
else
{
if ((hour == 0) &&
(minute == 0) &&
(second == 0) &&
(milliseconds == 0))
{
App.s_fArgumentCheckPassed = true;
Console.WriteLine("Argument check passed. All trailing arguments are zero.");
}
else
{
App.s_fArgumentCheckPassed = false;
Console.WriteLine(
"Argument check failed. Trailing argument values are:\r\n" +
" Hour = {0:x8}\r\n" +
" Minute = {1:x8}\r\n" +
" Second = {2:x8}\r\n" +
" Milliseconds = {3:x8}\r\n",
hour,
minute,
second,
milliseconds
);
}
return;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static
void GenerateHalfInitializedArgSlots(
RegistryTimeZoneInformation timeZoneInformation
)
{
if (timeZoneInformation.DaylightDate.Year == 0)
{
App.CheckArguments(
1,
1,
1,
1,
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds
);
}
return;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static
void InitializeStack(
Int32 arg1,
Int32 arg2,
Int32 arg3,
Int32 arg4,
StackFiller fill1,
StackFiller fill2,
StackFiller fill3,
StackFiller fill4
)
{
return;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static
void StompStackBelowCallerSP(
)
{
var filler = new StackFiller();
StackFiller.FillWithFFPattern(ref filler);
App.InitializeStack(
1, 1, 1, 1,
filler, filler, filler, filler
);
return;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static
void PrepareMethods(
)
{
var timeZoneInformation = new RegistryTimeZoneInformation();
App.s_fPreparingMethods = true;
{
App.GenerateHalfInitializedArgSlots(timeZoneInformation);
}
App.s_fPreparingMethods = false;
return;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static
int RunTest(
)
{
var timeZoneInformation = new RegistryTimeZoneInformation();
App.StompStackBelowCallerSP();
App.GenerateHalfInitializedArgSlots(timeZoneInformation);
if (App.s_fArgumentCheckPassed)
{
Console.WriteLine("Passed.");
return 100;
}
else
{
Console.WriteLine("Failed.");
return 101;
}
}
private static int Main()
{
App.PrepareMethods();
return App.RunTest();
}
}
}
| |
/*******************************************************************************
*
* Copyright (C) 2013-2014 Frozen North Computing
*
* 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.Drawing;
#if FN2D_WIN
using FN2DBitmap = System.Drawing.Bitmap;
#elif FN2D_IOS
using MonoTouch.UIKit;
using FN2DBitmap = MonoTouch.UIKit.UIImage;
#elif FN2D_AND
using FN2DBitmap = Android.Graphics.Bitmap;
#endif
namespace FrozenNorth.OpenGL.FN2D
{
/// <summary>
/// OpenGL 2D button base.
/// </summary>
public class FN2DButton : FN2DControl
{
// public constants
public static int IconTextPadding = 3;
// instance variables
protected FN2DBitmap normalIcon, disabledIcon, selectedIcon, disabledSelectedIcon;
protected FN2DImage iconImage;
protected FN2DLabel titleLabel;
protected Color topColor, bottomColor, topPressedColor, bottomPressedColor, topDisabledColor, bottomDisabledColor;
protected bool selected = false;
protected FN2DIconAlignment iconAlignment = FN2DIconAlignment.Left;
protected Point iconOffsets = Point.Empty;
protected Point titleOffsets = Point.Empty;
/// <summary>
/// Constructor - Creates a colored button based on top and bottom colors.
/// </summary>
/// <param name="canvas">Canvas that the button is on.</param>
/// <param name="frame">Position and size of the button.</param>
/// <param name="cornerRadius">Corner radius.</param>
/// <param name="topColor">Top color.</param>
/// <param name="bottomColor">Bottom color.</param>
/// <param name="title">Title that appears on the button.</param>
public FN2DButton(FN2DCanvas canvas, Rectangle frame, int cornerRadius, Color topColor, Color bottomColor, string title = "")
: base(canvas, frame, cornerRadius, topColor, bottomColor)
{
// disable refreshing
RefreshEnabled = false;
// create the icon image
iconImage = new FN2DImage(canvas);
Add(iconImage);
// create the label
titleLabel = new FN2DLabel(canvas, title);
titleLabel.Font = canvas.GetFont(FN2DCanvas.DefaultFontSize, true);
titleLabel.AutoSize = true;
Add(titleLabel);
// set the colors
TopColor = topColor;
BottomColor = bottomColor;
// enable refreshing
RefreshEnabled = true;
}
/// <summary>
/// Constructor - Creates a colored button based on top and bottom colors using the default corner radius.
/// </summary>
/// <param name="canvas">Canvas that the button is on.</param>
/// <param name="frame">Position and size of the button.</param>
/// <param name="topColor">Top color.</param>
/// <param name="bottomColor">Bottom color.</param>
/// <param name="title">Title that appears on the button.</param>
public FN2DButton(FN2DCanvas canvas, Rectangle frame, Color topColor, Color bottomColor, string title = "")
: this(canvas, frame, FN2DCanvas.DefaultCornerRadius, topColor, bottomColor, title)
{
}
/// <summary>
/// Constructor - Creates a colored button based on a single color using the default corner radius.
/// </summary>
/// <param name="canvas">Canvas that the button is on.</param>
/// <param name="frame">Position and size of the button.</param>
/// <param name="color">Top and bottom color.</param>
/// <param name="title">Title that appears on the button.</param>
public FN2DButton(FN2DCanvas canvas, Rectangle frame, Color color, string title = "")
: this(canvas, frame, FN2DCanvas.DefaultCornerRadius, color, color, title)
{
}
/// <summary>
/// Constructor - Creates a colored button based on the default top
/// and bottom colors using the default corner radius.
/// </summary>
/// <param name="canvas">Canvas that the button is on.</param>
/// <param name="frame">Position and size of the button.</param>
/// <param name="title">Title that appears on the button.</param>
public FN2DButton(FN2DCanvas canvas, Rectangle frame, string title = "")
: this(canvas, frame, FN2DCanvas.DefaultCornerRadius, FN2DCanvas.DefaultTopColor, FN2DCanvas.DefaultBottomColor, title)
{
}
/// <summary>
/// Constructor - Creates a colored button based on the default
/// top and bottom colors using the default corner radius.
/// </summary>
/// <param name="canvas">Canvas that the button is on.</param>
/// <param name="size">Size of the button.</param>
/// <param name="title">Title that appears on the button.</param>
public FN2DButton(FN2DCanvas canvas, Size size, string title = "")
: this(canvas, new Rectangle(Point.Empty, size), title)
{
}
/// <summary>
/// Constructor - Creates a colored button based on the default top and
/// bottom colors using the default corner radius and size.
/// </summary>
/// <param name="canvas">Canvas that the button is on.</param>
/// <param name="title">Title that appears on the button.</param>
public FN2DButton(FN2DCanvas canvas, string title = "")
: this(canvas, FN2DCanvas.DefaultButtonSize, title)
{
}
/// <summary>
/// Frees unmanaged resources and calls Dispose() on the member objects.
/// </summary>
protected override void Dispose(bool disposing)
{
// if we got here via Dispose(), call Dispose() on the member objects
if (disposing)
{
if (normalIcon != null) normalIcon.Dispose();
if (disabledIcon != null) disabledIcon.Dispose();
if (selectedIcon != null) selectedIcon.Dispose();
if (disabledSelectedIcon != null) disabledSelectedIcon.Dispose();
}
// clear the object references
normalIcon = null;
disabledIcon = null;
selectedIcon = null;
disabledSelectedIcon = null;
iconImage = null;
titleLabel = null;
// call the base handler
base.Dispose(disposing);
}
/// <summary>
/// Sets the button images based on the current state.
/// </summary>
public override void Refresh()
{
if (refreshEnabled)
{
base.Refresh();
// don't do anyhting until the control has been fully created
if (iconImage == null || titleLabel == null)
{
return;
}
// set the background colors
if (!Enabled)
{
background.SetColors(topDisabledColor, bottomDisabledColor);
}
else if (touching)
{
if (selected)
{
background.SetColors(topColor, bottomColor);
}
else
{
background.SetColors(topPressedColor, bottomPressedColor);
}
}
else if (selected)
{
background.SetColors(topPressedColor, bottomPressedColor);
}
else
{
background.SetColors(topColor, bottomColor);
}
// set the icon image
if (selected && selectedIcon != null)
{
iconImage.Image = Enabled ? selectedIcon : (disabledSelectedIcon ?? selectedIcon);
}
else
{
iconImage.Image = Enabled ? normalIcon : (disabledIcon ?? normalIcon);
}
// show/hide the icon and label
iconImage.Visible = iconImage.Image != null;
titleLabel.Visible = !string.IsNullOrEmpty(titleLabel.Text);
// if there's an icon
if (iconImage.Visible)
{
// if there's a title, position the icon relative to it
if (titleLabel.Visible)
{
int width = titleLabel.Width + iconImage.Width + IconTextPadding;
int height = titleLabel.Height + iconImage.Height + IconTextPadding;
int x = (Width - width) / 2;
int y = (Height - height) / 2;
Point iconLocation = Point.Empty;
Point titleLocation = Point.Empty;
switch (iconAlignment)
{
case FN2DIconAlignment.Left:
iconLocation = new Point(x, (Height - iconImage.Height) / 2);
titleLocation = new Point(x + iconImage.Width + IconTextPadding, (Height - titleLabel.Height) / 2);
break;
case FN2DIconAlignment.Right:
iconLocation = new Point(x + titleLabel.Width + IconTextPadding, (Height - iconImage.Height) / 2);
titleLocation = new Point(x, (Height - titleLabel.Height) / 2);
break;
case FN2DIconAlignment.Above:
iconLocation = new Point((Width - iconImage.Width) / 2, y);
titleLocation = new Point((Width - titleLabel.Width) / 2, y + iconImage.Height + IconTextPadding);
break;
case FN2DIconAlignment.Below:
iconLocation = new Point((Width - iconImage.Width) / 2, y + titleLabel.Height + IconTextPadding);
titleLocation = new Point((Width - titleLabel.Width) / 2, y);
break;
}
iconImage.Location = iconLocation;
titleLabel.Location = titleLocation;
}
// otherwise just center the icon
else
{
iconImage.Location = new Point((Width - iconImage.Width) / 2 + iconOffsets.X, (Height - iconImage.Height) / 2 + iconOffsets.Y);
}
}
// if there's a title, center it
else if (titleLabel.Visible)
{
titleLabel.Location = new Point((Width - titleLabel.Width) / 2 + titleOffsets.X, (Height - titleLabel.Height) / 2 + titleOffsets.Y);
}
}
}
/// <summary>
/// Called when a finger goes down on the control.
/// </summary>
public override void TouchDown(FN2DTouchEventArgs e)
{
Touching = true;
Refresh();
}
/// <summary>
/// Called when a finger goes up on the control.
/// </summary>
public override void TouchUp(FN2DTouchEventArgs e)
{
base.TouchUp(e);
Touching = false;
Refresh();
}
/// <summary>
/// Cancels any touch tracking that is in progress.
/// </summary>
public override void TouchCancel(FN2DTouchEventArgs e)
{
base.TouchCancel(e);
Refresh();
}
/// <summary>
/// Gets or sets the background color.
/// </summary>
public override Color BackgroundColor
{
get { return base.BackgroundColor; }
set
{
TopColor = value;
BottomColor = value;
}
}
/// <summary>
/// Gets or sets the top background color.
/// </summary>
public override Color TopColor
{
get { return topColor; }
set
{
topColor = value;
if (topColor != Color.Transparent)
{
topPressedColor = Lighten(topColor);
topDisabledColor = Gray(topColor);
}
else
{
topPressedColor = Color.Transparent;
topDisabledColor = Color.Transparent;
}
Refresh();
}
}
/// <summary>
/// Gets or sets the bottom background color.
/// </summary>
public override Color BottomColor
{
get { return bottomColor; }
set
{
bottomColor = value;
if (bottomColor != Color.Transparent)
{
bottomPressedColor = Lighten(bottomColor);
bottomDisabledColor = Gray(bottomColor);
}
else
{
bottomPressedColor = Color.Transparent;
bottomDisabledColor = Color.Transparent;
}
Refresh();
}
}
/// <summary>
/// Gets or sets the top color when the button is pressed.
/// </summary>
public Color TopPressedColor
{
get { return topPressedColor; }
set
{
topPressedColor = value;
Refresh();
}
}
/// <summary>
/// Gets or sets the bottom color when the button is pressed.
/// </summary>
public Color BottomPressedColor
{
get { return bottomPressedColor; }
set
{
bottomPressedColor = value;
Refresh();
}
}
/// <summary>
/// Gets or sets the top color when the button is disabled.
/// </summary>
public Color TopDisabledColor
{
get { return topDisabledColor; }
set
{
topDisabledColor = value;
Refresh();
}
}
/// <summary>
/// Gets or sets the bottom color when the button is disabled.
/// </summary>
public Color BottomDisabledColor
{
get { return bottomDisabledColor; }
set
{
bottomDisabledColor = value;
Refresh();
}
}
/// <summary>
/// Sets/gets the selected state.
/// </summary>
public bool Selected
{
get { return selected; }
set
{
selected = value;
Refresh();
}
}
/// <summary>
/// Gets the title label.
/// </summary>
public FN2DLabel Label
{
get { return titleLabel; }
}
/// <summary>
/// Sets/gets the title.
/// </summary>
public string Title
{
get { return (titleLabel != null) ? titleLabel.Text : ""; }
set
{
titleLabel.Text = value;
Refresh();
}
}
/// <summary>
/// Sets/gets the title position offsets.
/// </summary>
public Point TitleOffsets
{
get { return titleOffsets; }
set
{
titleOffsets = value;
Refresh();
}
}
/// <summary>
/// Sets/gets the icon position offsets.
/// </summary>
public Point IconOffsets
{
get { return iconOffsets; }
set
{
iconOffsets = value;
Refresh();
}
}
/// <summary>
/// Sets/gets the icon alignment relative to the button text.
/// </summary>
public FN2DIconAlignment IconAlignment
{
get { return iconAlignment; }
set
{
iconAlignment = value;
Refresh();
}
}
/// <summary>
/// Sets/gets the normal icon image.
/// </summary>
public FN2DBitmap Icon
{
get { return normalIcon; }
set
{
normalIcon = value;
Refresh();
}
}
/// <summary>
/// Sets/gets the disabled icon image.
/// </summary>
public FN2DBitmap DisabledIcon
{
get { return disabledIcon; }
set
{
disabledIcon = value;
Refresh();
}
}
/// <summary>
/// Sets/gets the selected icon image.
/// </summary>
public FN2DBitmap SelectedIcon
{
get { return selectedIcon; }
set
{
selectedIcon = value;
Refresh();
}
}
/// <summary>
/// Sets/gets the disabled selected icon image.
/// </summary>
public FN2DBitmap DisabledSelectedIcon
{
get { return disabledSelectedIcon; }
set
{
disabledSelectedIcon = value;
Refresh();
}
}
/// <summary>
/// Sets the normal and disabled icons.
/// </summary>
/// <param name="icon">Normal icon.</param>
/// <param name="iconDisabled">Normal disabled icon.</param>
public void SetIcons(FN2DBitmap icon, FN2DBitmap iconDisabled)
{
normalIcon = icon;
disabledIcon = iconDisabled;
Refresh();
}
/// <summary>
/// Sets the selected and disabled selected icons.
/// </summary>
/// <param name="iconSelected">Selected icon.</param>
/// <param name="iconSelectedDisabled">Disabled selected icon.</param>
public void SetSelectedIcons(FN2DBitmap iconSelected, FN2DBitmap iconSelectedDisabled)
{
selectedIcon = iconSelected;
disabledSelectedIcon = iconSelectedDisabled;
Refresh();
}
/// <summary>
/// Lightens the specified color.
/// </summary>
/// <param name="color">Color to be lightened.</param>
/// <returns>The lightened color.</returns>
private Color Lighten(Color color)
{
float hue = color.GetHue() / 360;
float saturation = color.GetSaturation();
float luminosity = color.GetBrightness() * 1.3f;
double r = 0, g = 0, b = 0;
if (luminosity != 0)
{
if (saturation == 0)
{
r = g = b = luminosity;
}
else
{
double temp2 = (luminosity < 0.5) ? (luminosity * (1.0 + saturation)) : (luminosity + saturation - (luminosity * saturation));
double temp1 = 2.0 * luminosity - temp2;
r = GetColorComponent(temp1, temp2, hue + 1.0 / 3.0);
g = GetColorComponent(temp1, temp2, hue);
b = GetColorComponent(temp1, temp2, hue - 1.0 / 3.0);
}
}
return Color.FromArgb((byte)(255 * r), (byte)(255 * g), (byte)(255 * b));
}
/// <summary>
/// Gets a color component when lightening a color.
/// </summary>
/// <returns>The color component.</returns>
/// <param name="temp1">Temp1.</param>
/// <param name="temp2">Temp2.</param>
/// <param name="temp3">Temp3.</param>
private static double GetColorComponent(double temp1, double temp2, double temp3)
{
if (temp3 < 0.0)
temp3 += 1.0;
else if (temp3 > 1.0)
temp3 -= 1.0;
if (temp3 < 1.0 / 6.0)
return temp1 + (temp2 - temp1) * 6.0 * temp3;
else if (temp3 < 0.5)
return temp2;
else if (temp3 < 2.0 / 3.0)
return temp1 + ((temp2 - temp1) * ((2.0 / 3.0) - temp3) * 6.0);
else
return temp1;
}
/// <summary>
/// Gets the gray version of the specified color.
/// </summary>
/// <param name="color">Color to be grayed.</param>
/// <returns>The grayed color.</returns>
private Color Gray(Color color)
{
int rgb = ((int)color.R + color.G + color.B) / 3;
return Color.FromArgb(color.A, rgb, rgb, rgb);
}
}
/// <summary>
/// OpenGL 2D icon alignment.
/// </summary>
public enum FN2DIconAlignment
{
Above,
Below,
Left,
Right
}
}
| |
/*
* 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 Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Support;
using Lucene.Net.Util;
using Payload = Lucene.Net.Index.Payload;
using TermPositions = Lucene.Net.Index.TermPositions;
using ArrayUtil = Lucene.Net.Util.ArrayUtil;
using Attribute = Lucene.Net.Util.Attribute;
namespace Lucene.Net.Analysis
{
/// <summary>A Token is an occurrence of a term from the text of a field. It consists of
/// a term's text, the start and end offset of the term in the text of the field,
/// and a type string.
/// <p/>
/// The start and end offsets permit applications to re-associate a token with
/// its source text, e.g., to display highlighted query terms in a document
/// browser, or to show matching text fragments in a <abbr
/// title="KeyWord In Context">KWIC</abbr> display, etc.
/// <p/>
/// The type is a string, assigned by a lexical analyzer
/// (a.k.a. tokenizer), naming the lexical or syntactic class that the token
/// belongs to. For example an end of sentence marker token might be implemented
/// with type "eos". The default token type is "word".
/// <p/>
/// A Token can optionally have metadata (a.k.a. Payload) in the form of a variable
/// length byte array. Use <see cref="TermPositions.PayloadLength" /> and
/// <see cref="TermPositions.GetPayload(byte[], int)" /> to retrieve the payloads from the index.
/// </summary>
/// <summary><br/><br/>
/// </summary>
/// <summary><p/><b>NOTE:</b> As of 2.9, Token implements all <see cref="IAttribute" /> interfaces
/// that are part of core Lucene and can be found in the <see cref="Lucene.Net.Analysis.Tokenattributes"/> namespace.
/// Even though it is not necessary to use Token anymore, with the new TokenStream API it can
/// be used as convenience class that implements all <see cref="IAttribute" />s, which is especially useful
/// to easily switch from the old to the new TokenStream API.
/// <br/><br/>
/// <p/>Tokenizers and TokenFilters should try to re-use a Token instance when
/// possible for best performance, by implementing the
/// <see cref="TokenStream.IncrementToken()" /> API.
/// Failing that, to create a new Token you should first use
/// one of the constructors that starts with null text. To load
/// the token from a char[] use <see cref="SetTermBuffer(char[], int, int)" />.
/// To load from a String use <see cref="SetTermBuffer(String)" /> or <see cref="SetTermBuffer(String, int, int)" />.
/// Alternatively you can get the Token's termBuffer by calling either <see cref="TermBuffer()" />,
/// if you know that your text is shorter than the capacity of the termBuffer
/// or <see cref="ResizeTermBuffer(int)" />, if there is any possibility
/// that you may need to grow the buffer. Fill in the characters of your term into this
/// buffer, with <see cref="string.ToCharArray(int, int)" /> if loading from a string,
/// or with <see cref="Array.Copy(Array, long, Array, long, long)" />, and finally call <see cref="SetTermLength(int)" /> to
/// set the length of the term text. See <a target="_top"
/// href="https://issues.apache.org/jira/browse/LUCENE-969">LUCENE-969</a>
/// for details.<p/>
/// <p/>Typical Token reuse patterns:
/// <list type="bullet">
/// <item> Copying text from a string (type is reset to <see cref="DEFAULT_TYPE" /> if not
/// specified):<br/>
/// <code>
/// return reusableToken.reinit(string, startOffset, endOffset[, type]);
/// </code>
/// </item>
/// <item> Copying some text from a string (type is reset to <see cref="DEFAULT_TYPE" />
/// if not specified):<br/>
/// <code>
/// return reusableToken.reinit(string, 0, string.length(), startOffset, endOffset[, type]);
/// </code>
/// </item>
/// <item> Copying text from char[] buffer (type is reset to <see cref="DEFAULT_TYPE" />
/// if not specified):<br/>
/// <code>
/// return reusableToken.reinit(buffer, 0, buffer.length, startOffset, endOffset[, type]);
/// </code>
/// </item>
/// <item> Copying some text from a char[] buffer (type is reset to
/// <see cref="DEFAULT_TYPE" /> if not specified):<br/>
/// <code>
/// return reusableToken.reinit(buffer, start, end - start, startOffset, endOffset[, type]);
/// </code>
/// </item>
/// <item> Copying from one one Token to another (type is reset to
/// <see cref="DEFAULT_TYPE" /> if not specified):<br/>
/// <code>
/// return reusableToken.reinit(source.termBuffer(), 0, source.termLength(), source.startOffset(), source.endOffset()[, source.type()]);
/// </code>
/// </item>
/// </list>
/// A few things to note:
/// <list type="bullet">
/// <item>clear() initializes all of the fields to default values. This was changed in contrast to Lucene 2.4, but should affect no one.</item>
/// <item>Because <c>TokenStreams</c> can be chained, one cannot assume that the <c>Token's</c> current type is correct.</item>
/// <item>The startOffset and endOffset represent the start and offset in the
/// source text, so be careful in adjusting them.</item>
/// <item>When caching a reusable token, clone it. When injecting a cached token into a stream that can be reset, clone it again.</item>
/// </list>
/// <p/>
/// </summary>
/// <seealso cref="Lucene.Net.Index.Payload">
/// </seealso>
//[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300
public class Token : Attribute, ITermAttribute, ITypeAttribute, IPositionIncrementAttribute, IFlagsAttribute, IOffsetAttribute, IPayloadAttribute
{
public const String DEFAULT_TYPE = "word";
private const int MIN_BUFFER_SIZE = 10;
private char[] termBuffer;
private int termLength;
private int startOffset, endOffset;
private string type = DEFAULT_TYPE;
private int flags;
private Payload payload;
private int positionIncrement = 1;
/// <summary>Constructs a Token will null text. </summary>
public Token()
{
}
/// <summary>Constructs a Token with null text and start & end
/// offsets.
/// </summary>
/// <param name="start">start offset in the source text</param>
/// <param name="end">end offset in the source text</param>
public Token(int start, int end)
{
startOffset = start;
endOffset = end;
}
/// <summary>Constructs a Token with null text and start & end
/// offsets plus the Token type.
/// </summary>
/// <param name="start">start offset in the source text</param>
/// <param name="end">end offset in the source text</param>
/// <param name="typ">the lexical type of this Token</param>
public Token(int start, int end, String typ)
{
startOffset = start;
endOffset = end;
type = typ;
}
/// <summary> Constructs a Token with null text and start & end
/// offsets plus flags. NOTE: flags is EXPERIMENTAL.
/// </summary>
/// <param name="start">start offset in the source text</param>
/// <param name="end">end offset in the source text</param>
/// <param name="flags">The bits to set for this token</param>
public Token(int start, int end, int flags)
{
startOffset = start;
endOffset = end;
this.flags = flags;
}
/// <summary>Constructs a Token with the given term text, and start
/// & end offsets. The type defaults to "word."
/// <b>NOTE:</b> for better indexing speed you should
/// instead use the char[] termBuffer methods to set the
/// term text.
/// </summary>
/// <param name="text">term text</param>
/// <param name="start">start offset</param>
/// <param name="end">end offset</param>
public Token(String text, int start, int end)
{
SetTermBuffer(text);
startOffset = start;
endOffset = end;
}
/// <summary>Constructs a Token with the given text, start and end
/// offsets, & type. <b>NOTE:</b> for better indexing
/// speed you should instead use the char[] termBuffer
/// methods to set the term text.
/// </summary>
/// <param name="text">term text</param>
/// <param name="start">start offset</param>
/// <param name="end">end offset</param>
/// <param name="typ">token type</param>
public Token(System.String text, int start, int end, System.String typ)
{
SetTermBuffer(text);
startOffset = start;
endOffset = end;
type = typ;
}
/// <summary> Constructs a Token with the given text, start and end
/// offsets, & type. <b>NOTE:</b> for better indexing
/// speed you should instead use the char[] termBuffer
/// methods to set the term text.
/// </summary>
/// <param name="text"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="flags">token type bits</param>
public Token(System.String text, int start, int end, int flags)
{
SetTermBuffer(text);
startOffset = start;
endOffset = end;
this.flags = flags;
}
/// <summary> Constructs a Token with the given term buffer (offset
/// & length), start and end
/// offsets
/// </summary>
/// <param name="startTermBuffer"></param>
/// <param name="termBufferOffset"></param>
/// <param name="termBufferLength"></param>
/// <param name="start"></param>
/// <param name="end"></param>
public Token(char[] startTermBuffer, int termBufferOffset, int termBufferLength, int start, int end)
{
SetTermBuffer(startTermBuffer, termBufferOffset, termBufferLength);
startOffset = start;
endOffset = end;
}
/// <summary>Set the position increment. This determines the position of this token
/// relative to the previous Token in a <see cref="TokenStream" />, used in phrase
/// searching.
///
/// <p/>The default value is one.
///
/// <p/>Some common uses for this are:<list>
///
/// <item>Set it to zero to put multiple terms in the same position. This is
/// useful if, e.g., a word has multiple stems. Searches for phrases
/// including either stem will match. In this case, all but the first stem's
/// increment should be set to zero: the increment of the first instance
/// should be one. Repeating a token with an increment of zero can also be
/// used to boost the scores of matches on that token.</item>
///
/// <item>Set it to values greater than one to inhibit exact phrase matches.
/// If, for example, one does not want phrases to match across removed stop
/// words, then one could build a stop word filter that removes stop words and
/// also sets the increment to the number of stop words removed before each
/// non-stop word. Then exact phrase queries will only match when the terms
/// occur with no intervening stop words.</item>
///
/// </list>
/// </summary>
/// <value> the distance from the prior term </value>
/// <seealso cref="Lucene.Net.Index.TermPositions">
/// </seealso>
public virtual int PositionIncrement
{
set
{
if (value < 0)
throw new System.ArgumentException("Increment must be zero or greater: " + value);
this.positionIncrement = value;
}
get { return positionIncrement; }
}
/// <summary>Returns the Token's term text.
///
/// This method has a performance penalty
/// because the text is stored internally in a char[]. If
/// possible, use <see cref="TermBuffer()" /> and <see cref="TermLength()"/>
/// directly instead. If you really need a
/// String, use this method, which is nothing more than
/// a convenience call to <b>new String(token.termBuffer(), 0, token.termLength())</b>
/// </summary>
public string Term
{
get
{
InitTermBuffer();
return new System.String(termBuffer, 0, termLength);
}
}
/// <summary>Copies the contents of buffer, starting at offset for
/// length characters, into the termBuffer array.
/// </summary>
/// <param name="buffer">the buffer to copy</param>
/// <param name="offset">the index in the buffer of the first character to copy</param>
/// <param name="length">the number of characters to copy</param>
public void SetTermBuffer(char[] buffer, int offset, int length)
{
GrowTermBuffer(length);
Array.Copy(buffer, offset, termBuffer, 0, length);
termLength = length;
}
/// <summary>Copies the contents of buffer into the termBuffer array.</summary>
/// <param name="buffer">the buffer to copy
/// </param>
public void SetTermBuffer(System.String buffer)
{
int length = buffer.Length;
GrowTermBuffer(length);
TextSupport.GetCharsFromString(buffer, 0, length, termBuffer, 0);
termLength = length;
}
/// <summary>Copies the contents of buffer, starting at offset and continuing
/// for length characters, into the termBuffer array.
/// </summary>
/// <param name="buffer">the buffer to copy
/// </param>
/// <param name="offset">the index in the buffer of the first character to copy
/// </param>
/// <param name="length">the number of characters to copy
/// </param>
public void SetTermBuffer(System.String buffer, int offset, int length)
{
System.Diagnostics.Debug.Assert(offset <= buffer.Length);
System.Diagnostics.Debug.Assert(offset + length <= buffer.Length);
GrowTermBuffer(length);
TextSupport.GetCharsFromString(buffer, offset, offset + length, termBuffer, 0);
termLength = length;
}
/// <summary>Returns the internal termBuffer character array which
/// you can then directly alter. If the array is too
/// small for your token, use <see cref="ResizeTermBuffer(int)" />
/// to increase it. After
/// altering the buffer be sure to call <see cref="SetTermLength" />
/// to record the number of valid
/// characters that were placed into the termBuffer.
/// </summary>
public char[] TermBuffer()
{
InitTermBuffer();
return termBuffer;
}
/// <summary>Grows the termBuffer to at least size newSize, preserving the
/// existing content. Note: If the next operation is to change
/// the contents of the term buffer use
/// <see cref="SetTermBuffer(char[], int, int)" />,
/// <see cref="SetTermBuffer(String)" />, or
/// <see cref="SetTermBuffer(String, int, int)" />
/// to optimally combine the resize with the setting of the termBuffer.
/// </summary>
/// <param name="newSize">minimum size of the new termBuffer
/// </param>
/// <returns> newly created termBuffer with length >= newSize
/// </returns>
public virtual char[] ResizeTermBuffer(int newSize)
{
if (termBuffer == null)
{
termBuffer = new char[ArrayUtil.GetNextSize(newSize < MIN_BUFFER_SIZE ? MIN_BUFFER_SIZE : newSize)];
}
else
{
if (termBuffer.Length < newSize)
{
// Not big enough; create a new array with slight
// over allocation and preserve content
var newCharBuffer = new char[ArrayUtil.GetNextSize(newSize)];
Array.Copy(termBuffer, 0, newCharBuffer, 0, termBuffer.Length);
termBuffer = newCharBuffer;
}
}
return termBuffer;
}
/// <summary>Allocates a buffer char[] of at least newSize, without preserving the existing content.
/// its always used in places that set the content
/// </summary>
/// <param name="newSize">minimum size of the buffer
/// </param>
private void GrowTermBuffer(int newSize)
{
if (termBuffer == null)
{
// The buffer is always at least MIN_BUFFER_SIZE
termBuffer = new char[ArrayUtil.GetNextSize(newSize < MIN_BUFFER_SIZE?MIN_BUFFER_SIZE:newSize)];
}
else
{
if (termBuffer.Length < newSize)
{
// Not big enough; create a new array with slight
// over allocation:
termBuffer = new char[ArrayUtil.GetNextSize(newSize)];
}
}
}
private void InitTermBuffer()
{
if (termBuffer == null)
{
termBuffer = new char[ArrayUtil.GetNextSize(MIN_BUFFER_SIZE)];
termLength = 0;
}
}
/// <summary>Return number of valid characters (length of the term)
/// in the termBuffer array.
/// </summary>
public int TermLength()
{
InitTermBuffer();
return termLength;
}
/// <summary>Set number of valid characters (length of the term) in
/// the termBuffer array. Use this to truncate the termBuffer
/// or to synchronize with external manipulation of the termBuffer.
/// Note: to grow the size of the array,
/// use <see cref="ResizeTermBuffer(int)" /> first.
/// </summary>
/// <param name="length">the truncated length
/// </param>
public void SetTermLength(int length)
{
InitTermBuffer();
if (length > termBuffer.Length)
throw new System.ArgumentException("length " + length + " exceeds the size of the termBuffer (" + termBuffer.Length + ")");
termLength = length;
}
/// <summary>Gets or sets this Token's starting offset, the position of the first character
/// corresponding to this token in the source text.
/// Note that the difference between endOffset() and startOffset() may not be
/// equal to <see cref="TermLength"/>, as the term text may have been altered by a
/// stemmer or some other filter.
/// </summary>
public virtual int StartOffset
{
get { return startOffset; }
set { this.startOffset = value; }
}
/// <summary>Gets or sets this Token's ending offset, one greater than the position of the
/// last character corresponding to this token in the source text. The length
/// of the token in the source text is (endOffset - startOffset).
/// </summary>
public virtual int EndOffset
{
get { return endOffset; }
set { this.endOffset = value; }
}
/// <summary>Set the starting and ending offset.
/// See StartOffset() and EndOffset()
/// </summary>
public virtual void SetOffset(int startOffset, int endOffset)
{
this.startOffset = startOffset;
this.endOffset = endOffset;
}
/// <summary>Returns this Token's lexical type. Defaults to "word". </summary>
public string Type
{
get { return type; }
set { this.type = value; }
}
/// <summary> EXPERIMENTAL: While we think this is here to stay, we may want to change it to be a long.
/// <p/>
///
/// Get the bitset for any bits that have been set. This is completely distinct from <see cref="Type()" />, although they do share similar purposes.
/// The flags can be used to encode information about the token for use by other <see cref="TokenFilter"/>s.
///
///
/// </summary>
/// <value> The bits </value>
public virtual int Flags
{
get { return flags; }
set { flags = value; }
}
/// <summary> Returns this Token's payload.</summary>
public virtual Payload Payload
{
get { return payload; }
set { payload = value; }
}
public override String ToString()
{
var sb = new System.Text.StringBuilder();
sb.Append('(');
InitTermBuffer();
if (termBuffer == null)
sb.Append("null");
else
sb.Append(termBuffer, 0, termLength);
sb.Append(',').Append(startOffset).Append(',').Append(endOffset);
if (!type.Equals("word"))
sb.Append(",type=").Append(type);
if (positionIncrement != 1)
sb.Append(",posIncr=").Append(positionIncrement);
sb.Append(')');
return sb.ToString();
}
/// <summary>Resets the term text, payload, flags, and positionIncrement,
/// startOffset, endOffset and token type to default.
/// </summary>
public override void Clear()
{
payload = null;
// Leave termBuffer to allow re-use
termLength = 0;
positionIncrement = 1;
flags = 0;
startOffset = endOffset = 0;
type = DEFAULT_TYPE;
}
public override System.Object Clone()
{
var t = (Token) base.Clone();
// Do a deep clone
if (termBuffer != null)
{
t.termBuffer = new char[termBuffer.Length];
termBuffer.CopyTo(t.termBuffer, 0);
}
if (payload != null)
{
t.payload = (Payload) payload.Clone();
}
return t;
}
/// <summary>Makes a clone, but replaces the term buffer &
/// start/end offset in the process. This is more
/// efficient than doing a full clone (and then calling
/// setTermBuffer) because it saves a wasted copy of the old
/// termBuffer.
/// </summary>
public virtual Token Clone(char[] newTermBuffer, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset)
{
var t = new Token(newTermBuffer, newTermOffset, newTermLength, newStartOffset, newEndOffset)
{positionIncrement = positionIncrement, flags = flags, type = type};
if (payload != null)
t.payload = (Payload) payload.Clone();
return t;
}
public override bool Equals(Object obj)
{
if (obj == this)
return true;
var other = obj as Token;
if (other == null)
return false;
InitTermBuffer();
other.InitTermBuffer();
if (termLength == other.termLength && startOffset == other.startOffset && endOffset == other.endOffset &&
flags == other.flags && positionIncrement == other.positionIncrement && SubEqual(type, other.type) &&
SubEqual(payload, other.payload))
{
for (int i = 0; i < termLength; i++)
if (termBuffer[i] != other.termBuffer[i])
return false;
return true;
}
return false;
}
private bool SubEqual(System.Object o1, System.Object o2)
{
if (o1 == null)
return o2 == null;
return o1.Equals(o2);
}
public override int GetHashCode()
{
InitTermBuffer();
int code = termLength;
code = code * 31 + startOffset;
code = code * 31 + endOffset;
code = code * 31 + flags;
code = code * 31 + positionIncrement;
code = code * 31 + type.GetHashCode();
code = (payload == null?code:code * 31 + payload.GetHashCode());
code = code * 31 + ArrayUtil.HashCode(termBuffer, 0, termLength);
return code;
}
// like clear() but doesn't clear termBuffer/text
private void ClearNoTermBuffer()
{
payload = null;
positionIncrement = 1;
flags = 0;
startOffset = endOffset = 0;
type = DEFAULT_TYPE;
}
/// <summary>Shorthand for calling <see cref="Clear" />,
/// <see cref="SetTermBuffer(char[], int, int)" />,
/// <see cref="StartOffset" />,
/// <see cref="EndOffset" />,
/// <see cref="Type" />
/// </summary>
/// <returns> this Token instance
/// </returns>
public virtual Token Reinit(char[] newTermBuffer, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset, System.String newType)
{
ClearNoTermBuffer();
payload = null;
positionIncrement = 1;
SetTermBuffer(newTermBuffer, newTermOffset, newTermLength);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = newType;
return this;
}
/// <summary>Shorthand for calling <see cref="Clear" />,
/// <see cref="SetTermBuffer(char[], int, int)" />,
/// <see cref="StartOffset" />,
/// <see cref="EndOffset" />
/// <see cref="Type" /> on Token.DEFAULT_TYPE
/// </summary>
/// <returns> this Token instance
/// </returns>
public virtual Token Reinit(char[] newTermBuffer, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset)
{
ClearNoTermBuffer();
SetTermBuffer(newTermBuffer, newTermOffset, newTermLength);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = DEFAULT_TYPE;
return this;
}
/// <summary>Shorthand for calling <see cref="Clear" />,
/// <see cref="SetTermBuffer(String)" />,
/// <see cref="StartOffset" />,
/// <see cref="EndOffset" />
/// <see cref="Type" />
/// </summary>
/// <returns> this Token instance
/// </returns>
public virtual Token Reinit(System.String newTerm, int newStartOffset, int newEndOffset, System.String newType)
{
ClearNoTermBuffer();
SetTermBuffer(newTerm);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = newType;
return this;
}
/// <summary>Shorthand for calling <see cref="Clear" />,
/// <see cref="SetTermBuffer(String, int, int)" />,
/// <see cref="StartOffset" />,
/// <see cref="EndOffset" />
/// <see cref="Type" />
/// </summary>
/// <returns> this Token instance
/// </returns>
public virtual Token Reinit(System.String newTerm, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset, System.String newType)
{
ClearNoTermBuffer();
SetTermBuffer(newTerm, newTermOffset, newTermLength);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = newType;
return this;
}
/// <summary>Shorthand for calling <see cref="Clear" />,
/// <see cref="SetTermBuffer(String)" />,
/// <see cref="StartOffset" />,
/// <see cref="EndOffset" />
/// <see cref="Type" /> on Token.DEFAULT_TYPE
/// </summary>
/// <returns> this Token instance
/// </returns>
public virtual Token Reinit(System.String newTerm, int newStartOffset, int newEndOffset)
{
ClearNoTermBuffer();
SetTermBuffer(newTerm);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = DEFAULT_TYPE;
return this;
}
/// <summary>Shorthand for calling <see cref="Clear" />,
/// <see cref="SetTermBuffer(String, int, int)" />,
/// <see cref="StartOffset" />,
/// <see cref="EndOffset" />
/// <see cref="Type" /> on Token.DEFAULT_TYPE
/// </summary>
/// <returns> this Token instance
/// </returns>
public virtual Token Reinit(System.String newTerm, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset)
{
ClearNoTermBuffer();
SetTermBuffer(newTerm, newTermOffset, newTermLength);
startOffset = newStartOffset;
endOffset = newEndOffset;
type = DEFAULT_TYPE;
return this;
}
/// <summary> Copy the prototype token's fields into this one. Note: Payloads are shared.</summary>
/// <param name="prototype">
/// </param>
public virtual void Reinit(Token prototype)
{
prototype.InitTermBuffer();
SetTermBuffer(prototype.termBuffer, 0, prototype.termLength);
positionIncrement = prototype.positionIncrement;
flags = prototype.flags;
startOffset = prototype.startOffset;
endOffset = prototype.endOffset;
type = prototype.type;
payload = prototype.payload;
}
/// <summary> Copy the prototype token's fields into this one, with a different term. Note: Payloads are shared.</summary>
/// <param name="prototype">
/// </param>
/// <param name="newTerm">
/// </param>
public virtual void Reinit(Token prototype, System.String newTerm)
{
SetTermBuffer(newTerm);
positionIncrement = prototype.positionIncrement;
flags = prototype.flags;
startOffset = prototype.startOffset;
endOffset = prototype.endOffset;
type = prototype.type;
payload = prototype.payload;
}
/// <summary> Copy the prototype token's fields into this one, with a different term. Note: Payloads are shared.</summary>
/// <param name="prototype">
/// </param>
/// <param name="newTermBuffer">
/// </param>
/// <param name="offset">
/// </param>
/// <param name="length">
/// </param>
public virtual void Reinit(Token prototype, char[] newTermBuffer, int offset, int length)
{
SetTermBuffer(newTermBuffer, offset, length);
positionIncrement = prototype.positionIncrement;
flags = prototype.flags;
startOffset = prototype.startOffset;
endOffset = prototype.endOffset;
type = prototype.type;
payload = prototype.payload;
}
public override void CopyTo(Attribute target)
{
if (target is Token)
{
var to = (Token) target;
to.Reinit(this);
// reinit shares the payload, so clone it:
if (payload != null)
{
to.payload = (Payload) payload.Clone();
}
}
else
{
InitTermBuffer();
((ITermAttribute) target).SetTermBuffer(termBuffer, 0, termLength);
((IOffsetAttribute) target).SetOffset(startOffset, endOffset);
((IPositionIncrementAttribute) target).PositionIncrement = positionIncrement;
((IPayloadAttribute) target).Payload = (payload == null)?null:(Payload) payload.Clone();
((IFlagsAttribute) target).Flags = flags;
((ITypeAttribute) target).Type = type;
}
}
///<summary>
/// Convenience factory that returns <c>Token</c> as implementation for the basic
/// attributes and return the default impl (with "Impl" appended) for all other
/// attributes.
/// @since 3.0
/// </summary>
public static AttributeSource.AttributeFactory TOKEN_ATTRIBUTE_FACTORY =
new TokenAttributeFactory(AttributeSource.AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY);
/// <summary>
/// <b>Expert</b>: Creates an AttributeFactory returning {@link Token} as instance for the basic attributes
/// and for all other attributes calls the given delegate factory.
/// </summary>
public class TokenAttributeFactory : AttributeSource.AttributeFactory
{
private readonly AttributeSource.AttributeFactory _delegateFactory;
/// <summary>
/// <b>Expert</b>: Creates an AttributeFactory returning {@link Token} as instance for the basic attributes
/// and for all other attributes calls the given delegate factory.
/// </summary>
public TokenAttributeFactory(AttributeSource.AttributeFactory delegateFactory)
{
this._delegateFactory = delegateFactory;
}
public override Attribute CreateAttributeInstance<T>()
{
return typeof(T).IsAssignableFrom(typeof(Token))
? new Token()
: _delegateFactory.CreateAttributeInstance<T>();
}
public override bool Equals(Object other)
{
if (this == other) return true;
var af = other as TokenAttributeFactory;
return af != null && _delegateFactory.Equals(af._delegateFactory);
}
public override int GetHashCode()
{
return _delegateFactory.GetHashCode() ^ 0x0a45aa31;
}
}
}
}
| |
using System;
using System.Threading;
namespace Amib.Threading.Internal
{
#region WorkItemsQueue class
/// <summary>
/// WorkItemsQueue class.
/// </summary>
public class WorkItemsQueue : IDisposable
{
#region Member variables
/// <summary>
/// Waiters queue (implemented as stack).
/// </summary>
private readonly WaiterEntry _headWaiterEntry = new WaiterEntry();
/// <summary>
/// Waiters count
/// </summary>
private int _waitersCount = 0;
/// <summary>
/// Work items queue
/// </summary>
private readonly PriorityQueue _workItems = new PriorityQueue();
/// <summary>
/// Indicate that work items are allowed to be queued
/// </summary>
private bool _isWorkItemsQueueActive = true;
#if (_WINDOWS_CE)
private static LocalDataStoreSlot _waiterEntrySlot = Thread.AllocateDataSlot();
#else
[ThreadStatic]
private static WaiterEntry _waiterEntry;
#endif
/// <summary>
/// Each thread in the thread pool keeps its own waiter entry.
/// </summary>
private static WaiterEntry CurrentWaiterEntry
{
#if (_WINDOWS_CE)
get
{
return Thread.GetData(_waiterEntrySlot) as WaiterEntry;
}
set
{
Thread.SetData(_waiterEntrySlot, value);
}
#else
get
{
return _waiterEntry;
}
set
{
_waiterEntry = value;
}
#endif
}
/// <summary>
/// A flag that indicates if the WorkItemsQueue has been disposed.
/// </summary>
private bool _isDisposed = false;
#endregion
#region Public properties
/// <summary>
/// Returns the current number of work items in the queue
/// </summary>
public int Count
{
get
{
return _workItems.Count;
}
}
/// <summary>
/// Returns the current number of waiters
/// </summary>
public int WaitersCount
{
get
{
return _waitersCount;
}
}
#endregion
#region Public methods
/// <summary>
/// Enqueue a work item to the queue.
/// </summary>
public bool EnqueueWorkItem(WorkItem workItem)
{
// A work item cannot be null, since null is used in the
// WaitForWorkItem() method to indicate timeout or cancel
if (null == workItem)
{
throw new ArgumentNullException("workItem" , "workItem cannot be null");
}
bool enqueue = true;
// First check if there is a waiter waiting for work item. During
// the check, timed out waiters are ignored. If there is no
// waiter then the work item is queued.
lock(this)
{
ValidateNotDisposed();
if (!_isWorkItemsQueueActive)
{
return false;
}
while(_waitersCount > 0)
{
// Dequeue a waiter.
WaiterEntry waiterEntry = PopWaiter();
// Signal the waiter. On success break the loop
if (waiterEntry.Signal(workItem))
{
enqueue = false;
break;
}
}
if (enqueue)
{
// Enqueue the work item
_workItems.Enqueue(workItem);
}
}
return true;
}
/// <summary>
/// Waits for a work item or exits on timeout or cancel
/// </summary>
/// <param name="millisecondsTimeout">Timeout in milliseconds</param>
/// <param name="cancelEvent">Cancel wait handle</param>
/// <returns>Returns true if the resource was granted</returns>
public WorkItem DequeueWorkItem(
int millisecondsTimeout,
WaitHandle cancelEvent)
{
// This method cause the caller to wait for a work item.
// If there is at least one waiting work item then the
// method returns immidiately with it.
//
// If there are no waiting work items then the caller
// is queued between other waiters for a work item to arrive.
//
// If a work item didn't come within millisecondsTimeout or
// the user canceled the wait by signaling the cancelEvent
// then the method returns null to indicate that the caller
// didn't get a work item.
WaiterEntry waiterEntry;
WorkItem workItem = null;
try
{
Monitor.Enter(this);
ValidateNotDisposed();
// If there are waiting work items then take one and return.
if (_workItems.Count > 0)
{
workItem = _workItems.Dequeue() as WorkItem;
return workItem;
}
// No waiting work items ...
// Get the waiter entry for the waiters queue
waiterEntry = GetThreadWaiterEntry();
// Put the waiter with the other waiters
PushWaiter(waiterEntry);
}
finally
{
Monitor.Exit(this);
}
// Prepare array of wait handle for the WaitHandle.WaitAny()
WaitHandle [] waitHandles = new WaitHandle[] {
waiterEntry.WaitHandle,
cancelEvent };
// Wait for an available resource, cancel event, or timeout.
// During the wait we are supposes to exit the synchronization
// domain. (Placing true as the third argument of the WaitAny())
// It just doesn't work, I don't know why, so I have two lock(this)
// statments instead of one.
int index = STPEventWaitHandle.WaitAny(
waitHandles,
millisecondsTimeout,
true);
lock(this)
{
// success is true if it got a work item.
bool success = (0 == index);
// The timeout variable is used only for readability.
// (We treat cancel as timeout)
bool timeout = !success;
// On timeout update the waiterEntry that it is timed out
if (timeout)
{
// The Timeout() fails if the waiter has already been signaled
timeout = waiterEntry.Timeout();
// On timeout remove the waiter from the queue.
// Note that the complexity is O(1).
if(timeout)
{
RemoveWaiter(waiterEntry, false);
}
// Again readability
success = !timeout;
}
// On success return the work item
if (success)
{
workItem = waiterEntry.WorkItem;
if (null == workItem)
{
workItem = _workItems.Dequeue() as WorkItem;
}
}
}
// On failure return null.
return workItem;
}
/// <summary>
/// Cleanup the work items queue, hence no more work
/// items are allowed to be queue
/// </summary>
private void Cleanup()
{
lock(this)
{
// Deactivate only once
if (!_isWorkItemsQueueActive)
{
return;
}
// Don't queue more work items
_isWorkItemsQueueActive = false;
foreach(WorkItem workItem in _workItems)
{
workItem.DisposeOfState();
}
// Clear the work items that are already queued
_workItems.Clear();
// Note:
// I don't iterate over the queue and dispose of work items's states,
// since if a work item has a state object that is still in use in the
// application then I must not dispose it.
// Tell the waiters that they were timed out.
// It won't signal them to exit, but to ignore their
// next work item.
while(_waitersCount > 0)
{
WaiterEntry waiterEntry = PopWaiter();
waiterEntry.Timeout();
}
}
}
public object[] GetStates()
{
lock (this)
{
object[] states = new object[_workItems.Count];
int i = 0;
foreach (WorkItem workItem in _workItems)
{
states[i] = workItem.GetWorkItemResult().State;
++i;
}
return states;
}
}
#endregion
#region Private methods
/// <summary>
/// Returns the WaiterEntry of the current thread
/// </summary>
/// <returns></returns>
/// In order to avoid creation and destuction of WaiterEntry
/// objects each thread has its own WaiterEntry object.
private static WaiterEntry GetThreadWaiterEntry()
{
if (null == CurrentWaiterEntry)
{
CurrentWaiterEntry = new WaiterEntry();
}
CurrentWaiterEntry.Reset();
return CurrentWaiterEntry;
}
#region Waiters stack methods
/// <summary>
/// Push a new waiter into the waiter's stack
/// </summary>
/// <param name="newWaiterEntry">A waiter to put in the stack</param>
public void PushWaiter(WaiterEntry newWaiterEntry)
{
// Remove the waiter if it is already in the stack and
// update waiter's count as needed
RemoveWaiter(newWaiterEntry, false);
// If the stack is empty then newWaiterEntry is the new head of the stack
if (null == _headWaiterEntry._nextWaiterEntry)
{
_headWaiterEntry._nextWaiterEntry = newWaiterEntry;
newWaiterEntry._prevWaiterEntry = _headWaiterEntry;
}
// If the stack is not empty then put newWaiterEntry as the new head
// of the stack.
else
{
// Save the old first waiter entry
WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry;
// Update the links
_headWaiterEntry._nextWaiterEntry = newWaiterEntry;
newWaiterEntry._nextWaiterEntry = oldFirstWaiterEntry;
newWaiterEntry._prevWaiterEntry = _headWaiterEntry;
oldFirstWaiterEntry._prevWaiterEntry = newWaiterEntry;
}
// Increment the number of waiters
++_waitersCount;
}
/// <summary>
/// Pop a waiter from the waiter's stack
/// </summary>
/// <returns>Returns the first waiter in the stack</returns>
private WaiterEntry PopWaiter()
{
// Store the current stack head
WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry;
// Store the new stack head
WaiterEntry newHeadWaiterEntry = oldFirstWaiterEntry._nextWaiterEntry;
// Update the old stack head list links and decrement the number
// waiters.
RemoveWaiter(oldFirstWaiterEntry, true);
// Update the new stack head
_headWaiterEntry._nextWaiterEntry = newHeadWaiterEntry;
if (null != newHeadWaiterEntry)
{
newHeadWaiterEntry._prevWaiterEntry = _headWaiterEntry;
}
// Return the old stack head
return oldFirstWaiterEntry;
}
/// <summary>
/// Remove a waiter from the stack
/// </summary>
/// <param name="waiterEntry">A waiter entry to remove</param>
/// <param name="popDecrement">If true the waiter count is always decremented</param>
private void RemoveWaiter(WaiterEntry waiterEntry, bool popDecrement)
{
// Store the prev entry in the list
WaiterEntry prevWaiterEntry = waiterEntry._prevWaiterEntry;
// Store the next entry in the list
WaiterEntry nextWaiterEntry = waiterEntry._nextWaiterEntry;
// A flag to indicate if we need to decrement the waiters count.
// If we got here from PopWaiter then we must decrement.
// If we got here from PushWaiter then we decrement only if
// the waiter was already in the stack.
bool decrementCounter = popDecrement;
// Null the waiter's entry links
waiterEntry._prevWaiterEntry = null;
waiterEntry._nextWaiterEntry = null;
// If the waiter entry had a prev link then update it.
// It also means that the waiter is already in the list and we
// need to decrement the waiters count.
if (null != prevWaiterEntry)
{
prevWaiterEntry._nextWaiterEntry = nextWaiterEntry;
decrementCounter = true;
}
// If the waiter entry had a next link then update it.
// It also means that the waiter is already in the list and we
// need to decrement the waiters count.
if (null != nextWaiterEntry)
{
nextWaiterEntry._prevWaiterEntry = prevWaiterEntry;
decrementCounter = true;
}
// Decrement the waiters count if needed
if (decrementCounter)
{
--_waitersCount;
}
}
#endregion
#endregion
#region WaiterEntry class
// A waiter entry in the _waiters queue.
public sealed class WaiterEntry : IDisposable
{
#region Member variables
/// <summary>
/// Event to signal the waiter that it got the work item.
/// </summary>
//private AutoResetEvent _waitHandle = new AutoResetEvent(false);
private AutoResetEvent _waitHandle = EventWaitHandleFactory.CreateAutoResetEvent();
/// <summary>
/// Flag to know if this waiter already quited from the queue
/// because of a timeout.
/// </summary>
private bool _isTimedout = false;
/// <summary>
/// Flag to know if the waiter was signaled and got a work item.
/// </summary>
private bool _isSignaled = false;
/// <summary>
/// A work item that passed directly to the waiter withou going
/// through the queue
/// </summary>
private WorkItem _workItem = null;
private bool _isDisposed = false;
// Linked list members
internal WaiterEntry _nextWaiterEntry = null;
internal WaiterEntry _prevWaiterEntry = null;
#endregion
#region Construction
public WaiterEntry()
{
Reset();
}
#endregion
#region Public methods
public WaitHandle WaitHandle
{
get { return _waitHandle; }
}
public WorkItem WorkItem
{
get
{
return _workItem;
}
}
/// <summary>
/// Signal the waiter that it got a work item.
/// </summary>
/// <returns>Return true on success</returns>
/// The method fails if Timeout() preceded its call
public bool Signal(WorkItem workItem)
{
lock(this)
{
if (!_isTimedout)
{
_workItem = workItem;
_isSignaled = true;
_waitHandle.Set();
return true;
}
}
return false;
}
/// <summary>
/// Mark the wait entry that it has been timed out
/// </summary>
/// <returns>Return true on success</returns>
/// The method fails if Signal() preceded its call
public bool Timeout()
{
lock(this)
{
// Time out can happen only if the waiter wasn't marked as
// signaled
if (!_isSignaled)
{
// We don't remove the waiter from the queue, the DequeueWorkItem
// method skips _waiters that were timed out.
_isTimedout = true;
return true;
}
}
return false;
}
/// <summary>
/// Reset the wait entry so it can be used again
/// </summary>
public void Reset()
{
_workItem = null;
_isTimedout = false;
_isSignaled = false;
_waitHandle.Reset();
}
/// <summary>
/// Free resources
/// </summary>
public void Close()
{
if (null != _waitHandle)
{
_waitHandle.Close();
_waitHandle = null;
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
lock (this)
{
if (!_isDisposed)
{
Close();
}
_isDisposed = true;
}
}
#endregion
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (!_isDisposed)
{
Cleanup();
}
_isDisposed = true;
}
private void ValidateNotDisposed()
{
if(_isDisposed)
{
throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown");
}
}
#endregion
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
#pragma warning disable 618 // obsolete types
namespace System.Collections.Tests
{
public class HashtableTests
{
[Fact]
public void Ctor_Empty()
{
var hash = new ComparableHashtable();
VerifyHashtable(hash, null, null);
}
[Fact]
public void Ctor_HashCodeProvider_Comparer()
{
var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash, null, hash.EqualityComparer);
Assert.Same(CaseInsensitiveHashCodeProvider.DefaultInvariant, hash.HashCodeProvider);
Assert.Same(StringComparer.OrdinalIgnoreCase, hash.Comparer);
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void Ctor_HashCodeProvider_Comparer_NullInputs(bool nullProvider, bool nullComparer)
{
var hash = new ComparableHashtable(
nullProvider ? null : CaseInsensitiveHashCodeProvider.DefaultInvariant,
nullComparer ? null : StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash, null, hash.EqualityComparer);
}
[Fact]
public void Ctor_IDictionary()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable());
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable())))));
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2);
VerifyHashtable(hash1, hash2, null);
}
[Fact]
public void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable((IDictionary)null)); // Dictionary is null
}
[Fact]
public void Ctor_IDictionary_HashCodeProvider_Comparer()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable())))), CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash1, hash2, hash1.EqualityComparer);
}
[Fact]
public void Ctor_IDictionary_HashCodeProvider_Comparer_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, CaseInsensitiveHashCodeProvider.Default, StringComparer.OrdinalIgnoreCase)); // Dictionary is null
}
[Fact]
public void Ctor_IEqualityComparer()
{
// Null comparer
var hash = new ComparableHashtable((IEqualityComparer)null);
VerifyHashtable(hash, null, null);
// Custom comparer
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(comparer);
VerifyHashtable(hash, null, comparer);
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
public void Ctor_Int(int capacity)
{
var hash = new ComparableHashtable(capacity);
VerifyHashtable(hash, null, null);
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
public void Ctor_Int_HashCodeProvider_Comparer(int capacity)
{
var hash = new ComparableHashtable(capacity, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash, null, hash.EqualityComparer);
}
[Fact]
public void Ctor_Int_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1)); // Capacity < 0
AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue)); // Capacity / load factor > int.MaxValue
}
[Fact]
public void Ctor_IDictionary_Int()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), 1f, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f,
CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, 1f, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash1, hash2, hash1.EqualityComparer);
}
[Fact]
public void Ctor_IDictionary_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f)); // Dictionary is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f)); // Load factor < 0.1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f)); // Load factor > 1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN)); // Load factor is NaN
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity)); // Load factor is infinity
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity)); // Load factor is infinity
}
[Fact]
public void Ctor_IDictionary_Int_HashCodeProvider_Comparer()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), 1f);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f);
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, 1f);
VerifyHashtable(hash1, hash2, null);
}
[Fact]
public void Ctor_IDictionary_IEqualityComparer()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), null);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), null), null), null), null), null);
Assert.Equal(0, hash1.Count);
// Null comparer
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, null);
VerifyHashtable(hash1, hash2, null);
// Custom comparer
hash2 = Helpers.CreateIntHashtable(100);
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash1 = new ComparableHashtable(hash2, comparer);
VerifyHashtable(hash1, hash2, comparer);
}
[Fact]
public void Ctor_IDictionary_IEqualityComparer_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable((IDictionary)null, null)); // Dictionary is null
}
[Theory]
[InlineData(0, 0.1)]
[InlineData(10, 0.2)]
[InlineData(100, 0.3)]
[InlineData(1000, 1)]
public void Ctor_Int_Int(int capacity, float loadFactor)
{
var hash = new ComparableHashtable(capacity, loadFactor);
VerifyHashtable(hash, null, null);
}
[Theory]
[InlineData(0, 0.1)]
[InlineData(10, 0.2)]
[InlineData(100, 0.3)]
[InlineData(1000, 1)]
public void Ctor_Int_Int_HashCodeProvider_Comparer(int capacity, float loadFactor)
{
var hash = new ComparableHashtable(capacity, loadFactor, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash, null, hash.EqualityComparer);
}
[Fact]
public void Ctor_Int_Int_GenerateNewPrime()
{
// The ctor for Hashtable performs the following calculation:
// rawSize = capacity / (loadFactor * 0.72)
// If rawSize is > 3, then it calls HashHelpers.GetPrime(rawSize) to generate a prime.
// Then, if the rawSize > 7,199,369 (the largest number in a list of known primes), we have to generate a prime programatically
// This test makes sure this works.
int capacity = 8000000;
float loadFactor = 0.1f / 0.72f;
try
{
var hash = new ComparableHashtable(capacity, loadFactor);
}
catch (OutOfMemoryException)
{
// On memory constrained devices, we can get an OutOfMemoryException, which we can safely ignore.
}
}
[Fact]
public void Ctor_Int_Int_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f)); // Capacity < 0
AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, 0.1f)); // Capacity / load factor > int.MaxValue
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f)); // Load factor < 0.1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f)); // Load factor > 1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN)); // Load factor is NaN
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity)); // Load factor is infinity
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity)); // Load factor is infinity
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public void Ctor_Int_IEqualityComparer(int capacity)
{
// Null comparer
var hash = new ComparableHashtable(capacity, null);
VerifyHashtable(hash, null, null);
// Custom comparer
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(capacity, comparer);
VerifyHashtable(hash, null, comparer);
}
[Fact]
public void Ctor_Int_IEqualityComparer_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, null)); // Capacity < 0
AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, null)); // Capacity / load factor > int.MaxValue
}
[Fact]
public void Ctor_IDictionary_Int_IEqualityComparer()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), 1f, null);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(
new Hashtable(new Hashtable(new Hashtable(), 1f, null), 1f, null), 1f, null), 1f, null), 1f, null);
Assert.Equal(0, hash1.Count);
// Null comparer
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, 1f, null);
VerifyHashtable(hash1, hash2, null);
hash2 = Helpers.CreateIntHashtable(100);
// Custom comparer
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash1 = new ComparableHashtable(hash2, 1f, comparer);
VerifyHashtable(hash1, hash2, comparer);
}
[Fact]
public void Ctor_IDictionary_LoadFactor_IEqualityComparer_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f, null)); // Dictionary is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f, null)); // Load factor < 0.1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f, null)); // Load factor > 1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN, null)); // Load factor is NaN
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity, null)); // Load factor is infinity
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity, null)); // Load factor is infinity
}
[Theory]
[InlineData(0, 0.1)]
[InlineData(10, 0.2)]
[InlineData(100, 0.3)]
[InlineData(1000, 1)]
public void Ctor_Int_Int_IEqualityComparer(int capacity, float loadFactor)
{
// Null comparer
var hash = new ComparableHashtable(capacity, loadFactor, null);
VerifyHashtable(hash, null, null);
Assert.Null(hash.EqualityComparer);
// Custom compare
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(capacity, loadFactor, comparer);
VerifyHashtable(hash, null, comparer);
}
[Fact]
public void Ctor_Capacity_LoadFactor_IEqualityComparer_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f, null)); // Capacity < 0
AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, 0.1f, null)); // Capacity / load factor > int.MaxValue
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f, null)); // Load factor < 0.1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f, null)); // Load factor > 1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN, null)); // Load factor is NaN
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity, null)); // Load factor is infinity
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity, null)); // Load factor is infinity
}
[Fact]
public void DebuggerAttribute()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new Hashtable());
var hash = new Hashtable() { { "a", 1 }, { "b", 2 } };
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(hash);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), Hashtable.Synchronized(hash));
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), null);
}
catch (TargetInvocationException ex)
{
threwNull = ex.InnerException is ArgumentNullException;
}
Assert.True(threwNull);
}
[Fact]
public void Add_ReferenceType()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
// Value is a reference
var foo = new Foo();
hash2.Add("Key", foo);
Assert.Equal("Hello World", ((Foo)hash2["Key"]).StringValue);
// Changing original object should change the object stored in the Hashtable
foo.StringValue = "Goodbye";
Assert.Equal("Goodbye", ((Foo)hash2["Key"]).StringValue);
});
}
[Fact]
public void Add_ClearRepeatedly()
{
const int Iterations = 2;
const int Count = 2;
var hash = new Hashtable();
for (int i = 0; i < Iterations; i++)
{
for (int j = 0; j < Count; j++)
{
string key = "Key: i=" + i + ", j=" + j;
string value = "Value: i=" + i + ", j=" + j;
hash.Add(key, value);
}
Assert.Equal(Count, hash.Count);
hash.Clear();
}
}
[Fact]
[OuterLoop]
public void AddRemove_LargeAmountNumbers()
{
// Generate a random 100,000 array of ints as test data
var inputData = new int[100000];
var random = new Random(341553);
for (int i = 0; i < inputData.Length; i++)
{
inputData[i] = random.Next(7500000, int.MaxValue);
}
var hash = new Hashtable();
int count = 0;
foreach (long number in inputData)
{
hash.Add(number, count++);
}
count = 0;
foreach (long number in inputData)
{
Assert.Equal(hash[number], count);
Assert.True(hash.ContainsKey(number));
count++;
}
foreach (long number in inputData)
{
hash.Remove(number);
}
Assert.Equal(0, hash.Count);
}
[Fact]
public void DuplicatedKeysWithInitialCapacity()
{
// Make rehash get called because to many items with duplicated keys have been added to the hashtable
var hash = new Hashtable(200);
const int Iterations = 1600;
for (int i = 0; i < Iterations; i += 2)
{
hash.Add(new BadHashCode(i), i.ToString());
hash.Add(new BadHashCode(i + 1), (i + 1).ToString());
hash.Remove(new BadHashCode(i));
hash.Remove(new BadHashCode(i + 1));
}
for (int i = 0; i < Iterations; i++)
{
hash.Add(i.ToString(), i);
}
for (int i = 0; i < Iterations; i++)
{
Assert.Equal(i, hash[i.ToString()]);
}
}
[Fact]
public void DuplicatedKeysWithDefaultCapacity()
{
// Make rehash get called because to many items with duplicated keys have been added to the hashtable
var hash = new Hashtable();
const int Iterations = 1600;
for (int i = 0; i < Iterations; i += 2)
{
hash.Add(new BadHashCode(i), i.ToString());
hash.Add(new BadHashCode(i + 1), (i + 1).ToString());
hash.Remove(new BadHashCode(i));
hash.Remove(new BadHashCode(i + 1));
}
for (int i = 0; i < Iterations; i++)
{
hash.Add(i.ToString(), i);
}
for (int i = 0; i < Iterations; i++)
{
Assert.Equal(i, hash[i.ToString()]);
}
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public void Clone(int count)
{
Hashtable hash1 = Helpers.CreateStringHashtable(count);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Hashtable clone = (Hashtable)hash2.Clone();
Assert.Equal(hash2.Count, clone.Count);
Assert.Equal(hash2.IsSynchronized, clone.IsSynchronized);
Assert.Equal(hash2.IsFixedSize, clone.IsFixedSize);
Assert.Equal(hash2.IsReadOnly, clone.IsReadOnly);
for (int i = 0; i < clone.Count; i++)
{
string key = "Key_" + i;
string value = "Value_" + i;
Assert.True(clone.ContainsKey(key));
Assert.True(clone.ContainsValue(value));
Assert.Equal(value, clone[key]);
}
});
}
[Fact]
public void Clone_IsShallowCopy()
{
var hash = new Hashtable();
for (int i = 0; i < 10; i++)
{
hash.Add(i, new Foo());
}
Hashtable clone = (Hashtable)hash.Clone();
for (int i = 0; i < clone.Count; i++)
{
Assert.Equal("Hello World", ((Foo)clone[i]).StringValue);
Assert.Same(hash[i], clone[i]);
}
// Change object in original hashtable
((Foo)hash[1]).StringValue = "Goodbye";
Assert.Equal("Goodbye", ((Foo)clone[1]).StringValue);
// Removing an object from the original hashtable doesn't change the clone
hash.Remove(0);
Assert.True(clone.Contains(0));
}
[Fact]
public void Clone_HashtableCastedToInterfaces()
{
// Try to cast the returned object from Clone() to different types
Hashtable hash = Helpers.CreateIntHashtable(100);
ICollection collection = (ICollection)hash.Clone();
Assert.Equal(hash.Count, collection.Count);
IDictionary dictionary = (IDictionary)hash.Clone();
Assert.Equal(hash.Count, dictionary.Count);
}
[Fact]
public void ContainsKey()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < hash2.Count; i++)
{
string key = "Key_" + i;
Assert.True(hash2.ContainsKey(key));
Assert.True(hash2.Contains(key));
}
Assert.False(hash2.ContainsKey("Non Existent Key"));
Assert.False(hash2.Contains("Non Existent Key"));
Assert.False(hash2.ContainsKey(101));
Assert.False(hash2.Contains("Non Existent Key"));
string removedKey = "Key_1";
hash2.Remove(removedKey);
Assert.False(hash2.ContainsKey(removedKey));
Assert.False(hash2.Contains(removedKey));
});
}
[Fact]
public void ContainsKey_EqualObjects()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var foo1 = new Foo() { StringValue = "Goodbye" };
var foo2 = new Foo() { StringValue = "Goodbye" };
hash2.Add(foo1, 101);
Assert.True(hash2.ContainsKey(foo2));
Assert.True(hash2.Contains(foo2));
int i1 = 0x10;
int i2 = 0x100;
long l1 = (((long)i1) << 32) + i2; // Create two longs with same hashcode
long l2 = (((long)i2) << 32) + i1;
hash2.Add(l1, 101);
hash2.Add(l2, 101); // This will cause collision bit of the first entry to be set
Assert.True(hash2.ContainsKey(l1));
Assert.True(hash2.Contains(l1));
hash2.Remove(l1); // Remove the first item
Assert.False(hash2.ContainsKey(l1));
Assert.False(hash2.Contains(l1));
Assert.True(hash2.ContainsKey(l2));
Assert.True(hash2.Contains(l2));
});
}
[Fact]
public void ContainsKey_NullKey_ThrowsArgumentNullException()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => hash2.ContainsKey(null)); // Key is null
AssertExtensions.Throws<ArgumentNullException>("key", () => hash2.Contains(null)); // Key is null
});
}
[Fact]
public void ContainsValue()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < hash2.Count; i++)
{
string value = "Value_" + i;
Assert.True(hash2.ContainsValue(value));
}
Assert.False(hash2.ContainsValue("Non Existent Value"));
Assert.False(hash2.ContainsValue(101));
Assert.False(hash2.ContainsValue(null));
hash2.Add("Key_101", null);
Assert.True(hash2.ContainsValue(null));
string removedKey = "Key_1";
string removedValue = "Value_1";
hash2.Remove(removedKey);
Assert.False(hash2.ContainsValue(removedValue));
});
}
[Fact]
public void ContainsValue_EqualObjects()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var foo1 = new Foo() { StringValue = "Goodbye" };
var foo2 = new Foo() { StringValue = "Goodbye" };
hash2.Add(101, foo1);
Assert.True(hash2.ContainsValue(foo2));
});
}
[Fact]
public void Keys_ModifyingHashtable_ModifiesCollection()
{
Hashtable hash = Helpers.CreateStringHashtable(100);
ICollection keys = hash.Keys;
// Removing a key from the hashtable should update the Keys ICollection.
// This means that the Keys ICollection no longer contains the key.
hash.Remove("Key_0");
IEnumerator enumerator = keys.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.NotEqual("Key_0", enumerator.Current);
}
}
[Fact]
public void Remove_SameHashcode()
{
// We want to add and delete items (with the same hashcode) to the hashtable in such a way that the hashtable
// does not expand but have to tread through collision bit set positions to insert the new elements. We do this
// by creating a default hashtable of size 11 (with the default load factor of 0.72), this should mean that
// the hashtable does not expand as long as we have at most 7 elements at any given time?
var hash = new Hashtable();
var arrList = new ArrayList();
for (int i = 0; i < 7; i++)
{
var hashConfuse = new BadHashCode(i);
arrList.Add(hashConfuse);
hash.Add(hashConfuse, i);
}
var rand = new Random(-55);
int iCount = 7;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 7; j++)
{
Assert.Equal(hash[arrList[j]], ((BadHashCode)arrList[j]).Value);
}
// Delete 3 elements from the hashtable
for (int j = 0; j < 3; j++)
{
int iElement = rand.Next(6);
hash.Remove(arrList[iElement]);
Assert.False(hash.ContainsValue(null));
arrList.RemoveAt(iElement);
int testInt = iCount++;
var hashConfuse = new BadHashCode(testInt);
arrList.Add(hashConfuse);
hash.Add(hashConfuse, testInt);
}
}
}
[Fact]
public void SynchronizedProperties()
{
// Ensure Synchronized correctly reflects a wrapped hashtable
var hash1 = Helpers.CreateStringHashtable(100);
var hash2 = Hashtable.Synchronized(hash1);
Assert.Equal(hash1.Count, hash2.Count);
Assert.Equal(hash1.IsReadOnly, hash2.IsReadOnly);
Assert.Equal(hash1.IsFixedSize, hash2.IsFixedSize);
Assert.True(hash2.IsSynchronized);
Assert.Equal(hash1.SyncRoot, hash2.SyncRoot);
for (int i = 0; i < hash2.Count; i++)
{
Assert.Equal("Value_" + i, hash2["Key_" + i]);
}
}
[Fact]
public void Synchronized_NullTable_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("table", () => Hashtable.Synchronized(null)); // Table is null
}
[Fact]
public void Values_ModifyingHashtable_ModifiesCollection()
{
Hashtable hash = Helpers.CreateStringHashtable(100);
ICollection values = hash.Values;
// Removing a value from the hashtable should update the Values ICollection.
// This means that the Values ICollection no longer contains the value.
hash.Remove("Key_0");
IEnumerator enumerator = values.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.NotEqual("Value_0", enumerator.Current);
}
}
[Fact]
public void HashCodeProvider_Set_ImpactsSearch()
{
var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
hash.Add("test", "test");
// Should be able to find with the same and different casing
Assert.True(hash.ContainsKey("test"));
Assert.True(hash.ContainsKey("TEST"));
// Changing the hash code provider, we shouldn't be able to find either
hash.HashCodeProvider = new FixedHashCodeProvider
{
FixedHashCode = CaseInsensitiveHashCodeProvider.DefaultInvariant.GetHashCode("test") + 1
};
Assert.False(hash.ContainsKey("test"));
Assert.False(hash.ContainsKey("TEST"));
// Changing it back, should be able to find both again
hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
Assert.True(hash.ContainsKey("test"));
Assert.True(hash.ContainsKey("TEST"));
}
[Fact]
public void HashCodeProvider_Comparer_CompatibleGetSet_Success()
{
var hash = new ComparableHashtable();
Assert.Null(hash.HashCodeProvider);
Assert.Null(hash.Comparer);
hash = new ComparableHashtable();
hash.HashCodeProvider = null;
hash.Comparer = null;
hash = new ComparableHashtable();
hash.Comparer = null;
hash.HashCodeProvider = null;
hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
hash.Comparer = StringComparer.OrdinalIgnoreCase;
}
[Fact]
public void HashCodeProvider_Comparer_IncompatibleGetSet_Throws()
{
var hash = new ComparableHashtable(StringComparer.CurrentCulture);
AssertExtensions.Throws<ArgumentException>(null, () => hash.HashCodeProvider);
AssertExtensions.Throws<ArgumentException>(null, () => hash.Comparer);
AssertExtensions.Throws<ArgumentException>(null, () => hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant);
AssertExtensions.Throws<ArgumentException>(null, () => hash.Comparer = StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void Comparer_Set_ImpactsSearch()
{
var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
hash.Add("test", "test");
// Should be able to find with the same and different casing
Assert.True(hash.ContainsKey("test"));
Assert.True(hash.ContainsKey("TEST"));
// Changing the comparer, should only be able to find the matching case
hash.Comparer = StringComparer.Ordinal;
Assert.True(hash.ContainsKey("test"));
Assert.False(hash.ContainsKey("TEST"));
// Changing it back, should be able to find both again
hash.Comparer = StringComparer.OrdinalIgnoreCase;
Assert.True(hash.ContainsKey("test"));
Assert.True(hash.ContainsKey("TEST"));
}
private class FixedHashCodeProvider : IHashCodeProvider
{
public int FixedHashCode;
public int GetHashCode(object obj) => FixedHashCode;
}
private static void VerifyHashtable(ComparableHashtable hash1, Hashtable hash2, IEqualityComparer ikc)
{
if (hash2 == null)
{
Assert.Equal(0, hash1.Count);
}
else
{
// Make sure that construtor imports all keys and values
Assert.Equal(hash2.Count, hash1.Count);
for (int i = 0; i < 100; i++)
{
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
// Make sure the new and old hashtables are not linked
hash2.Clear();
for (int i = 0; i < 100; i++)
{
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
}
Assert.Equal(ikc, hash1.EqualityComparer);
Assert.False(hash1.IsFixedSize);
Assert.False(hash1.IsReadOnly);
Assert.False(hash1.IsSynchronized);
// Make sure we can add to the hashtable
int count = hash1.Count;
for (int i = count; i < count + 100; i++)
{
hash1.Add(i, i);
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
}
private class ComparableHashtable : Hashtable
{
public ComparableHashtable() : base() { }
public ComparableHashtable(int capacity) : base(capacity) { }
public ComparableHashtable(int capacity, float loadFactor) : base(capacity, loadFactor) { }
public ComparableHashtable(int capacity, IHashCodeProvider hcp, IComparer comparer) : base(capacity, hcp, comparer) { }
public ComparableHashtable(int capacity, IEqualityComparer ikc) : base(capacity, ikc) { }
public ComparableHashtable(IHashCodeProvider hcp, IComparer comparer) : base(hcp, comparer) { }
public ComparableHashtable(IEqualityComparer ikc) : base(ikc) { }
public ComparableHashtable(IDictionary d) : base(d) { }
public ComparableHashtable(IDictionary d, float loadFactor) : base(d, loadFactor) { }
public ComparableHashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer) : base(d, hcp, comparer) { }
public ComparableHashtable(IDictionary d, IEqualityComparer ikc) : base(d, ikc) { }
public ComparableHashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : base(d, loadFactor, hcp, comparer) { }
public ComparableHashtable(IDictionary d, float loadFactor, IEqualityComparer ikc) : base(d, loadFactor, ikc) { }
public ComparableHashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : base(capacity, loadFactor, hcp, comparer) { }
public ComparableHashtable(int capacity, float loadFactor, IEqualityComparer ikc) : base(capacity, loadFactor, ikc) { }
public new IEqualityComparer EqualityComparer => base.EqualityComparer;
public IHashCodeProvider HashCodeProvider { get { return hcp; } set { hcp = value; } }
public IComparer Comparer { get { return comparer; } set { comparer = value; } }
}
private class BadHashCode
{
public BadHashCode(int value)
{
Value = value;
}
public int Value { get; private set; }
public override bool Equals(object o)
{
BadHashCode rhValue = o as BadHashCode;
if (rhValue != null)
{
return Value.Equals(rhValue.Value);
}
else
{
throw new ArgumentException("is not BadHashCode type actual " + o.GetType(), nameof(o));
}
}
// Return 0 for everything to force hash collisions.
public override int GetHashCode() => 0;
public override string ToString() => Value.ToString();
}
private class Foo
{
public string StringValue { get; set; } = "Hello World";
public override bool Equals(object obj)
{
Foo foo = obj as Foo;
return foo != null && StringValue == foo.StringValue;
}
public override int GetHashCode() => StringValue.GetHashCode();
}
}
/// <summary>
/// A hashtable can have a race condition:
/// A read operation on hashtable has three steps:
/// (1) calculate the hash and find the slot number.
/// (2) compare the hashcode, if equal, go to step 3. Otherwise end.
/// (3) compare the key, if equal, go to step 4. Otherwise end.
/// (4) return the value contained in the bucket.
/// The problem is that after step 3 and before step 4. A writer can kick in a remove the old item and add a new one
/// in the same bucket. In order to make this happen easily, I created two long with same hashcode.
/// </summary>
public class Hashtable_ItemThreadSafetyTests
{
private object _key1;
private object _key2;
private object _value1 = "value1";
private object _value2 = "value2";
private Hashtable _hash;
private bool _errorOccurred = false;
private bool _timeExpired = false;
private const int MAX_TEST_TIME_MS = 10000; // 10 seconds
[Fact]
[OuterLoop]
public void GetItem_ThreadSafety()
{
int i1 = 0x10;
int i2 = 0x100;
// Setup key1 and key2 so they are different values but have the same hashcode
// To produce a hashcode long XOR's the first 32bits with the last 32 bits
long l1 = (((long)i1) << 32) + i2;
long l2 = (((long)i2) << 32) + i1;
_key1 = l1;
_key2 = l2;
_hash = new Hashtable(3); // Just one item will be in the hashtable at a time
int taskCount = 3;
var readers1 = new Task[taskCount];
var readers2 = new Task[taskCount];
Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = 0; i < readers1.Length; i++)
{
readers1[i] = Task.Run(new Action(ReaderFunction1));
}
for (int i = 0; i < readers2.Length; i++)
{
readers2[i] = Task.Run(new Action(ReaderFunction2));
}
Task writer = Task.Run(new Action(WriterFunction));
var spin = new SpinWait();
while (!_errorOccurred && !_timeExpired)
{
if (MAX_TEST_TIME_MS < stopwatch.ElapsedMilliseconds)
{
_timeExpired = true;
}
spin.SpinOnce();
}
Task.WaitAll(readers1);
Task.WaitAll(readers2);
writer.Wait();
Assert.False(_errorOccurred);
}
private void ReaderFunction1()
{
while (!_timeExpired)
{
object value = _hash[_key1];
if (value != null)
{
Assert.NotEqual(value, _value2);
}
}
}
private void ReaderFunction2()
{
while (!_errorOccurred && !_timeExpired)
{
object value = _hash[_key2];
if (value != null)
{
Assert.NotEqual(value, _value1);
}
}
}
private void WriterFunction()
{
while (!_errorOccurred && !_timeExpired)
{
_hash.Add(_key1, _value1);
_hash.Remove(_key1);
_hash.Add(_key2, _value2);
_hash.Remove(_key2);
}
}
}
public class Hashtable_SynchronizedTests
{
private Hashtable _hash2;
private int _iNumberOfElements = 20;
[Fact]
[OuterLoop]
public void SynchronizedThreadSafety()
{
const int NumberOfWorkers = 3;
// Synchronized returns a hashtable that is thread safe
// We will try to test this by getting a number of threads to write some items
// to a synchronized IList
var hash1 = new Hashtable();
_hash2 = Hashtable.Synchronized(hash1);
var workers = new Task[NumberOfWorkers];
for (int i = 0; i < workers.Length; i++)
{
var name = "Thread worker " + i;
var task = new Action(() => AddElements(name));
workers[i] = Task.Run(task);
}
Task.WaitAll(workers);
// Check time
Assert.Equal(_hash2.Count, _iNumberOfElements * NumberOfWorkers);
for (int i = 0; i < NumberOfWorkers; i++)
{
for (int j = 0; j < _iNumberOfElements; j++)
{
string strValue = "Thread worker " + i + "_" + j;
Assert.True(_hash2.Contains(strValue));
}
}
// We cannot can make an assumption on the order of these items but
// now we are going to remove all of these
workers = new Task[NumberOfWorkers];
for (int i = 0; i < workers.Length; i++)
{
string name = "Thread worker " + i;
var task = new Action(() => RemoveElements(name));
workers[i] = Task.Run(task);
}
Task.WaitAll(workers);
Assert.Equal(0, _hash2.Count);
}
private void AddElements(string strName)
{
for (int i = 0; i < _iNumberOfElements; i++)
{
_hash2.Add(strName + "_" + i, "string_" + i);
}
}
private void RemoveElements(string strName)
{
for (int i = 0; i < _iNumberOfElements; i++)
{
_hash2.Remove(strName + "_" + i);
}
}
}
public class Hashtable_SyncRootTests
{
private Hashtable _hashDaughter;
private Hashtable _hashGrandDaughter;
private const int NumberOfElements = 100;
[Fact]
public void SyncRoot()
{
// Different hashtables have different SyncRoots
var hash1 = new Hashtable();
var hash2 = new Hashtable();
Assert.NotSame(hash1.SyncRoot, hash2.SyncRoot);
Assert.Equal(typeof(Hashtable), hash1.SyncRoot.GetType());
// Cloned hashtables have different SyncRoots
hash1 = new Hashtable();
hash2 = Hashtable.Synchronized(hash1);
Hashtable hash3 = (Hashtable)hash2.Clone();
Assert.NotSame(hash2.SyncRoot, hash3.SyncRoot);
Assert.NotSame(hash1.SyncRoot, hash3.SyncRoot);
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenario we have in mind.
// 1) Create your Down to earth mother Hashtable
// 2) Get a synchronized wrapper from it
// 3) Get a Synchronized wrapper from 2)
// 4) Get a synchronized wrapper of the mother from 1)
// 5) all of these should SyncRoot to the mother earth
var hashMother = new Hashtable();
for (int i = 0; i < NumberOfElements; i++)
{
hashMother.Add("Key_" + i, "Value_" + i);
}
Hashtable hashSon = Hashtable.Synchronized(hashMother);
_hashGrandDaughter = Hashtable.Synchronized(hashSon);
_hashDaughter = Hashtable.Synchronized(hashMother);
Assert.Same(hashSon.SyncRoot, hashMother.SyncRoot);
Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
Assert.Same(_hashGrandDaughter.SyncRoot, hashMother.SyncRoot);
Assert.Same(_hashDaughter.SyncRoot, hashMother.SyncRoot);
Assert.Same(hashSon.SyncRoot, hashMother.SyncRoot);
// We are going to rumble with the Hashtables with some threads
int iNumberOfWorkers = 30;
var workers = new Task[iNumberOfWorkers];
var ts2 = new Action(RemoveElements);
for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2)
{
var name = "Thread_worker_" + iThreads;
var ts1 = new Action(() => AddMoreElements(name));
workers[iThreads] = Task.Run(ts1);
workers[iThreads + 1] = Task.Run(ts2);
}
Task.WaitAll(workers);
// Check:
// Either there should be some elements (the new ones we added and/or the original ones) or none
var hshPossibleValues = new Hashtable();
for (int i = 0; i < NumberOfElements; i++)
{
hshPossibleValues.Add("Key_" + i, "Value_" + i);
}
for (int i = 0; i < iNumberOfWorkers; i++)
{
hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
}
IDictionaryEnumerator idic = hashMother.GetEnumerator();
while (idic.MoveNext())
{
Assert.True(hshPossibleValues.ContainsKey(idic.Key));
Assert.True(hshPossibleValues.ContainsValue(idic.Value));
}
}
private void AddMoreElements(string threadName)
{
_hashGrandDaughter.Add("Key_" + threadName, threadName);
}
private void RemoveElements()
{
_hashDaughter.Clear();
}
}
}
| |
// Copyright 2019 Esri.
//
// 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 Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Linq;
namespace ArcGISRuntimeXamarin.Samples.UpdateAttributes
{
[Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Update attributes (feature service)",
category: "Data",
description: "Update feature attributes in an online feature service.",
instructions: "To change the feature's damage property, tap the feature to select it, and update the damage type using the drop down.",
tags: new[] { "amend", "attribute", "details", "edit", "editing", "information", "value" })]
public class UpdateAttributes : Activity
{
// Hold a reference to the MapView.
private MapView _myMapView;
// URL to the feature service.
private const string FeatureServiceUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0";
// Name of the field that will be updated.
private const string AttributeFieldName = "typdamage";
// Hold a reference to the feature layer.
private FeatureLayer _damageLayer;
// Hold a reference to the selected feature.
private ArcGISFeature _selectedFeature;
// Hold a reference to the domain.
private CodedValueDomain _domain;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Update attributes (feature service)";
CreateLayout();
Initialize();
}
private void Initialize()
{
// Create the map with streets basemap.
_myMapView.Map = new Map(BasemapStyle.ArcGISStreets);
// Create the feature table, referring to the Damage Assessment feature service.
ServiceFeatureTable damageTable = new ServiceFeatureTable(new Uri(FeatureServiceUrl));
// When the table loads, use it to discover the domain of the typdamage field.
damageTable.Loaded += DamageTable_Loaded;
// Create a feature layer to visualize the features in the table.
_damageLayer = new FeatureLayer(damageTable);
// Add the layer to the map.
_myMapView.Map.OperationalLayers.Add(_damageLayer);
// Zoom to the United States.
_myMapView.SetViewpointCenterAsync(new MapPoint(-10800000, 4500000, SpatialReferences.WebMercator), 3e7);
}
private void DamageTable_Loaded(object sender, EventArgs e)
{
// This code needs to work with the UI, so it needs to run on the UI thread.
RunOnUiThread(() =>
{
// Get the relevant field from the table.
ServiceFeatureTable table = (ServiceFeatureTable) sender;
Field typeDamageField = table.Fields.First(field => field.Name == AttributeFieldName);
// Get the domain for the field.
_domain = (CodedValueDomain) typeDamageField.Domain;
// Listen for user taps on the map - this will select the feature.
_myMapView.GeoViewTapped += MapView_Tapped;
});
}
private async void MapView_Tapped(object sender, GeoViewInputEventArgs e)
{
// Clear any existing selection.
_damageLayer.ClearSelection();
// Dismiss any existing callouts.
_myMapView.DismissCallout();
try
{
// Perform an identify to determine if a user tapped on a feature.
IdentifyLayerResult identifyResult = await _myMapView.IdentifyLayerAsync(_damageLayer, e.Position, 8, false);
// Do nothing if there are no results.
if (!identifyResult.GeoElements.Any())
{
return;
}
// Get the tapped feature.
_selectedFeature = (ArcGISFeature)identifyResult.GeoElements.First();
// Select the feature.
_damageLayer.SelectFeature(_selectedFeature);
// Update the UI for the selection.
ShowFeatureOptions();
}
catch (Exception ex)
{
ShowMessage("Error selecting feature.", ex.ToString());
}
}
private void ShowFeatureOptions()
{
// Get the current value.
string currentAttributeValue = _selectedFeature.Attributes[AttributeFieldName].ToString();
// Set up the UI for the callout.
Button changeValueButton = new Button(this);
changeValueButton.Text = $"{currentAttributeValue} - Edit";
changeValueButton.Click += ShowDamageTypeChoices;
// Show the callout.
_myMapView.ShowCalloutAt((MapPoint) _selectedFeature.Geometry, changeValueButton);
}
private void ShowDamageTypeChoices(object sender, EventArgs e)
{
// Create menu to show options.
PopupMenu menu = new PopupMenu(this, (Button) sender);
menu.MenuItemClick += (o, menuArgs) => { UpdateDamageType(menuArgs.Item.ToString()); };
// Create menu options.
foreach (CodedValue codeValue in _domain.CodedValues)
{
menu.Menu.Add(codeValue.Name);
}
// Show menu in the view.
menu.Show();
}
private async void UpdateDamageType(string selectedAttributeValue)
{
try
{
// Load the feature.
await _selectedFeature.LoadAsync();
if (_selectedFeature.Attributes[AttributeFieldName].ToString() == selectedAttributeValue)
{
throw new Exception("Old and new attribute values are the same.");
}
// Update the attribute value.
_selectedFeature.SetAttributeValue(AttributeFieldName, selectedAttributeValue);
// Update the table.
await _selectedFeature.FeatureTable.UpdateFeatureAsync(_selectedFeature);
// Update the service.
ServiceFeatureTable table = (ServiceFeatureTable) _selectedFeature.FeatureTable;
await table.ApplyEditsAsync();
ShowMessage("Success!", $"Edited feature {_selectedFeature.Attributes["objectid"]}");
}
catch (Exception ex)
{
ShowMessage("Failed to edit feature", ex.Message);
}
finally
{
// Clear the selection.
_damageLayer.ClearSelection();
_selectedFeature = null;
// Dismiss any callout.
_myMapView.DismissCallout();
}
}
private void ShowMessage(string title, string message)
{
// Display the message to the user.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetMessage(message).SetTitle(title).Show();
}
private void CreateLayout()
{
// Create a new vertical layout for the app.
var layout = new LinearLayout(this) {Orientation = Orientation.Vertical};
// Create the MapView.
_myMapView = new MapView(this);
// Create the help label.
TextView helpLabel = new TextView(this);
helpLabel.Text = "Tap to select a feature to edit.";
helpLabel.TextAlignment = TextAlignment.Center;
helpLabel.Gravity = GravityFlags.Center;
// Add the help label to the layout.
layout.AddView(helpLabel);
// Add the map view to the layout.
layout.AddView(_myMapView);
// Show the layout in the app.
SetContentView(layout);
}
}
}
| |
#pragma warning disable 1591
using System;
using System.Net;
using DynabicBilling.RestAPI.RestInterfaces;
using DynabicBilling.RestApiDataContract.RestInterfaces;
using DynabicPlatform.Classes;
using DynabicPlatform.Interfaces;
using DynabicPlatform.RestAPI.RestInterfaces;
using DynabicPlatform.Services;
namespace DynabicBilling.Classes
{
/// <summary>
/// This is the primary interface to the DynabicBilling Gateway.
/// </summary>
/// <remarks>
/// This class interacts with:
/// <ul>
/// <li><see cref="SubscriptionService">Subscriptions</see></li>
/// <li><see cref="TransactionService">Transactions</see></li>
/// </ul>
/// </remarks>
/// <example>
/// Quick Start Example:
/// <code>
/// using System;
/// using DynabicBilling;
///
/// namespace DynabicBillingExample
/// {
/// class Program
/// {
/// static void Main(string[] args)
/// {
/// var gateway = new BillingGateway
/// {
/// Environment = Environment.PRODUCTION,
/// PublicKey = "a_public_key",
/// PrivateKey = "a_private_key"
/// };
///
/// var request = new SubscriptionRequest
/// {
/// ProductId = 11,
/// ...
/// CustomerRequest = new CustomerRequest
/// {
/// Name = "John Doe",
/// ...
/// }
/// };
///
/// SubscriptionResponse subscription = gateway.Subscription.Create(request);
///
/// Console.WriteLine(String.Format("Subscription ID: {0}", subscription.Id));
/// Console.WriteLine(String.Format("Status: {0}", subscription.Status));
/// }
/// }
/// }
/// </code>
/// </example>
public class BillingGateway
{
public IDynabicEnvironment Environment
{
get { return Configuration.Environment; }
set { Configuration.Environment = value; }
}
public String PublicKey
{
get { return Configuration.PublicKey; }
set { Configuration.PublicKey = value; }
}
public String PrivateKey
{
get { return Configuration.PrivateKey; }
set { Configuration.PrivateKey = value; }
}
public Configuration Configuration { get; set; }
public BillingGateway()
{
Configuration = new Configuration();
}
public BillingGateway(BillingEnvironment environment, string publicKey, string privateKey)
{
Configuration = new Configuration(environment, publicKey, privateKey);
// Prepare Platform Configuration
PlatformEnvironment platformEnvironment = null;
switch (environment.EnvironmentType)
{
case EnvironmentType.Development:
platformEnvironment = PlatformEnvironment.DEVELOPMENT;
break;
case EnvironmentType.QA:
platformEnvironment = PlatformEnvironment.QA;
break;
case EnvironmentType.Production:
platformEnvironment = PlatformEnvironment.PRODUCTION;
break;
}
_platformConfiguration = new Configuration(platformEnvironment, publicKey, privateKey);
}
public BillingGateway(BillingEnvironment environment, Cookie authenticationCookie)
{
Configuration = new Configuration(environment, authenticationCookie);
// Prepare Platform Configuration
PlatformEnvironment platformEnvironment = null;
switch (environment.EnvironmentType)
{
case EnvironmentType.Development:
platformEnvironment = PlatformEnvironment.DEVELOPMENT;
break;
case EnvironmentType.QA:
platformEnvironment = PlatformEnvironment.QA;
break;
case EnvironmentType.Production:
platformEnvironment = PlatformEnvironment.PRODUCTION;
break;
}
_platformConfiguration = new Configuration(platformEnvironment, authenticationCookie);
}
public virtual CustomerService Customer
{
get { return new CustomerService(new CommunicationLayer(this.Configuration)); }
}
public virtual ISubscriptionsService Subscription
{
get { return new SubscriptionService(new CommunicationLayer(Configuration)); }
}
public virtual ITransactionsService Transaction
{
get { return new TransactionService(new CommunicationLayer(Configuration)); }
}
public virtual IProductFamiliesService ProductFamilies
{
get { return new ProductFamiliesService(new CommunicationLayer(Configuration)); }
}
public virtual IProductsService Products
{
get { return new ProductsService(new CommunicationLayer(Configuration)); }
}
public virtual IReportsService Reports
{
get { return new ReportsService(new CommunicationLayer(Configuration)); }
}
public virtual IStatementsService Statements
{
get { return new StatementsService(new CommunicationLayer(Configuration)); }
}
/// <summary>
/// This method allows you to subscribe for webhooks notifications.
///
/// You should pass in the Webhook URL and Signatyre Key that you defined via Billing Web App (WebhookSettings screen @ dynabic.com/billing/settings/webhooks)
/// and retrieve a WebhooksChannel object.
///
/// The WebhooksChannel object allows you to register for all Dynabic Webhooks and write your own .NET event handlers for them.
///
/// Please refer to the code below for a quickstart example.
/// </summary>
/// <param name="listenUrl">
/// The URL to which to listen for webhook notifications.
/// This should be the Webhook URL defined in the WebhooksSettings screen of the Billing Web App (dynabic.com/billing/settings/webhooks)
/// </param>
/// <param name="signatureKey"></param>
/// <returns></returns>
/// <example>
/// <code>
/// var gateway = new BillingGateway
/// {
/// Environment = BillingEnvironment.QA,
/// PrivateKey = "19c7a0d97d2d4413aba5",
/// PublicKey = "19c7a0d97d2d4413aba5"
/// };
///
/// var channel = gateway.Subscribe("http://localhost/WebhookListener/", "dynabic");
///
/// channel.SignupSuccess += new EventHandler(channel_SignupSuccess);
///
/// [...]
///
/// void channel_SignupSuccess(object sender, SignupEventArgs e)
/// {
/// if (e.Customer == null)
/// {
/// return;
/// }
///
/// Console.WriteLine("Signup successful for customer with e-mail: " + e.Customer.Email);
/// }
///
/// [...]
/// // to unsubscribe, simply call:
/// channel.StopListening();
/// </code>
/// </example>
public WebhooksChannel Subscribe(string listenUrl, string signatureKey)
{
WebhooksChannel channel = new WebhooksChannel(listenUrl, signatureKey)
{
Customers = Customer,
Products = Products,
Subscriptions = Subscription
};
if (!channel.StartListening())
{
channel = null;
}
return channel;
}
#region Platform
private Configuration _platformConfiguration;
public virtual ISitesService Sites
{
get { return new SiteService(new CommunicationLayer(_platformConfiguration)); }
}
public virtual IEventsService Events
{
get { return new EventService(new CommunicationLayer(_platformConfiguration)); }
}
#endregion Platform
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// The mailing address.
/// </summary>
public class PostalAddress_Core : TypeCore, IContactPoint
{
public PostalAddress_Core()
{
this._TypeId = 213;
this._Id = "PostalAddress";
this._Schema_Org_Url = "http://schema.org/PostalAddress";
string label = "";
GetLabel(out label, "PostalAddress", typeof(PostalAddress_Core));
this._Label = label;
this._Ancestors = new int[]{266,138,253,70};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{70};
this._Properties = new int[]{67,108,143,229,48,75,91,196,6,7,8,162,163,215};
}
/// <summary>
/// The country. For example, USA. You can also provide the two-letter <a href=\http://en.wikipedia.org/wiki/ISO_3166-1\ target=\new\>ISO 3166-1 alpha-2 country code</a>.
/// </summary>
private AddressCountry_Core addressCountry;
public AddressCountry_Core AddressCountry
{
get
{
return addressCountry;
}
set
{
addressCountry = value;
SetPropertyInstance(addressCountry);
}
}
/// <summary>
/// The locality. For example, Mountain View.
/// </summary>
private AddressLocality_Core addressLocality;
public AddressLocality_Core AddressLocality
{
get
{
return addressLocality;
}
set
{
addressLocality = value;
SetPropertyInstance(addressLocality);
}
}
/// <summary>
/// The region. For example, CA.
/// </summary>
private AddressRegion_Core addressRegion;
public AddressRegion_Core AddressRegion
{
get
{
return addressRegion;
}
set
{
addressRegion = value;
SetPropertyInstance(addressRegion);
}
}
/// <summary>
/// A person or organization can have different contact points, for different purposes. For example, a sales contact point, a PR contact point and so on. This property is used to specify the kind of contact point.
/// </summary>
private ContactType_Core contactType;
public ContactType_Core ContactType
{
get
{
return contactType;
}
set
{
contactType = value;
SetPropertyInstance(contactType);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The postal code. For example, 94043.
/// </summary>
private PostalCode_Core postalCode;
public PostalCode_Core PostalCode
{
get
{
return postalCode;
}
set
{
postalCode = value;
SetPropertyInstance(postalCode);
}
}
/// <summary>
/// The post offce box number for PO box addresses.
/// </summary>
private PostOfficeBoxNumber_Core postOfficeBoxNumber;
public PostOfficeBoxNumber_Core PostOfficeBoxNumber
{
get
{
return postOfficeBoxNumber;
}
set
{
postOfficeBoxNumber = value;
SetPropertyInstance(postOfficeBoxNumber);
}
}
/// <summary>
/// The street address. For example, 1600 Amphitheatre Pkwy.
/// </summary>
private StreetAddress_Core streetAddress;
public StreetAddress_Core StreetAddress
{
get
{
return streetAddress;
}
set
{
streetAddress = value;
SetPropertyInstance(streetAddress);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.GroupsMigration.v1
{
/// <summary>The GroupsMigration Service.</summary>
public class GroupsMigrationService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public GroupsMigrationService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public GroupsMigrationService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Archive = new ArchiveResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "groupsmigration";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://groupsmigration.googleapis.com/";
#else
"https://groupsmigration.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://groupsmigration.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Groups Migration API.</summary>
public class Scope
{
/// <summary>Upload messages to any Google group in your domain</summary>
public static string AppsGroupsMigration = "https://www.googleapis.com/auth/apps.groups.migration";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Groups Migration API.</summary>
public static class ScopeConstants
{
/// <summary>Upload messages to any Google group in your domain</summary>
public const string AppsGroupsMigration = "https://www.googleapis.com/auth/apps.groups.migration";
}
/// <summary>Gets the Archive resource.</summary>
public virtual ArchiveResource Archive { get; }
}
/// <summary>A base abstract class for GroupsMigration requests.</summary>
public abstract class GroupsMigrationBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new GroupsMigrationBaseServiceRequest instance.</summary>
protected GroupsMigrationBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes GroupsMigration parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "archive" collection of methods.</summary>
public class ArchiveResource
{
private const string Resource = "archive";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ArchiveResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
/// <param name="groupId">The group ID</param>
public virtual InsertRequest Insert(string groupId)
{
return new InsertRequest(service, groupId);
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
public class InsertRequest : GroupsMigrationBaseServiceRequest<Google.Apis.GroupsMigration.v1.Data.Groups>
{
/// <summary>Constructs a new Insert request.</summary>
public InsertRequest(Google.Apis.Services.IClientService service, string groupId) : base(service)
{
GroupId = groupId;
InitParameters();
}
/// <summary>The group ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupId { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "insert";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "groups/v1/groups/{groupId}/archive";
/// <summary>Initializes Insert parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("groupId", new Google.Apis.Discovery.Parameter
{
Name = "groupId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
/// <remarks>
/// Considerations regarding <paramref name="stream"/>:
/// <list type="bullet">
/// <item>
/// <description>
/// If <paramref name="stream"/> is seekable, then the stream position will be reset to <c>0</c> before reading
/// commences. If <paramref name="stream"/> is not seekable, then it will be read from its current position
/// </description>
/// </item>
/// <item>
/// <description>
/// Caller is responsible for maintaining the <paramref name="stream"/> open until the upload is completed
/// </description>
/// </item>
/// <item><description>Caller is responsible for closing the <paramref name="stream"/></description></item>
/// </list>
/// </remarks>
/// <param name="groupId">The group ID</param>
/// <param name="stream">The stream to upload. See remarks for further information.</param>
/// <param name="contentType">The content type of the stream to upload.</param>
public virtual InsertMediaUpload Insert(string groupId, System.IO.Stream stream, string contentType)
{
return new InsertMediaUpload(service, groupId, stream, contentType);
}
/// <summary>Insert media upload which supports resumable upload.</summary>
public class InsertMediaUpload : Google.Apis.Upload.ResumableUpload<string, Google.Apis.GroupsMigration.v1.Data.Groups>
{
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned
/// to a user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>The group ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupId { get; private set; }
/// <summary>Constructs a new Insert media upload instance.</summary>
/// <remarks>
/// Considerations regarding <paramref name="stream"/>:
/// <list type="bullet">
/// <item>
/// <description>
/// If <paramref name="stream"/> is seekable, then the stream position will be reset to <c>0</c> before
/// reading commences. If <paramref name="stream"/> is not seekable, then it will be read from its current
/// position
/// </description>
/// </item>
/// <item>
/// <description>
/// Caller is responsible for maintaining the <paramref name="stream"/> open until the upload is completed
/// </description>
/// </item>
/// <item><description>Caller is responsible for closing the <paramref name="stream"/></description></item>
/// </list>
/// </remarks>
public InsertMediaUpload(Google.Apis.Services.IClientService service, string groupId, System.IO.Stream stream, string contentType)
: base(service, string.Format("/{0}/{1}{2}", "upload", service.BasePath, "groups/v1/groups/{groupId}/archive"), "POST", stream, contentType)
{
GroupId = groupId;
}
}
}
}
namespace Google.Apis.GroupsMigration.v1.Data
{
/// <summary>JSON response template for groups migration API.</summary>
public class Groups : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The kind of insert resource this is.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The status of the insert request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("responseCode")]
public virtual string ResponseCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
/*
* Magix - A Web Application Framework for Humans
* Copyright 2010 - 2014 - thomas@magixilluminate.com
* Magix is licensed as MITx11, see enclosed License.txt File for Details.
*/
using System;
using System.Collections.Generic;
using Magix.Core;
namespace Magix.execute
{
/*
* hyperlisp event support
*/
public class EventCore : ActiveController
{
private static Node _events = new Node();
private static Node _inspect = new Node();
/*
* creates the associations between existing events in the database, and active event references
*/
[ActiveEvent(Name = "magix.core.application-startup")]
public static void magix_core_application_startup(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.execute",
"Magix.execute.hyperlisp.inspect.hl",
"[magix.execute.application-startup-dox].value");
return;
}
Node tmp = new Node();
tmp["prototype"]["type"].Value = "magix.execute.event";
RaiseActiveEvent(
"magix.data.load",
tmp);
if (tmp.Contains("objects"))
{
foreach (Node idx in tmp["objects"])
{
ActiveEvents.Instance.CreateEventMapping(
idx["value"]["event"].Get<string>(),
"magix.execute._active-event-2-code-callback");
if (idx["value"].Contains("remotable") && idx["value"]["remotable"].Get<bool>())
ActiveEvents.Instance.MakeRemotable(idx["value"]["event"].Get<string>());
_events[idx["value"]["event"].Get<string>()].Clear();
_events[idx["value"]["event"].Get<string>()].AddRange(idx["value"]["code"]);
if (idx["value"].ContainsValue("inspect"))
AppendInspect(
true,
_inspect[idx["value"]["event"].Get<string>()],
idx["value"]["inspect"].Get<string>());
}
}
}
/*
* event hyperlisp keyword
*/
[ActiveEvent(Name = "magix.execute.event")]
public static void magix_execute_event(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip) && !ip.Contains("code"))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.execute",
"Magix.execute.hyperlisp.inspect.hl",
"[magix.execute.event-dox].value");
AppendCodeFromResource(
ip,
"Magix.execute",
"Magix.execute.hyperlisp.inspect.hl",
"[magix.execute.event-sample]");
return;
}
Node dp = Dp(e.Params);
if (!ip.ContainsValue("name"))
throw new ArgumentException("you cannot create an event without a [name]");
string activeEvent = Expressions.GetExpressionValue<string>(ip["name"].Get<string>(), dp, ip, false);
if (ip.Contains("code"))
{
CreateActiveEvent(ip, activeEvent, e.Params);
}
else
{
RemoveActiveEvent(ip, activeEvent, e.Params);
}
}
/*
* creates an active event
*/
private static void CreateActiveEvent(Node ip, string activeEvent, Node pars)
{
Node dp = Dp(pars);
bool remotable = ip.Contains("remotable") && ip["remotable"].Get<bool>();
string inspect = Expressions.GetFormattedExpression("inspect", pars, "");
if (!ip.Contains("persist") || ip["persist"].Get<bool>())
{
// removing any previous similar events
DataBaseRemoval.Remove(activeEvent, "magix.execute.event", pars);
Node saveNode = new Node("magix.data.save");
saveNode["id"].Value = Guid.NewGuid().ToString();
saveNode["value"]["event"].Value = activeEvent;
saveNode["value"]["type"].Value = "magix.execute.event";
saveNode["value"]["remotable"].Value = remotable;
if (ip.Contains("inspect"))
saveNode["value"]["inspect"].Value = inspect;
saveNode["value"]["code"].AddRange(ip["code"].Clone());
BypassExecuteActiveEvent(saveNode, pars);
}
ActiveEvents.Instance.CreateEventMapping(
activeEvent,
"magix.execute._active-event-2-code-callback");
if (ip.Contains("remotable"))
{
if (remotable)
ActiveEvents.Instance.MakeRemotable(activeEvent);
else
ActiveEvents.Instance.RemoveRemotable(activeEvent);
}
_events[activeEvent].Clear();
_events[activeEvent].AddRange(ip["code"].Clone());
_inspect[activeEvent].Clear();
if (ip.Contains("inspect"))
_inspect[activeEvent].Value = inspect;
}
/*
* removes an active event
*/
private static void RemoveActiveEvent(Node ip, string activeEvent, Node pars)
{
if (!ip.Contains("persist") || ip["persist"].Get<bool>())
DataBaseRemoval.Remove(activeEvent, "magix.execute.event", pars);
ActiveEvents.Instance.RemoveMapping(activeEvent);
ActiveEvents.Instance.RemoveRemotable(activeEvent);
_events[activeEvent].UnTie();
_inspect[activeEvent].UnTie();
}
/*
* entry point for hyperlisp created active event overrides
*/
[ActiveEvent(Name = "magix.execute._active-event-2-code-callback")]
public static void magix_execute__active_event_2_code_callback(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
if (e.Name == "magix.execute._active-event-2-code-callback")
{
AppendInspectFromResource(
ip["inspect"],
"Magix.execute",
"Magix.execute.hyperlisp.inspect.hl",
"[magix.execute._active-event-2-code-callback-dox].value");
}
else if (_events.Contains(e.Name))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.execute",
"Magix.execute.hyperlisp.inspect.hl",
"[magix.execute._active-event-2-code-callback-dynamic-dox].value");
if (_inspect.ContainsValue(e.Name))
{
ip["inspect"].Value = null; // dropping the default documentation
AppendInspect(ip["inspect"], _inspect[e.Name].Get<string>());
}
foreach (Node idx in _events[e.Name])
{
ip.Add(idx.Clone().UnTie());
}
}
return;
}
Node dp = Dp(e.Params);
Node code = GetEventCode(e.Name);
if (code != null)
{
e.Params["_ip"].Value = code;
if (!e.Params.Contains("_dp") || (ip.Name != null && ip.Name.Contains(".")))
e.Params["_dp"].Value = code;
Node nDp = Dp(e.Params);
if (ip.Count > 0)
nDp["$"].AddRange(ip);
// making sure we're starting with correct namespace
e.Params["_namespaces"].Add(new Node("item", "magix.execute"));
e.Params["_root-only-execution"].UnTie();
try
{
if (e.Params.Contains("_whitelist"))
e.Params["_whitelist"].Name = "_whitelist-old";
RaiseActiveEvent(
"magix.execute",
e.Params);
ip.Clear();
if (nDp.Contains("$") && nDp["$"].Count > 0)
ip.AddRange(nDp["$"]);
if (nDp.ContainsValue("$"))
ip.Value = nDp["$"].Value;
nDp["$"].UnTie();
e.Params["_dp"].Value = dp;
e.Params["_ip"].Value = ip;
}
catch (Exception err)
{
while (err.InnerException != null)
err = err.InnerException;
if (!(err is HyperlispStopException))
throw;
}
finally
{
if (e.Params.Contains("_whitelist-old"))
e.Params["_whitelist-old"].Name = "_whitelist";
if (ip != e.Params)
{
e.Params["_namespaces"][e.Params["_namespaces"].Count - 1].UnTie();
if (e.Params["_namespaces"].Count == 0)
e.Params["_namespaces"].UnTie();
e.Params["_ip"].Value = ip;
e.Params["_dp"].Value = dp;
}
}
}
}
/*
* get active events active event
*/
[ActiveEvent(Name = "magix.execute.list-events")]
public static void magix_execute_list_events(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.execute",
"Magix.execute.hyperlisp.inspect.hl",
"[magix.execute.list-events-dox].value");
AppendCodeFromResource(
ip,
"Magix.execute",
"Magix.execute.hyperlisp.inspect.hl",
"[magix.execute.list-events-sample]");
return;
}
bool open = false;
if (ip.Contains("open"))
open = ip["open"].Get<bool>();
bool all = true;
if (ip.Contains("all"))
all = ip["all"].Get<bool>();
bool remoted = false;
if (ip.Contains("remoted"))
remoted = ip["remoted"].Get<bool>();
bool overridden = false;
if (ip.Contains("overridden"))
overridden = ip["overridden"].Get<bool>();
string beginsWith = null;
if (ip.Contains("begins-with"))
beginsWith = ip["begins-with"].Get<string>();
foreach (string idx in ActiveEvents.Instance.ActiveEventHandlers)
{
if (open && !ActiveEvents.Instance.IsAllowedRemotely(idx))
continue;
if (remoted && string.IsNullOrEmpty(ActiveEvents.Instance.RemotelyOverriddenURL(idx)))
continue;
if (overridden && !ActiveEvents.Instance.IsOverride(idx))
continue;
if (!all && !string.IsNullOrEmpty(beginsWith) && idx.Replace(beginsWith, "").Contains("_"))
continue;
if (!all && idx.StartsWith("magix.test."))
continue;
if (!string.IsNullOrEmpty(beginsWith) && !idx.StartsWith(beginsWith))
continue;
if (string.IsNullOrEmpty(idx))
continue;
ip["events"][idx].Value = null;
string remoteOverride = ActiveEvents.Instance.RemotelyOverriddenURL(idx);
if (!string.IsNullOrEmpty(remoteOverride))
ip["events"][idx]["url"].Value = remoteOverride;
}
ip["events"].Sort(
delegate(Node left, Node right)
{
return left.Name.CompareTo(right.Name);
});
}
/*
* returns stored active event
*/
private static Node GetEventCode(string name)
{
if (_events.Contains(name) && _events[name].Count > 0)
return _events[name].Clone();
else if (_events.Contains(name))
return null;
lock (typeof(EventCore))
{
if (_events.Contains(name) && _events[name].Count > 0)
return _events[name].Clone();
else if (_events.Contains(name))
return null;
else
{
Node evtNode = new Node();
evtNode["prototype"]["type"].Value = "magix.execute.event";
evtNode["prototype"]["event"].Value = name;
RaiseActiveEvent(
"magix.data.load",
evtNode);
if (evtNode.Contains("objects"))
{
_events[name].AddRange(evtNode["objects"][0]["value"]["code"].UnTie());
return _events[name].Clone();
}
_events[name].Value = null;
return null;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.Suggestions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.TableControl;
using Roslyn.Utilities;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Suppression
{
/// <summary>
/// Service to compute and apply bulk suppression fixes.
/// </summary>
[Export(typeof(IVisualStudioSuppressionFixService))]
internal sealed class VisualStudioSuppressionFixService : IVisualStudioSuppressionFixService
{
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly IWpfTableControl _tableControl;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly ExternalErrorDiagnosticUpdateSource _buildErrorDiagnosticService;
private readonly ICodeFixService _codeFixService;
private readonly IFixMultipleOccurrencesService _fixMultipleOccurencesService;
private readonly ICodeActionEditHandlerService _editHandlerService;
private readonly VisualStudioDiagnosticListSuppressionStateService _suppressionStateService;
private readonly IWaitIndicator _waitIndicator;
[ImportingConstructor]
public VisualStudioSuppressionFixService(
SVsServiceProvider serviceProvider,
VisualStudioWorkspaceImpl workspace,
IDiagnosticAnalyzerService diagnosticService,
ExternalErrorDiagnosticUpdateSource buildErrorDiagnosticService,
ICodeFixService codeFixService,
ICodeActionEditHandlerService editHandlerService,
IVisualStudioDiagnosticListSuppressionStateService suppressionStateService,
IWaitIndicator waitIndicator)
{
_workspace = workspace;
_diagnosticService = diagnosticService;
_buildErrorDiagnosticService = buildErrorDiagnosticService;
_codeFixService = codeFixService;
_suppressionStateService = (VisualStudioDiagnosticListSuppressionStateService)suppressionStateService;
_editHandlerService = editHandlerService;
_waitIndicator = waitIndicator;
_fixMultipleOccurencesService = workspace.Services.GetService<IFixMultipleOccurrencesService>();
var errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList;
_tableControl = errorList?.TableControl;
}
public bool AddSuppressions(IVsHierarchy projectHierarchyOpt)
{
if (_tableControl == null)
{
return false;
}
Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt);
// Apply suppressions fix in global suppressions file for non-compiler diagnostics and
// in source only for compiler diagnostics.
var diagnosticsToFix = GetDiagnosticsToFix(shouldFixInProject, selectedEntriesOnly: false, isAddSuppression: true);
if (!ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: false, isAddSuppression: true, isSuppressionInSource: false, onlyCompilerDiagnostics: false, showPreviewChangesDialog: false))
{
return false;
}
return ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: false, isAddSuppression: true, isSuppressionInSource: true, onlyCompilerDiagnostics: true, showPreviewChangesDialog: false);
}
public bool AddSuppressions(bool selectedErrorListEntriesOnly, bool suppressInSource, IVsHierarchy projectHierarchyOpt)
{
if (_tableControl == null)
{
return false;
}
Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt);
return ApplySuppressionFix(shouldFixInProject, selectedErrorListEntriesOnly, isAddSuppression: true, isSuppressionInSource: suppressInSource, onlyCompilerDiagnostics: false, showPreviewChangesDialog: true);
}
public bool RemoveSuppressions(bool selectedErrorListEntriesOnly, IVsHierarchy projectHierarchyOpt)
{
if (_tableControl == null)
{
return false;
}
Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt);
return ApplySuppressionFix(shouldFixInProject, selectedErrorListEntriesOnly, isAddSuppression: false, isSuppressionInSource: false, onlyCompilerDiagnostics: false, showPreviewChangesDialog: true);
}
private static Func<Project, bool> GetShouldFixInProjectDelegate(VisualStudioWorkspaceImpl workspace, IVsHierarchy projectHierarchyOpt)
{
if (projectHierarchyOpt == null)
{
return p => true;
}
else
{
var projectIdsForHierarchy = (workspace.DeferredState?.ProjectTracker.ImmutableProjects ?? ImmutableArray<AbstractProject>.Empty)
.Where(p => p.Language == LanguageNames.CSharp || p.Language == LanguageNames.VisualBasic)
.Where(p => p.Hierarchy == projectHierarchyOpt)
.Select(p => workspace.CurrentSolution.GetProject(p.Id).Id)
.ToImmutableHashSet();
return p => projectIdsForHierarchy.Contains(p.Id);
}
}
private async Task<ImmutableArray<DiagnosticData>> GetAllBuildDiagnosticsAsync(Func<Project, bool> shouldFixInProject, CancellationToken cancellationToken)
{
var builder = ArrayBuilder<DiagnosticData>.GetInstance();
var buildDiagnostics = _buildErrorDiagnosticService.GetBuildErrors().Where(d => d.ProjectId != null && d.Severity != DiagnosticSeverity.Hidden);
var solution = _workspace.CurrentSolution;
foreach (var diagnosticsByProject in buildDiagnostics.GroupBy(d => d.ProjectId))
{
cancellationToken.ThrowIfCancellationRequested();
if (diagnosticsByProject.Key == null)
{
// Diagnostics with no projectId cannot be suppressed.
continue;
}
var project = solution.GetProject(diagnosticsByProject.Key);
if (project != null && shouldFixInProject(project))
{
var diagnosticsByDocument = diagnosticsByProject.GroupBy(d => d.DocumentId);
foreach (var group in diagnosticsByDocument)
{
var documentId = group.Key;
if (documentId == null)
{
// Project diagnostics, just add all of them.
builder.AddRange(group);
continue;
}
// For document diagnostics, build does not have the computed text span info.
// So we explicitly calculate the text span from the source text for the diagnostics.
var document = project.GetDocument(documentId);
if (document != null)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var text = await tree.GetTextAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in group)
{
builder.Add(diagnostic.WithCalculatedSpan(text));
}
}
}
}
}
return builder.ToImmutableAndFree();
}
private static string GetFixTitle(bool isAddSuppression)
{
return isAddSuppression ? ServicesVSResources.Suppress_diagnostics : ServicesVSResources.Remove_suppressions;
}
private static string GetWaitDialogMessage(bool isAddSuppression)
{
return isAddSuppression ? ServicesVSResources.Computing_suppressions_fix : ServicesVSResources.Computing_remove_suppressions_fix;
}
private IEnumerable<DiagnosticData> GetDiagnosticsToFix(Func<Project, bool> shouldFixInProject, bool selectedEntriesOnly, bool isAddSuppression)
{
var diagnosticsToFix = ImmutableHashSet<DiagnosticData>.Empty;
Action<IWaitContext> computeDiagnosticsToFix = context =>
{
var cancellationToken = context.CancellationToken;
// If we are fixing selected diagnostics in error list, then get the diagnostics from error list entry snapshots.
// Otherwise, get all diagnostics from the diagnostic service.
var diagnosticsToFixTask = selectedEntriesOnly ?
_suppressionStateService.GetSelectedItemsAsync(isAddSuppression, cancellationToken) :
GetAllBuildDiagnosticsAsync(shouldFixInProject, cancellationToken);
diagnosticsToFix = diagnosticsToFixTask.WaitAndGetResult(cancellationToken).ToImmutableHashSet();
};
var title = GetFixTitle(isAddSuppression);
var waitDialogMessage = GetWaitDialogMessage(isAddSuppression);
var result = InvokeWithWaitDialog(computeDiagnosticsToFix, title, waitDialogMessage);
// Bail out if the user cancelled.
if (result == WaitIndicatorResult.Canceled)
{
return null;
}
return diagnosticsToFix;
}
private bool ApplySuppressionFix(Func<Project, bool> shouldFixInProject, bool selectedEntriesOnly, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics, bool showPreviewChangesDialog)
{
var diagnosticsToFix = GetDiagnosticsToFix(shouldFixInProject, selectedEntriesOnly, isAddSuppression);
return ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, selectedEntriesOnly, isAddSuppression, isSuppressionInSource, onlyCompilerDiagnostics, showPreviewChangesDialog);
}
private bool ApplySuppressionFix(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics, bool showPreviewChangesDialog)
{
if (diagnosticsToFix == null)
{
return false;
}
diagnosticsToFix = FilterDiagnostics(diagnosticsToFix, isAddSuppression, isSuppressionInSource, onlyCompilerDiagnostics);
if (diagnosticsToFix.IsEmpty())
{
// Nothing to fix.
return true;
}
ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentDiagnosticsToFixMap = null;
ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectDiagnosticsToFixMap = null;
var title = GetFixTitle(isAddSuppression);
var waitDialogMessage = GetWaitDialogMessage(isAddSuppression);
var noDiagnosticsToFix = false;
var cancelled = false;
var newSolution = _workspace.CurrentSolution;
HashSet<string> languages = null;
Action<IWaitContext> computeDiagnosticsAndFix = context =>
{
var cancellationToken = context.CancellationToken;
cancellationToken.ThrowIfCancellationRequested();
documentDiagnosticsToFixMap = GetDocumentDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: filterStaleDiagnostics, cancellationToken: cancellationToken)
.WaitAndGetResult(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
projectDiagnosticsToFixMap = isSuppressionInSource ?
ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty :
GetProjectDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: filterStaleDiagnostics, cancellationToken: cancellationToken)
.WaitAndGetResult(cancellationToken);
if (documentDiagnosticsToFixMap == null ||
projectDiagnosticsToFixMap == null ||
(documentDiagnosticsToFixMap.IsEmpty && projectDiagnosticsToFixMap.IsEmpty))
{
// Nothing to fix.
noDiagnosticsToFix = true;
return;
}
cancellationToken.ThrowIfCancellationRequested();
// Equivalence key determines what fix will be applied.
// Make sure we don't include any specific diagnostic ID, as we want all of the given diagnostics (which can have varied ID) to be fixed.
var equivalenceKey = isAddSuppression ?
(isSuppressionInSource ? FeaturesResources.in_Source : FeaturesResources.in_Suppression_File) :
FeaturesResources.Remove_Suppression;
// We have different suppression fixers for every language.
// So we need to group diagnostics by the containing project language and apply fixes separately.
languages = new HashSet<string>(projectDiagnosticsToFixMap.Keys.Select(p => p.Language).Concat(documentDiagnosticsToFixMap.Select(kvp => kvp.Key.Project.Language)));
foreach (var language in languages)
{
// Use the Fix multiple occurrences service to compute a bulk suppression fix for the specified document and project diagnostics,
// show a preview changes dialog and then apply the fix to the workspace.
cancellationToken.ThrowIfCancellationRequested();
var documentDiagnosticsPerLanguage = GetDocumentDiagnosticsMappedToNewSolution(documentDiagnosticsToFixMap, newSolution, language);
if (!documentDiagnosticsPerLanguage.IsEmpty)
{
var suppressionFixer = GetSuppressionFixer(documentDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService);
if (suppressionFixer != null)
{
var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider();
newSolution = _fixMultipleOccurencesService.GetFix(
documentDiagnosticsPerLanguage,
_workspace,
suppressionFixer,
suppressionFixAllProvider,
equivalenceKey,
title,
waitDialogMessage,
cancellationToken);
if (newSolution == null)
{
// User cancelled or fixer threw an exception, so we just bail out.
cancelled = true;
return;
}
}
}
var projectDiagnosticsPerLanguage = GetProjectDiagnosticsMappedToNewSolution(projectDiagnosticsToFixMap, newSolution, language);
if (!projectDiagnosticsPerLanguage.IsEmpty)
{
var suppressionFixer = GetSuppressionFixer(projectDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService);
if (suppressionFixer != null)
{
var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider();
newSolution = _fixMultipleOccurencesService.GetFix(
projectDiagnosticsPerLanguage,
_workspace,
suppressionFixer,
suppressionFixAllProvider,
equivalenceKey,
title,
waitDialogMessage,
cancellationToken);
if (newSolution == null)
{
// User cancelled or fixer threw an exception, so we just bail out.
cancelled = true;
return;
}
}
}
}
};
var result = InvokeWithWaitDialog(computeDiagnosticsAndFix, title, waitDialogMessage);
// Bail out if the user cancelled.
if (cancelled || result == WaitIndicatorResult.Canceled)
{
return false;
}
else if (noDiagnosticsToFix || newSolution == _workspace.CurrentSolution)
{
// No changes.
return true;
}
if (showPreviewChangesDialog)
{
newSolution = FixAllGetFixesService.PreviewChanges(
_workspace.CurrentSolution,
newSolution,
fixAllPreviewChangesTitle: title,
fixAllTopLevelHeader: title,
languageOpt: languages?.Count == 1 ? languages.Single() : null,
workspace: _workspace);
if (newSolution == null)
{
return false;
}
}
waitDialogMessage = isAddSuppression ? ServicesVSResources.Applying_suppressions_fix : ServicesVSResources.Applying_remove_suppressions_fix;
Action<IWaitContext> applyFix = context =>
{
var operations = ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(newSolution));
var cancellationToken = context.CancellationToken;
_editHandlerService.ApplyAsync(
_workspace,
fromDocument: null,
operations: operations,
title: title,
progressTracker: context.ProgressTracker,
cancellationToken: cancellationToken).Wait(cancellationToken);
};
result = InvokeWithWaitDialog(applyFix, title, waitDialogMessage);
if (result == WaitIndicatorResult.Canceled)
{
return false;
}
// Kick off diagnostic re-analysis for affected projects so that diagnostics gets refreshed.
Task.Run(() =>
{
var reanalyzeDocuments = diagnosticsToFix.Where(d => d.DocumentId != null).Select(d => d.DocumentId).Distinct();
_diagnosticService.Reanalyze(_workspace, documentIds: reanalyzeDocuments, highPriority: true);
});
return true;
}
private static IEnumerable<DiagnosticData> FilterDiagnostics(IEnumerable<DiagnosticData> diagnostics, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics)
{
foreach (var diagnostic in diagnostics)
{
var isCompilerDiagnostic = SuppressionHelpers.IsCompilerDiagnostic(diagnostic);
if (onlyCompilerDiagnostics && !isCompilerDiagnostic)
{
continue;
}
if (isAddSuppression)
{
// Compiler diagnostics can only be suppressed in source.
if (!diagnostic.IsSuppressed &&
(isSuppressionInSource || !isCompilerDiagnostic))
{
yield return diagnostic;
}
}
else if (diagnostic.IsSuppressed)
{
yield return diagnostic;
}
}
}
private WaitIndicatorResult InvokeWithWaitDialog(
Action<IWaitContext> action, string waitDialogTitle, string waitDialogMessage)
{
var cancelled = false;
var result = _waitIndicator.Wait(
waitDialogTitle,
waitDialogMessage,
allowCancel: true,
showProgress: true,
action: waitContext =>
{
try
{
action(waitContext);
}
catch (OperationCanceledException)
{
cancelled = true;
}
});
return cancelled ? WaitIndicatorResult.Canceled : result;
}
private static ImmutableDictionary<Document, ImmutableArray<Diagnostic>> GetDocumentDiagnosticsMappedToNewSolution(ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentDiagnosticsToFixMap, Solution newSolution, string language)
{
ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Builder builder = null;
foreach (var kvp in documentDiagnosticsToFixMap)
{
if (kvp.Key.Project.Language != language)
{
continue;
}
var document = newSolution.GetDocument(kvp.Key.Id);
if (document != null)
{
builder = builder ?? ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>();
builder.Add(document, kvp.Value);
}
}
return builder != null ? builder.ToImmutable() : ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty;
}
private static ImmutableDictionary<Project, ImmutableArray<Diagnostic>> GetProjectDiagnosticsMappedToNewSolution(ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectDiagnosticsToFixMap, Solution newSolution, string language)
{
ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Builder projectDiagsBuilder = null;
foreach (var kvp in projectDiagnosticsToFixMap)
{
if (kvp.Key.Language != language)
{
continue;
}
var project = newSolution.GetProject(kvp.Key.Id);
if (project != null)
{
projectDiagsBuilder = projectDiagsBuilder ?? ImmutableDictionary.CreateBuilder<Project, ImmutableArray<Diagnostic>>();
projectDiagsBuilder.Add(project, kvp.Value);
}
}
return projectDiagsBuilder != null ? projectDiagsBuilder.ToImmutable() : ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty;
}
private static CodeFixProvider GetSuppressionFixer(IEnumerable<Diagnostic> diagnostics, string language, ICodeFixService codeFixService)
{
// Fetch the suppression fixer to apply the fix.
return codeFixService.GetSuppressionFixer(language, diagnostics.Select(d => d.Id));
}
private async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, CancellationToken cancellationToken)
{
Func<DiagnosticData, bool> isDocumentDiagnostic = d => d.DataLocation != null && d.HasTextSpan;
var builder = ImmutableDictionary.CreateBuilder<DocumentId, List<DiagnosticData>>();
foreach (var diagnosticData in diagnosticsToFix.Where(isDocumentDiagnostic))
{
if (!builder.TryGetValue(diagnosticData.DocumentId, out var diagnosticsPerDocument))
{
diagnosticsPerDocument = new List<DiagnosticData>();
builder[diagnosticData.DocumentId] = diagnosticsPerDocument;
}
diagnosticsPerDocument.Add(diagnosticData);
}
if (builder.Count == 0)
{
return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty;
}
var finalBuilder = ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>();
var latestDocumentDiagnosticsMapOpt = filterStaleDiagnostics ? new Dictionary<DocumentId, ImmutableHashSet<DiagnosticData>>() : null;
foreach (var group in builder.GroupBy(kvp => kvp.Key.ProjectId))
{
var projectId = group.Key;
var project = _workspace.CurrentSolution.GetProject(projectId);
if (project == null || !shouldFixInProject(project))
{
continue;
}
if (filterStaleDiagnostics)
{
var uniqueDiagnosticIds = group.SelectMany(kvp => kvp.Value.Select(d => d.Id)).ToImmutableHashSet();
var latestProjectDiagnostics = (await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: uniqueDiagnosticIds, includeSuppressedDiagnostics: true, cancellationToken: cancellationToken)
.ConfigureAwait(false)).Where(isDocumentDiagnostic);
latestDocumentDiagnosticsMapOpt.Clear();
foreach (var kvp in latestProjectDiagnostics.Where(d => d.DocumentId != null).GroupBy(d => d.DocumentId))
{
latestDocumentDiagnosticsMapOpt.Add(kvp.Key, kvp.ToImmutableHashSet());
}
}
foreach (var documentDiagnostics in group)
{
var document = project.GetDocument(documentDiagnostics.Key);
if (document == null)
{
continue;
}
IEnumerable<DiagnosticData> documentDiagnosticsToFix;
if (filterStaleDiagnostics)
{
if (!latestDocumentDiagnosticsMapOpt.TryGetValue(document.Id, out var latestDocumentDiagnostics))
{
// Ignore stale diagnostics in error list.
latestDocumentDiagnostics = ImmutableHashSet<DiagnosticData>.Empty;
}
// Filter out stale diagnostics in error list.
documentDiagnosticsToFix = documentDiagnostics.Value.Where(d => latestDocumentDiagnostics.Contains(d) || SuppressionHelpers.IsSynthesizedExternalSourceDiagnostic(d));
}
else
{
documentDiagnosticsToFix = documentDiagnostics.Value;
}
if (documentDiagnosticsToFix.Any())
{
var diagnostics = await documentDiagnosticsToFix.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
finalBuilder.Add(document, diagnostics);
}
}
}
return finalBuilder.ToImmutableDictionary();
}
private async Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, CancellationToken cancellationToken)
{
Func<DiagnosticData, bool> isProjectDiagnostic = d => d.DataLocation == null && d.ProjectId != null;
var builder = ImmutableDictionary.CreateBuilder<ProjectId, List<DiagnosticData>>();
foreach (var diagnosticData in diagnosticsToFix.Where(isProjectDiagnostic))
{
if (!builder.TryGetValue(diagnosticData.ProjectId, out var diagnosticsPerProject))
{
diagnosticsPerProject = new List<DiagnosticData>();
builder[diagnosticData.ProjectId] = diagnosticsPerProject;
}
diagnosticsPerProject.Add(diagnosticData);
}
if (builder.Count == 0)
{
return ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty;
}
var finalBuilder = ImmutableDictionary.CreateBuilder<Project, ImmutableArray<Diagnostic>>();
var latestDiagnosticsToFixOpt = filterStaleDiagnostics ? new HashSet<DiagnosticData>() : null;
foreach (var kvp in builder)
{
var projectId = kvp.Key;
var project = _workspace.CurrentSolution.GetProject(projectId);
if (project == null || !shouldFixInProject(project))
{
continue;
}
var diagnostics = kvp.Value;
IEnumerable<DiagnosticData> projectDiagnosticsToFix;
if (filterStaleDiagnostics)
{
var uniqueDiagnosticIds = diagnostics.Select(d => d.Id).ToImmutableHashSet();
var latestDiagnosticsFromDiagnosticService = (await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: uniqueDiagnosticIds, includeSuppressedDiagnostics: true, cancellationToken: cancellationToken)
.ConfigureAwait(false));
latestDiagnosticsToFixOpt.Clear();
latestDiagnosticsToFixOpt.AddRange(latestDiagnosticsFromDiagnosticService.Where(isProjectDiagnostic));
// Filter out stale diagnostics in error list.
projectDiagnosticsToFix = diagnostics.Where(d => latestDiagnosticsFromDiagnosticService.Contains(d) || SuppressionHelpers.IsSynthesizedExternalSourceDiagnostic(d));
}
else
{
projectDiagnosticsToFix = diagnostics;
}
if (projectDiagnosticsToFix.Any())
{
var projectDiagnostics = await projectDiagnosticsToFix.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
finalBuilder.Add(project, projectDiagnostics);
}
}
return finalBuilder.ToImmutableDictionary();
}
}
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using OpenKh.Kh2;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OpenKh.Tools.Kh2MapStudio.Models
{
class CollisionModel : IDisposable
{
private static readonly Color[] ColorPalette = Enumerable
.Range(0, 40)
.Select(x => FromHue(x * 78.75f))
.ToArray();
private static Color FromHue(float src_h)
{
float h = src_h * 2;
int hi = (int)(h / 60.0f) % 6;
float f = (h / 60.0f) - hi;
float q = 1.0f - f;
return hi switch
{
1 => new Color(q, 1f, 0f),
2 => new Color(0f, 1f, f),
3 => new Color(0f, q, 1f),
4 => new Color(f, 0f, 1f),
5 => new Color(1f, 0f, q),
_ => new Color(1f, f, 0f),
};
}
private VertexBuffer _vertexBuffer;
public CollisionModel(Coct coct)
{
Coct = coct;
}
public Coct Coct { get; }
public Assimp.Scene Scene => GetScene(Coct);
public bool IsVisible { get; set; }
public void Dispose()
{
_vertexBuffer?.Dispose();
}
public void Draw(GraphicsDevice graphics)
{
if (!IsVisible)
return;
_vertexBuffer?.Dispose();
_vertexBuffer = null;
if (_vertexBuffer == null)
_vertexBuffer = CreateVertexBufferForCollision(graphics, Coct);
graphics.SetVertexBuffer(_vertexBuffer);
graphics.DrawPrimitives(PrimitiveType.TriangleList, 0, _vertexBuffer.VertexCount);
graphics.SetVertexBuffer(null);
}
private static VertexBuffer CreateVertexBufferForCollision(GraphicsDevice graphics, Coct rawCoct)
{
var vb = new VertexBuffer(
graphics,
VertexPositionColorTexture.VertexDeclaration,
GetVertices(rawCoct).Count,
BufferUsage.WriteOnly);
vb.SetData(GetVertices(rawCoct).ToArray());
return vb;
}
private static Assimp.Scene GetScene(Coct coct)
{
var color = new Color(1f, 1f, 1f, 1f);
var scene = new Assimp.Scene();
scene.RootNode = new Assimp.Node("root");
for (int i = 0; i < coct.Nodes.Count; i++)
{
var j = 0;
var meshGroup = coct.Nodes[i];
foreach (var mesh in meshGroup.Meshes)
{
var faceIndex = 0;
var sceneMesh = new Assimp.Mesh($"Mesh{i}_{j}", Assimp.PrimitiveType.Triangle);
foreach (var item in mesh.Collisions)
{
var v1 = coct.VertexList[item.Vertex1];
var v2 = coct.VertexList[item.Vertex2];
var v3 = coct.VertexList[item.Vertex3];
List<VertexPositionColorTexture> vertices;
if (item.Vertex4 >= 0)
{
var v4 = coct.VertexList[item.Vertex4];
vertices = GenerateVertex(
color,
v1.X, v1.Y, v1.Z,
v2.X, v2.Y, v2.Z,
v3.X, v3.Y, v3.Z,
v1.X, v1.Y, v1.Z,
v3.X, v3.Y, v3.Z,
v4.X, v4.Y, v4.Z).ToList();
sceneMesh.Faces.Add(new Assimp.Face(new int[]
{
faceIndex++, faceIndex++, faceIndex++,
faceIndex++, faceIndex++, faceIndex++
}));
}
else
{
vertices = GenerateVertex(
color,
v1.X, v1.Y, v1.Z,
v2.X, v2.Y, v2.Z,
v3.X, v3.Y, v3.Z).ToList();
sceneMesh.Faces.Add(new Assimp.Face(new int[]
{
faceIndex++, faceIndex++, faceIndex++
}));
}
sceneMesh.Vertices.AddRange(vertices
.Select(x => new Assimp.Vector3D
{
X = x.Position.X,
Y = x.Position.Y,
Z = x.Position.Z,
}));
}
j++;
scene.Meshes.Add(sceneMesh);
}
}
scene.RootNode.MeshIndices.AddRange(Enumerable.Range(0, scene.MeshCount));
return scene;
}
private static List<VertexPositionColorTexture> GetVertices(Coct coct)
{
var vertices = new List<VertexPositionColorTexture>();
for (int i1 = 0; i1 < coct.Nodes.Count; i1++)
{
var meshGroup = coct.Nodes[i1];
foreach (var mesh in meshGroup.Meshes)
{
foreach (var item in mesh.Collisions)
{
var color = ColorPalette[(int)Math.Abs((item.Plane.D * ColorPalette.Length)) % ColorPalette.Length];
var v1 = coct.VertexList[item.Vertex1];
var v2 = coct.VertexList[item.Vertex2];
var v3 = coct.VertexList[item.Vertex3];
if (item.Vertex4 >= 0)
{
var v4 = coct.VertexList[item.Vertex4];
vertices.AddRange(GenerateVertex(
color,
v1.X, v1.Y, v1.Z,
v2.X, v2.Y, v2.Z,
v3.X, v3.Y, v3.Z,
v1.X, v1.Y, v1.Z,
v3.X, v3.Y, v3.Z,
v4.X, v4.Y, v4.Z));
}
else
{
vertices.AddRange(GenerateVertex(
color,
v1.X, v1.Y, v1.Z,
v2.X, v2.Y, v2.Z,
v3.X, v3.Y, v3.Z));
}
}
}
}
return vertices;
}
private static IEnumerable<VertexPositionColorTexture> GenerateVertex(Color color, params float[] n)
{
for (var i = 0; i < n.Length - 2; i += 3)
{
yield return new VertexPositionColorTexture
{
Position = new Vector3 { X = n[i], Y = -n[i + 1], Z = -n[i + 2] },
Color = color
};
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Orleans.Runtime.Configuration;
#pragma warning disable CS0618 // Type or member is obsolete
namespace Orleans.Runtime.Host
{
/// <summary>
/// Utility class for initializing an Orleans client running inside Azure.
/// </summary>
public static class AzureClient
{
private static readonly IServiceRuntimeWrapper serviceRuntimeWrapper = new ServiceRuntimeWrapper(AzureSilo.CreateDefaultLoggerFactory("AzureClient.log"));
/// <summary>Number of retry attempts to make when searching for gateway silos to connect to.</summary>
public static readonly int MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
/// <summary>Amount of time to pause before each retry attempt.</summary>
public static readonly TimeSpan StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
/// <summary> delegate to configure logging, default to none logger configured </summary>
public static Action<ILoggingBuilder> ConfigureLoggingDelegate { get; set; } = builder => { };
/// <summary>
/// Whether the Orleans Azure client runtime has already been initialized
/// </summary>
/// <returns><c>true</c> if client runtime is already initialized</returns>
public static bool IsInitialized { get { return GrainClient.IsInitialized; } }
/// <summary>
/// Initialise the Orleans client runtime in this Azure process
/// </summary>
public static void Initialize()
{
InitializeImpl_FromFile(null);
}
/// <summary>
/// Initialise the Orleans client runtime in this Azure process
/// </summary>
/// <param name="orleansClientConfigFile">Location of the Orleans client config file to use for base config settings</param>
/// <remarks>Any silo gateway address specified in the config file is ignored, and gateway endpoint info is read from the silo instance table in Azure storage instead.</remarks>
public static void Initialize(FileInfo orleansClientConfigFile)
{
InitializeImpl_FromFile(orleansClientConfigFile);
}
/// <summary>
/// Initialise the Orleans client runtime in this Azure process
/// </summary>
/// <param name="clientConfigFilePath">Location of the Orleans client config file to use for base config settings</param>
/// <remarks>Any silo gateway address specified in the config file is ignored, and gateway endpoint info is read from the silo instance table in Azure storage instead.</remarks>
public static void Initialize(string clientConfigFilePath)
{
InitializeImpl_FromFile(new FileInfo(clientConfigFilePath));
}
/// <summary>
/// Initializes the Orleans client runtime in this Azure process from the provided client configuration object.
/// If the configuration object is null, the initialization fails.
/// </summary>
/// <param name="config">A ClientConfiguration object.</param>
public static void Initialize(ClientConfiguration config)
{
InitializeImpl_FromConfig(config);
}
/// <summary>
/// Uninitializes the Orleans client runtime in this Azure process.
/// </summary>
public static void Uninitialize()
{
if (!GrainClient.IsInitialized) return;
Trace.TraceInformation("Uninitializing connection to Orleans gateway silo.");
GrainClient.Uninitialize();
}
/// <summary>
/// Returns default client configuration object for passing to AzureClient.
/// </summary>
/// <returns></returns>
public static ClientConfiguration DefaultConfiguration()
{
var config = new ClientConfiguration
{
GatewayProvider = ClientConfiguration.GatewayProviderType.AzureTable,
ClusterId = GetDeploymentId(),
DataConnectionString = GetDataConnectionString(),
};
return config;
}
#region Internal implementation of client initialization processing
private static void InitializeImpl_FromFile(FileInfo configFile)
{
if (GrainClient.IsInitialized)
{
Trace.TraceInformation("Connection to Orleans gateway silo already initialized.");
return;
}
ClientConfiguration config;
try
{
if (configFile == null)
{
Trace.TraceInformation("Looking for standard Orleans client config file");
config = ClientConfiguration.StandardLoad();
}
else
{
var configFileLocation = configFile.FullName;
Trace.TraceInformation("Loading Orleans client config file {0}", configFileLocation);
config = ClientConfiguration.LoadFromFile(configFileLocation);
}
}
catch (Exception ex)
{
var msg = String.Format("Error loading Orleans client configuration file {0} {1} -- unable to continue. {2}", configFile, ex.Message, LogFormatter.PrintException(ex));
Trace.TraceError(msg);
throw new AggregateException(msg, ex);
}
Trace.TraceInformation("Overriding Orleans client config from Azure runtime environment.");
try
{
config.ClusterId = GetDeploymentId();
config.DataConnectionString = GetDataConnectionString();
config.GatewayProvider = ClientConfiguration.GatewayProviderType.AzureTable;
}
catch (Exception ex)
{
var msg = string.Format("ERROR: No AzureClient role setting value '{0}' specified for this role -- unable to continue", AzureConstants.DataConnectionConfigurationSettingName);
Trace.TraceError(msg);
throw new AggregateException(msg, ex);
}
InitializeImpl_FromConfig(config);
}
internal static string GetDeploymentId()
{
return GrainClient.TestOnlyNoConnect ? "FakeDeploymentId" : serviceRuntimeWrapper.DeploymentId;
}
internal static string GetDataConnectionString()
{
return GrainClient.TestOnlyNoConnect
? "FakeConnectionString"
: serviceRuntimeWrapper.GetConfigurationSettingValue(AzureConstants.DataConnectionConfigurationSettingName);
}
private static void InitializeImpl_FromConfig(ClientConfiguration config)
{
if (GrainClient.IsInitialized)
{
Trace.TraceInformation("Connection to Orleans gateway silo already initialized.");
return;
}
//// Find endpoint info for the gateway to this Orleans silo cluster
//Trace.WriteLine("Searching for Orleans gateway silo via Orleans instance table...");
var clusterId = config.ClusterId;
var connectionString = config.DataConnectionString;
if (String.IsNullOrEmpty(clusterId))
throw new ArgumentException("Cannot connect to Azure silos with null deploymentId", "config.ClusterId");
if (String.IsNullOrEmpty(connectionString))
throw new ArgumentException("Cannot connect to Azure silos with null connectionString", "config.DataConnectionString");
bool initSucceeded = false;
Exception lastException = null;
for (int i = 0; i < MaxRetries; i++)
{
try
{
//parse through ConfigureLoggingDelegate to GrainClient
GrainClient.ConfigureLoggingDelegate = ConfigureLoggingDelegate;
// Initialize will throw if cannot find Gateways
GrainClient.Initialize(config);
initSucceeded = true;
break;
}
catch (Exception exc)
{
lastException = exc;
Trace.TraceError("Client.Initialize failed with exc -- {0}. Will try again", exc.Message);
}
// Pause to let Primary silo start up and register
Trace.TraceInformation("Pausing {0} awaiting silo and gateways registration for Deployment={1}", StartupRetryPause, clusterId);
Thread.Sleep(StartupRetryPause);
}
if (initSucceeded) return;
OrleansException err;
err = lastException != null ? new OrleansException(String.Format("Could not Initialize Client for ClusterId={0}. Last exception={1}",
clusterId, lastException.Message), lastException) : new OrleansException(String.Format("Could not Initialize Client for ClusterId={0}.", clusterId));
Trace.TraceError("Error starting Orleans Azure client application -- {0} -- bailing. {1}", err.Message, LogFormatter.PrintException(err));
throw err;
}
#endregion
}
}
#pragma warning restore CS0618 // Type or member is obsolete
| |
#region File Description
//-----------------------------------------------------------------------------
// Ionixx Games 3/9/2009
// Copyright (C) Bryan Phelps. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using SkinnedModelInstancing;
namespace InstancedSkinningSample
{
/// <summary>
/// This class is responsible for storing per-instance data for each Dwarf
/// </summary>
public class Dwarf
{
private static Random random = new Random();
#region Fields
//This data was simply pulled from the model
//I know that ModelMeshes 0,1,2 are different heads, and 3,7,8 are different bodies, etc
private static int [] HeadParts = new int[] { 0, 1, 2 };
private static int [] BodyParts = new int[] { 3, 7, 8 };
private static int [] LegParts = new int[] { 4, 5, 6 };
private Matrix transform;
private Matrix translationScaleMatrix;
private int headPart;
private int bodyPart;
private int legPart;
private Vector3 translation;
private InstancedSkinningData animationData;
private InstancedAnimationClip currentAnimation;
private float animationFrame;
private int repeatAnimation; //how many times we should replay the animation
#endregion
public BoundingSphere boundingSphere; //This is made public to save from copying across a getter/setter
#region Properties
/// <summary>
/// Return the transform matrix for this Dwarf
/// </summary>
public Matrix Transform
{
get { return transform; }
}
/// <summary>
/// The index of the InstancedModelPart for the head.
/// </summary>
public int HeadPart
{
get { return this.headPart; }
}
/// <summary>
/// The index of the InstancedModelPart for the body.
/// </summary>
public int BodyPart
{
get { return this.bodyPart; }
}
/// <summary>
/// The index of the InstancedModelPart of the leg.
/// </summary>
public int LegPart
{
get { return this.legPart; }
}
/// <summary>
/// The current animation frame for this dwarf.
/// </summary>
public int AnimationFrame
{
get { return (int)this.animationFrame; }
}
/// <summary>
/// Gets/sets whether or not this Dwarf is visible. Used by DwarfArmy.
/// </summary>
public bool IsVisible
{
get;
set;
}
#endregion
/// <summary>
/// Constructor for the Dwarf
/// </summary>
/// <param name="position"></param>
/// <param name="skinningData"></param>
public Dwarf(Vector3 position, InstancedSkinningData skinningData)
{
this.animationData = skinningData;
//Choose random body parts - having the same dwarf everywhere would be boring!
this.bodyPart = BodyParts[random.Next(0, 3)];
this.legPart = LegParts[random.Next(0, 3)];
this.headPart = HeadParts[random.Next(0, 3)];
//Mess with the scale some - dwarves come in all shapes and sizes!
float scale = (float)(random.NextDouble() * 0.4) + 0.8f;
this.translation = position;
//Precompute the matrix for translation and scale - rotation will be done dynamically
this.translationScaleMatrix = Matrix.CreateScale(scale) * Matrix.CreateTranslation(this.translation);
//Create the bounding sphere for this dwarf
this.boundingSphere = new BoundingSphere(translation, 1f);
}
/// <summary>
/// Update the animation and behavior of this dwarf
/// </summary>
/// <param name="gameTime"></param>
/// <param name="playerPosition"></param>
public void Update(GameTime gameTime, ref Vector3 playerPosition)
{
//If we don't have an animation, we should probably pick a new one out
if (this.currentAnimation == null)
{
this.currentAnimation = this.GetNextAnimation(ref playerPosition);
this.animationFrame = this.currentAnimation.StartRow;
}
//Otherwise, increment the animation frame on our current animation
if (this.currentAnimation != null)
{
this.animationFrame += (float)(gameTime.ElapsedGameTime.TotalSeconds * this.currentAnimation.FrameRate);
if ((int)this.animationFrame >= this.currentAnimation.EndRow)
{
//If we still need to repeat some, repeat
if (this.repeatAnimation > 0)
{
this.repeatAnimation--;
this.animationFrame = this.currentAnimation.StartRow;
}
else
{
this.animationFrame = this.currentAnimation.EndRow;
//Time to switch animation
this.currentAnimation = null;
}
}
}
//Rotate the dwarf to face the player
float zDelta = playerPosition.Z - this.translation.Z;
float xDelta = playerPosition.X - this.translation.X;
float rotation = (float)(Math.Atan2(xDelta, zDelta));
//Create the rotation matrix based on the rotation we calculated
Matrix rotationMatrix;
Matrix.CreateRotationY(rotation, out rotationMatrix);
//Calculate our final transform matrix for the dwarf
Matrix.Multiply(ref rotationMatrix, ref this.translationScaleMatrix, out this.transform);
}
/// <summary>
/// This function decides what animation we want to do next!
/// </summary>
/// <returns></returns>
private InstancedAnimationClip GetNextAnimation( ref Vector3 playerPosition)
{
//Otherwise, we're going to pick an animation based on the players proximity
//If the player is really close, we'll play the JumpCheer
//If he's sort of close, we'll play one of the Cheers
//If he's far, we'll play an Idle
float distanceSquared;
Vector3.DistanceSquared(ref playerPosition, ref this.translation, out distanceSquared);
//If we're close, then play the jump cheer animation. We also give a small random chance
//of playing it anyway, because some dwarves may be extra peppy
if (distanceSquared < 15000f || random.NextDouble() < 0.05)
{
this.repeatAnimation = 1;
return animationData.Animations["JumpCheer"];
}
//Play a cheer if we're sort of close.
else if (distanceSquared < 50000f || random.NextDouble() < 0.05)
{
this.repeatAnimation = 1;
int anim = random.Next(1, 4);
switch (anim)
{
case 1:
return animationData.Animations["Cheer1"];
case 2:
return animationData.Animations["Cheer2"];
case 3:
return animationData.Animations["Cheer3"];
}
}
//Otherwise, we'll probably play an idle animation
else
{
//For idle animations, they are very short, so we'll repeat them some
this.repeatAnimation = random.Next(5, 10);
int anim = random.Next(1, 3);
switch (anim)
{
case 1:
return animationData.Animations["Idle1"];
case 2:
return animationData.Animations["Idle2"];
}
}
return null;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UserDiagnosticProviderEngine
{
public class DiagnosticAnalyzerDriverTests
{
[Fact]
public async Task DiagnosticAnalyzerDriverAllInOne()
{
var source = TestResource.AllInOneCSharpCode;
// AllInOneCSharpCode has no properties with initializers or named types with primary constructors.
var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>();
symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property);
symbolKindsWithNoCodeBlocks.Add(SymbolKind.NamedType);
var analyzer = new CSharpTrackingDiagnosticAnalyzer();
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(source, TestOptions.Regular))
{
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
AccessSupportedDiagnostics(analyzer);
await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length));
analyzer.VerifyAllAnalyzerMembersWereCalled();
analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds();
analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds();
analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks, true);
}
}
[Fact, WorkItem(908658)]
public async Task DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock()
{
var methodNames = new string[] { "Initialize", "AnalyzeCodeBlock" };
var source = @"
[System.Obsolete]
class C
{
int P { get; set; }
delegate void A();
delegate string F();
}
";
var ideEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer();
using (var ideEngineWorkspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(source))
{
var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single();
await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineAnalyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length));
foreach (var method in methodNames)
{
Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid));
Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid));
Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType));
Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property));
}
}
var compilerEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer();
using (var compilerEngineWorkspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(source))
{
var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { compilerEngineAnalyzer });
foreach (var method in methodNames)
{
Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid));
Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid));
Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType));
Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property));
}
}
}
[Fact]
[WorkItem(759)]
public async Task DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions()
{
var source = TestResource.AllInOneCSharpCode;
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(source, TestOptions.Regular))
{
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
await ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(async analyzer =>
await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length), logAnalyzerExceptionAsDiagnostics: true));
}
}
[WorkItem(908621)]
[Fact]
public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_1()
{
var analyzer = new ThrowingDiagnosticAnalyzer<SyntaxKind>();
analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name);
AccessSupportedDiagnostics(analyzer);
}
[WorkItem(908621)]
[Fact]
public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_2()
{
var analyzer = new ThrowingDoNotCatchDiagnosticAnalyzer<SyntaxKind>();
analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name);
var exceptions = new List<Exception>();
try
{
AccessSupportedDiagnostics(analyzer);
}
catch (Exception e)
{
exceptions.Add(e);
}
Assert.True(exceptions.Count == 0);
}
[Fact]
public async Task AnalyzerOptionsArePassedToAllAnalyzers()
{
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(TestResource.AllInOneCSharpCode, TestOptions.Regular))
{
var currentProject = workspace.CurrentSolution.Projects.Single();
var additionalDocId = DocumentId.CreateNewId(currentProject.Id);
var newSln = workspace.CurrentSolution.AddAdditionalDocument(additionalDocId, "add.config", SourceText.From("random text"));
currentProject = newSln.Projects.Single();
var additionalDocument = currentProject.GetAdditionalDocument(additionalDocId);
AdditionalText additionalStream = new AdditionalTextDocument(additionalDocument.GetDocumentState());
AnalyzerOptions options = new AnalyzerOptions(ImmutableArray.Create(additionalStream));
var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(expectedOptions: options);
var sourceDocument = currentProject.Documents.Single();
await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, sourceDocument, new Text.TextSpan(0, sourceDocument.GetTextAsync().Result.Length));
analyzer.VerifyAnalyzerOptions();
}
}
private void AccessSupportedDiagnostics(DiagnosticAnalyzer analyzer)
{
var diagnosticService = new TestDiagnosticAnalyzerService(LanguageNames.CSharp, analyzer);
diagnosticService.GetDiagnosticDescriptors(projectOpt: null);
}
private class ThrowingDoNotCatchDiagnosticAnalyzer<TLanguageKindEnum> : ThrowingDiagnosticAnalyzer<TLanguageKindEnum>, IBuiltInAnalyzer where TLanguageKindEnum : struct
{
public DiagnosticAnalyzerCategory GetAnalyzerCategory()
{
return DiagnosticAnalyzerCategory.SyntaxAnalysis | DiagnosticAnalyzerCategory.SemanticDocumentAnalysis | DiagnosticAnalyzerCategory.ProjectAnalysis;
}
}
[Fact]
public async Task AnalyzerCreatedAtCompilationLevelNeedNotBeCompilationAnalyzer()
{
var source = @"x";
var analyzer = new CompilationAnalyzerWithSyntaxTreeAnalyzer();
using (var ideEngineWorkspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(source))
{
var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single();
var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length));
var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == "SyntaxDiagnostic");
Assert.Equal(1, diagnosticsFromAnalyzer.Count());
}
}
private class CompilationAnalyzerWithSyntaxTreeAnalyzer : DiagnosticAnalyzer
{
private const string ID = "SyntaxDiagnostic";
private static readonly DiagnosticDescriptor s_syntaxDiagnosticDescriptor =
new DiagnosticDescriptor(ID, title: "Syntax", messageFormat: "Syntax", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(s_syntaxDiagnosticDescriptor);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation);
}
public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
{
context.RegisterSyntaxTreeAction(new SyntaxTreeAnalyzer().AnalyzeSyntaxTree);
}
private class SyntaxTreeAnalyzer
{
public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
context.ReportDiagnostic(Diagnostic.Create(s_syntaxDiagnosticDescriptor, context.Tree.GetRoot().GetFirstToken().GetLocation()));
}
}
}
[Fact]
public async Task CodeBlockAnalyzersOnlyAnalyzeExecutableCode()
{
var source = @"
using System;
class C
{
void F(int x = 0)
{
Console.WriteLine(0);
}
}
";
var analyzer = new CodeBlockAnalyzerFactory();
using (var ideEngineWorkspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(source))
{
var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single();
var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length));
var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id);
Assert.Equal(2, diagnosticsFromAnalyzer.Count());
}
source = @"
using System;
class C
{
void F(int x = 0, int y = 1, int z = 2)
{
Console.WriteLine(0);
}
}
";
using (var compilerEngineWorkspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(source))
{
var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer });
var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id);
Assert.Equal(4, diagnosticsFromAnalyzer.Count());
}
}
private class CodeBlockAnalyzerFactory : DiagnosticAnalyzer
{
public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Descriptor);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterCodeBlockStartAction<SyntaxKind>(CreateAnalyzerWithinCodeBlock);
}
public void CreateAnalyzerWithinCodeBlock(CodeBlockStartAnalysisContext<SyntaxKind> context)
{
var blockAnalyzer = new CodeBlockAnalyzer();
context.RegisterCodeBlockEndAction(blockAnalyzer.AnalyzeCodeBlock);
context.RegisterSyntaxNodeAction(blockAnalyzer.AnalyzeNode, blockAnalyzer.SyntaxKindsOfInterest.ToArray());
}
private class CodeBlockAnalyzer
{
public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest
{
get
{
return ImmutableArray.Create(SyntaxKind.MethodDeclaration, SyntaxKind.ExpressionStatement, SyntaxKind.EqualsValueClause);
}
}
public void AnalyzeCodeBlock(CodeBlockAnalysisContext context)
{
}
public void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
// Ensure only executable nodes are analyzed.
Assert.NotEqual(SyntaxKind.MethodDeclaration, context.Node.Kind());
context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation()));
}
}
}
}
}
| |
/*
* Copyright (c) 2013-2015, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using SteamKit2;
namespace SteamDatabaseBackend
{
static class Utils
{
private static Random RandomGenerator = new Random();
// Adapted from http://stackoverflow.com/a/13503860/139147
// Mono doesn't really like method extensions
public static IEnumerable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
/* this*/ IEnumerable<TLeft> left,
IEnumerable<TRight> right,
Func<TLeft, TKey> leftKeySelector,
Func<TRight, TKey> rightKeySelector,
Func<TLeft, TRight, TKey, TResult> resultSelector,
TLeft defaultLeft = default(TLeft),
TRight defaultRight = default(TRight))
{
var leftLookup = left.ToLookup(leftKeySelector);
var rightLookup = right.ToLookup(rightKeySelector);
var leftKeys = leftLookup.Select(l => l.Key);
var rightKeys = rightLookup.Select(r => r.Key);
var keySet = new HashSet<TKey>(leftKeys.Union(rightKeys));
return from key in keySet
from leftValue in leftLookup[key].DefaultIfEmpty(defaultLeft)
from rightValue in rightLookup[key].DefaultIfEmpty(defaultRight)
select resultSelector(leftValue, rightValue, key);
}
public static int NextRandom(int maxValue)
{
lock (RandomGenerator)
{
return RandomGenerator.Next(maxValue);
}
}
public static int ExponentionalBackoff(int i)
{
return (1 << i) * 1000 + NextRandom(1001);
}
public static SteamApps.PICSRequest NewPICSRequest(uint id)
{
return new SteamApps.PICSRequest(id, PICSTokens.GetToken(id), false);
}
public static SteamApps.PICSRequest NewPICSRequest(uint id, ulong accessToken)
{
if (accessToken > 0)
{
PICSTokens.HandleToken(id, accessToken);
}
return new SteamApps.PICSRequest(id, accessToken, false);
}
public static byte[] AdlerHash(byte[] input)
{
uint a = 0, b = 0;
for (int i = 0; i < input.Length; i++)
{
a = (a + input[i]) % 65521;
b = (b + a) % 65521;
}
return BitConverter.GetBytes(a | (b << 16));
}
public static byte[] StringToByteArray(string str)
{
var HexAsBytes = new byte[str.Length / 2];
for (int index = 0; index < HexAsBytes.Length; index++)
{
string byteValue = str.Substring(index * 2, 2);
HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return HexAsBytes;
}
public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-", "");
}
public static bool ConvertUserInputToSQLSearch(ref string output)
{
if (output.Length < 2 || !output.Distinct().Skip(1).Any()) // TODO: Probably would be better to only search for % and _ repetitions
{
return false;
}
if (output[0] == '^')
{
output = output.Substring(1);
}
else
{
output = "%" + output;
}
if (output[output.Length - 1] == '$')
{
output = output.Substring(0, output.Length - 1);
}
else
{
output += "%";
}
if (output.Length == 0)
{
return false;
}
var distinct = output.Distinct().ToList();
if (distinct.Count == 1 && distinct.First() == '%')
{
return false;
}
return true;
}
public static string RemoveControlCharacters(string input)
{
return new string(input.Where(c => !char.IsControl(c)).ToArray());
}
public static string JsonifyKeyValue(KeyValue keys)
{
string value;
using (var sw = new StringWriter(new StringBuilder()))
{
using (JsonWriter w = new JsonTextWriter(sw))
{
JsonifyKeyValue(w, keys.Children);
}
value = sw.ToString();
}
return value;
}
private static void JsonifyKeyValue(JsonWriter w, List<KeyValue> keys)
{
w.WriteStartObject();
foreach (KeyValue keyval in keys)
{
if (keyval.Children.Count > 0)
{
w.WritePropertyName(keyval.Name);
JsonifyKeyValue(w, keyval.Children);
}
else if (keyval.Value != null) // TODO: Should we be writing null keys anyway?
{
w.WritePropertyName(keyval.Name);
w.WriteValue(keyval.Value);
}
}
w.WriteEndObject();
}
}
class EmptyGrouping<TKey, TValue> : IGrouping<TKey, TValue>
{
public TKey Key { get; set; }
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
{
return Enumerable.Empty<TValue>().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return Enumerable.Empty<TValue>().GetEnumerator();
}
}
}
| |
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.CodeAnalysis.VisualBasic.Syntax;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.DotNet.CodeFormatting.Rules
{
internal partial class ExplicitVisibilityRule
{
private sealed class VisualBasicVisibilityRewriter : VisualBasicSyntaxRewriter
{
private readonly Document _document;
private readonly CancellationToken _cancellationToken;
private SemanticModel _semanticModel;
private bool _inModule;
internal VisualBasicVisibilityRewriter(Document document, CancellationToken cancellationToken)
{
_document = document;
_cancellationToken = cancellationToken;
}
public override SyntaxNode VisitClassBlock(ClassBlockSyntax originalNode)
{
var node = (ClassBlockSyntax)base.VisitClassBlock(originalNode);
var begin = (ClassStatementSyntax)EnsureVisibility(
node.ClassStatement,
node.ClassStatement.ClassKeyword,
node.ClassStatement.Modifiers,
(x, k) => x.WithClassKeyword(k),
(x, l) => x.WithModifiers(l),
() => GetTypeDefaultVisibility(originalNode));
return node.WithClassStatement(begin);
}
public override SyntaxNode VisitStructureBlock(StructureBlockSyntax originalNode)
{
var node = (StructureBlockSyntax)base.VisitStructureBlock(originalNode);
var begin = (StructureStatementSyntax)EnsureVisibility(
node.StructureStatement,
node.StructureStatement.StructureKeyword,
node.StructureStatement.Modifiers,
(x, k) => x.WithStructureKeyword(k),
(x, l) => x.WithModifiers(l),
() => GetTypeDefaultVisibility(originalNode));
return node.WithStructureStatement(begin);
}
public override SyntaxNode VisitInterfaceBlock(InterfaceBlockSyntax originalNode)
{
var node = (InterfaceBlockSyntax)base.VisitInterfaceBlock(originalNode);
var begin = (InterfaceStatementSyntax)EnsureVisibility(
node.InterfaceStatement,
node.InterfaceStatement.InterfaceKeyword,
node.InterfaceStatement.Modifiers,
(x, k) => x.WithInterfaceKeyword(k),
(x, l) => x.WithModifiers(l),
() => GetTypeDefaultVisibility(originalNode));
return node.WithInterfaceStatement(begin);
}
public override SyntaxNode VisitModuleBlock(ModuleBlockSyntax node)
{
var savedInModule = _inModule;
try
{
_inModule = true;
node = (ModuleBlockSyntax)base.VisitModuleBlock(node);
}
finally
{
_inModule = savedInModule;
}
var begin = (ModuleStatementSyntax)EnsureVisibility(
node.ModuleStatement,
node.ModuleStatement.ModuleKeyword,
node.ModuleStatement.Modifiers,
(x, k) => x.WithModuleKeyword(k),
(x, l) => x.WithModifiers(l),
() => SyntaxKind.FriendKeyword);
return node.WithModuleStatement(begin);
}
public override SyntaxNode VisitEnumBlock(EnumBlockSyntax node)
{
var enumStatement = (EnumStatementSyntax)EnsureVisibility(
node.EnumStatement,
node.EnumStatement.EnumKeyword,
node.EnumStatement.Modifiers,
(x, k) => x.WithEnumKeyword(k),
(x, l) => x.WithModifiers(l),
() => GetDelegateTypeDefaultVisibility(node));
return node.WithEnumStatement(enumStatement);
}
public override SyntaxNode VisitMethodStatement(MethodStatementSyntax node)
{
if (IsInterfaceMember(node))
{
return node;
}
return EnsureVisibility(
node,
node.SubOrFunctionKeyword,
node.Modifiers,
(x, k) => x.WithSubOrFunctionKeyword(k),
(x, l) => x.WithModifiers(l),
() => SyntaxKind.PublicKeyword);
}
public override SyntaxNode VisitSubNewStatement(SubNewStatementSyntax node)
{
if (node.Modifiers.Any(x => x.IsKind(SyntaxKind.SharedKeyword)) || _inModule)
{
return node;
}
return EnsureVisibility(
node,
node.SubKeyword,
node.Modifiers,
(x, k) => x.WithSubKeyword(k),
(x, l) => x.WithModifiers(l),
() => SyntaxKind.PublicKeyword);
}
public override SyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node)
{
node = (FieldDeclarationSyntax)EnsureVisibility(
node,
node.Modifiers,
(x, l) => x.WithModifiers(l),
() => SyntaxKind.PrivateKeyword);
// Now that the field has an explicit modifier remove any Dim modifiers on it
// as it is now redundant
var list = node.Modifiers;
var i = 0;
while (i < list.Count)
{
if (list[i].Kind() == SyntaxKind.DimKeyword)
{
list = list.RemoveAt(i);
break;
}
i++;
}
return node.WithModifiers(list);
}
public override SyntaxNode VisitDelegateStatement(DelegateStatementSyntax node)
{
return EnsureVisibility(node, node.Modifiers, (x, l) => x.WithModifiers(l), () => GetDelegateTypeDefaultVisibility(node));
}
public override SyntaxNode VisitPropertyStatement(PropertyStatementSyntax node)
{
if (IsInterfaceMember(node))
{
return node;
}
return EnsureVisibility(node, node.Modifiers, (x, l) => x.WithModifiers(l), () => SyntaxKind.PublicKeyword);
}
private SyntaxKind GetTypeDefaultVisibility(TypeBlockSyntax originalTypeBlockSyntax)
{
// In the case of partial types we need to use the existing visibility if it exists
if (originalTypeBlockSyntax.BlockStatement.Modifiers.Any(x => x.Kind() == SyntaxKind.PartialKeyword))
{
SyntaxKind? kind = GetExistingPartialVisibility(originalTypeBlockSyntax);
if (kind.HasValue)
{
return kind.Value;
}
}
return GetDelegateTypeDefaultVisibility(originalTypeBlockSyntax);
}
private SyntaxKind GetDelegateTypeDefaultVisibility(SyntaxNode node)
{
return IsNestedDeclaration(node) ? SyntaxKind.PublicKeyword : SyntaxKind.FriendKeyword;
}
private SyntaxKind? GetExistingPartialVisibility(TypeBlockSyntax originalTypeBlockSyntax)
{
// Getting the SemanticModel is a relatively expensive operation. Can take a few seconds in
// projects of significant size. It is delay created to avoid this in files which already
// conform to the standards.
if (_semanticModel == null)
{
_semanticModel = _document.GetSemanticModelAsync(_cancellationToken).Result;
}
var symbol = _semanticModel.GetDeclaredSymbol(originalTypeBlockSyntax, _cancellationToken);
if (symbol == null)
{
return null;
}
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Friend:
return SyntaxKind.FriendKeyword;
case Accessibility.Public:
return SyntaxKind.PublicKeyword;
case Accessibility.Private:
return SyntaxKind.PrivateKeyword;
case Accessibility.Protected:
return SyntaxKind.ProtectedKeyword;
default: return null;
}
}
private static bool IsInterfaceMember(SyntaxNode node)
{
return node.Parent != null && node.Parent.Kind() == SyntaxKind.InterfaceBlock;
}
private static SyntaxKind? GetVisibilityModifier(SyntaxTokenList list)
{
foreach (var token in list)
{
if (SyntaxFacts.IsAccessibilityModifier(token.Kind()))
{
return token.Kind();
}
}
return null;
}
private static bool IsNestedDeclaration(SyntaxNode node)
{
var current = node.Parent;
while (current != null)
{
var kind = current.Kind();
if (kind == SyntaxKind.ClassBlock || kind == SyntaxKind.StructureBlock || kind == SyntaxKind.InterfaceBlock)
{
return true;
}
current = current.Parent;
}
return false;
}
private static SyntaxNode EnsureVisibility<T>(T node, SyntaxToken keyword, SyntaxTokenList originalModifiers, Func<T, SyntaxToken, T> withKeyword, Func<T, SyntaxTokenList, T> withModifiers, Func<SyntaxKind> getDefaultVisibility) where T : SyntaxNode
{
Func<SyntaxKind, T> withFirstModifier = (visibilityKind) =>
{
var leadingTrivia = keyword.LeadingTrivia;
node = withKeyword(node, keyword.WithLeadingTrivia());
var visibilityToken = SyntaxFactory.Token(
leadingTrivia,
visibilityKind,
SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ")));
var modifierList = SyntaxFactory.TokenList(visibilityToken);
return withModifiers(node, modifierList);
};
return EnsureVisibilityCore(
node,
originalModifiers,
withFirstModifier,
withModifiers,
getDefaultVisibility);
}
private static SyntaxNode EnsureVisibility<T>(T node, SyntaxTokenList originalModifiers, Func<T, SyntaxTokenList, T> withModifiers, Func<SyntaxKind> getDefaultVisibility) where T : SyntaxNode
{
Func<SyntaxKind, T> withFirstModifier = (visibilityKind) =>
{
var leadingTrivia = node.GetLeadingTrivia();
node = node.WithLeadingTrivia();
var visibilityToken = SyntaxFactory.Token(
leadingTrivia,
visibilityKind,
SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ")));
var modifierList = SyntaxFactory.TokenList(visibilityToken);
return withModifiers(node, modifierList);
};
return EnsureVisibilityCore(
node,
originalModifiers,
withFirstModifier,
withModifiers,
getDefaultVisibility);
}
/// <summary>
/// Return a node declaration that has a visibility modifier. If one isn't present it will be added as the
/// first modifier. Any trivia before the node will be added as leading trivia to the added <see cref="SyntaxToken"/>.
/// </summary>
private static SyntaxNode EnsureVisibilityCore<T>(T node, SyntaxTokenList originalModifiers, Func<SyntaxKind, T> withFirstModifier, Func<T, SyntaxTokenList, T> withModifiers, Func<SyntaxKind> getDefaultVisibility) where T : SyntaxNode
{
if (originalModifiers.Any(x => SyntaxFacts.IsAccessibilityModifier(x.Kind())))
{
return node;
}
SyntaxKind visibilityKind = getDefaultVisibility();
Debug.Assert(SyntaxFacts.IsAccessibilityModifier(visibilityKind));
SyntaxTokenList modifierList;
if (originalModifiers.Count == 0)
{
return withFirstModifier(visibilityKind);
}
else
{
var leadingTrivia = originalModifiers[0].LeadingTrivia;
var visibilityToken = SyntaxFactory.Token(
leadingTrivia,
visibilityKind,
SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ")));
var list = new List<SyntaxToken>();
list.Add(visibilityToken);
list.Add(originalModifiers[0].WithLeadingTrivia());
for (int i = 1; i < originalModifiers.Count; i++)
{
list.Add(originalModifiers[i]);
}
modifierList = SyntaxFactory.TokenList(list);
return withModifiers(node, modifierList);
}
}
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using EventStore.Common.Utils;
using EventStore.Core.Data;
using EventStore.Projections.Core.Services.Processing;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace EventStore.Projections.Core.Tests.Other
{
[TestFixture]
class can_serialize_and_deserialize
{
private ProjectionVersion _version;
[SetUp]
public void setup()
{
_version = new ProjectionVersion(1, 0, 0);
}
[Test]
public void position_based_checkpoint_tag()
{
CheckpointTag tag = CheckpointTag.FromPosition(1, -1, 0);
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
}
[Test]
public void prepare_position_based_checkpoint_tag_zero()
{
CheckpointTag tag = CheckpointTag.FromPreparePosition(1, 0);
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
}
[Test]
public void prepare_position_based_checkpoint_tag_minus_one()
{
CheckpointTag tag = CheckpointTag.FromPreparePosition(1, -1);
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
}
[Test]
public void prepare_position_based_checkpoint_tag()
{
CheckpointTag tag = CheckpointTag.FromPreparePosition(1, 1234);
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
}
[Test]
public void stream_based_checkpoint_tag()
{
CheckpointTag tag = CheckpointTag.FromStreamPosition(1, "$ce-account", 12345);
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
Assert.IsNull(back.CommitPosition);
}
[Test]
public void streams_based_checkpoint_tag()
{
CheckpointTag tag = CheckpointTag.FromStreamPositions(1, new Dictionary<string, int> {{"a", 1}, {"b", 2}});
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
Assert.IsNull(back.CommitPosition);
}
[Test]
public void event_by_type_index_based_checkpoint_tag()
{
CheckpointTag tag = CheckpointTag.FromEventTypeIndexPositions(
0, new TFPos(100, 50), new Dictionary<string, int> {{"a", 1}, {"b", 2}});
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
}
[Test]
public void phase_based_checkpoint_tag_completed()
{
CheckpointTag tag = CheckpointTag.FromPhase(2, completed: false);
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
}
[Test]
public void phase_based_checkpoint_tag_incomplete()
{
CheckpointTag tag = CheckpointTag.FromPhase(0, completed: true);
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
}
[Test]
public void by_stream_based_checkpoint_tag()
{
CheckpointTag tag = CheckpointTag.FromByStreamPosition(0, "catalog", 1, "data", 2, 12345);
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
}
[Test]
public void by_stream_based_checkpoint_tag_zero()
{
CheckpointTag tag = CheckpointTag.FromByStreamPosition(0, "catalog", -1, null, -1, 12345);
byte[] bytes = tag.ToJsonBytes(_version);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTag back = instring.ParseCheckpointTagJson();
Assert.AreEqual(tag, back);
}
[Test]
public void extra_metadata_are_preserved()
{
CheckpointTag tag = CheckpointTag.FromPosition(0, -1, 0);
var extra = new Dictionary<string, JToken> {{"$$a", new JRaw("\"b\"")}, {"$$c", new JRaw("\"d\"")}};
byte[] bytes = tag.ToJsonBytes(_version, extra);
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
CheckpointTagVersion back = instring.ParseCheckpointTagVersionExtraJson(_version);
Assert.IsNotNull(back.ExtraMetadata);
JToken v;
Assert.IsTrue(back.ExtraMetadata.TryGetValue("$$a", out v));
Assert.AreEqual("b", (string) ((JValue) v).Value);
Assert.IsTrue(back.ExtraMetadata.TryGetValue("$$c", out v));
Assert.AreEqual("d", (string) ((JValue) v).Value);
}
[Test]
public void can_deserialize_readonly_fields()
{
TestData data = new TestData("123");
byte[] bytes = data.ToJsonBytes();
string instring = Helper.UTF8NoBom.GetString(bytes);
Console.WriteLine(instring);
TestData back = instring.ParseJson<TestData>();
Assert.AreEqual(data, back);
}
private class TestData
{
public readonly string Data;
public TestData(string data)
{
Data = data;
}
protected bool Equals(TestData other)
{
return string.Equals(Data, other.Data);
}
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((TestData) obj);
}
public override int GetHashCode()
{
return (Data != null ? Data.GetHashCode() : 0);
}
public override string ToString()
{
return string.Format("Data: {0}", Data);
}
}
}
}
| |
// 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 RoundToZeroSingle()
{
var test = new SimpleUnaryOpTest__RoundToZeroSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.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();
if (Sse.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 (Sse.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__RoundToZeroSingle
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int RetElementCount = VectorSize / sizeof(Single);
private static Single[] _data = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar;
private Vector128<Single> _fld;
private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable;
static SimpleUnaryOpTest__RoundToZeroSingle()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__RoundToZeroSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.RoundToZero(
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.RoundToZero(
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.RoundToZero(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZero), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZero), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZero), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.RoundToZero(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr);
var result = Sse41.RoundToZero(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse41.RoundToZero(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse41.RoundToZero(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__RoundToZeroSingle();
var result = Sse41.RoundToZero(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.RoundToZero(_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<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits((firstOp[0] > 0) ? MathF.Floor(firstOp[0]) : MathF.Ceiling(firstOp[0])))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits((firstOp[i] > 0) ? MathF.Floor(firstOp[i]) : MathF.Ceiling(firstOp[i])))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.RoundToZero)}<Single>(Vector128<Single>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations for managing Azure SQL Database secure
/// connection. Contains operations to: Create, Retrieve and Update
/// secure connection policy .
/// </summary>
internal partial class SecureConnectionPolicyOperations : IServiceOperations<SqlManagementClient>, ISecureConnectionPolicyOperations
{
/// <summary>
/// Initializes a new instance of the SecureConnectionPolicyOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SecureConnectionPolicyOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates or updates an Azure SQL Connection policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the policy
/// applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// secure connection policy.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateOrUpdateDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, DatabaseSecureConnectionPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateDatabasePolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/connectionPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject databaseSecureConnectionPolicyCreateOrUpdateParametersValue = new JObject();
requestDoc = databaseSecureConnectionPolicyCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
databaseSecureConnectionPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.SecurityEnabledAccess != null)
{
propertiesValue["securityEnabledAccess"] = parameters.Properties.SecurityEnabledAccess;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns an Azure SQL Database secure connection policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the secure
/// connection policy applies.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get database secure connection request.
/// </returns>
public async Task<DatabaseSecureConnectionPolicyGetResponse> GetDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "GetDatabasePolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/connectionPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseSecureConnectionPolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseSecureConnectionPolicyGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DatabaseSecureConnectionPolicy secureConnectionPolicyInstance = new DatabaseSecureConnectionPolicy();
result.SecureConnectionPolicy = secureConnectionPolicyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DatabaseSecureConnectionPolicyProperties propertiesInstance = new DatabaseSecureConnectionPolicyProperties();
secureConnectionPolicyInstance.Properties = propertiesInstance;
JToken proxyDnsNameValue = propertiesValue["proxyDnsName"];
if (proxyDnsNameValue != null && proxyDnsNameValue.Type != JTokenType.Null)
{
string proxyDnsNameInstance = ((string)proxyDnsNameValue);
propertiesInstance.ProxyDnsName = proxyDnsNameInstance;
}
JToken proxyPortValue = propertiesValue["proxyPort"];
if (proxyPortValue != null && proxyPortValue.Type != JTokenType.Null)
{
string proxyPortInstance = ((string)proxyPortValue);
propertiesInstance.ProxyPort = proxyPortInstance;
}
JToken securityEnabledAccessValue = propertiesValue["securityEnabledAccess"];
if (securityEnabledAccessValue != null && securityEnabledAccessValue.Type != JTokenType.Null)
{
string securityEnabledAccessInstance = ((string)securityEnabledAccessValue);
propertiesInstance.SecurityEnabledAccess = securityEnabledAccessInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
secureConnectionPolicyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
secureConnectionPolicyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
secureConnectionPolicyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
secureConnectionPolicyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
secureConnectionPolicyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Grpc.Tools
{
/// <summary>
/// Run Google proto compiler (protoc).
///
/// After a successful run, the task reads the dependency file if specified
/// to be saved by the compiler, and returns its output files.
///
/// This task (unlike PrepareProtoCompile) does not attempt to guess anything
/// about language-specific behavior of protoc, and therefore can be used for
/// any language outputs.
/// </summary>
public class ProtoCompile : ToolTask
{
/*
Usage: /home/kkm/work/protobuf/src/.libs/lt-protoc [OPTION] PROTO_FILES
Parse PROTO_FILES and generate output based on the options given:
-IPATH, --proto_path=PATH Specify the directory in which to search for
imports. May be specified multiple times;
directories will be searched in order. If not
given, the current working directory is used.
--version Show version info and exit.
-h, --help Show this text and exit.
--encode=MESSAGE_TYPE Read a text-format message of the given type
from standard input and write it in binary
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode=MESSAGE_TYPE Read a binary message of the given type from
standard input and write it in text format
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode_raw Read an arbitrary protocol message from
standard input and write the raw tag/value
pairs in text format to standard output. No
PROTO_FILES should be given when using this
flag.
--descriptor_set_in=FILES Specifies a delimited list of FILES
each containing a FileDescriptorSet (a
protocol buffer defined in descriptor.proto).
The FileDescriptor for each of the PROTO_FILES
provided will be loaded from these
FileDescriptorSets. If a FileDescriptor
appears multiple times, the first occurrence
will be used.
-oFILE, Writes a FileDescriptorSet (a protocol buffer,
--descriptor_set_out=FILE defined in descriptor.proto) containing all of
the input files to FILE.
--include_imports When using --descriptor_set_out, also include
all dependencies of the input files in the
set, so that the set is self-contained.
--include_source_info When using --descriptor_set_out, do not strip
SourceCodeInfo from the FileDescriptorProto.
This results in vastly larger descriptors that
include information about the original
location of each decl in the source file as
well as surrounding comments.
--dependency_out=FILE Write a dependency output file in the format
expected by make. This writes the transitive
set of input file paths to FILE
--error_format=FORMAT Set the format in which to print errors.
FORMAT may be 'gcc' (the default) or 'msvs'
(Microsoft Visual Studio format).
--print_free_field_numbers Print the free field numbers of the messages
defined in the given proto files. Groups share
the same field number space with the parent
message. Extension ranges are counted as
occupied fields numbers.
--plugin=EXECUTABLE Specifies a plugin executable to use.
Normally, protoc searches the PATH for
plugins, but you may specify additional
executables not in the path using this flag.
Additionally, EXECUTABLE may be of the form
NAME=PATH, in which case the given plugin name
is mapped to the given executable even if
the executable's own name differs.
--cpp_out=OUT_DIR Generate C++ header and source.
--csharp_out=OUT_DIR Generate C# source file.
--java_out=OUT_DIR Generate Java source file.
--javanano_out=OUT_DIR Generate Java Nano source file.
--js_out=OUT_DIR Generate JavaScript source.
--objc_out=OUT_DIR Generate Objective C header and source.
--php_out=OUT_DIR Generate PHP source file.
--python_out=OUT_DIR Generate Python source file.
--ruby_out=OUT_DIR Generate Ruby source file.
@<filename> Read options and filenames from file. If a
relative file path is specified, the file
will be searched in the working directory.
The --proto_path option will not affect how
this argument file is searched. Content of
the file will be expanded in the position of
@<filename> as in the argument list. Note
that shell expansion is not applied to the
content of the file (i.e., you cannot use
quotes, wildcards, escapes, commands, etc.).
Each line corresponds to a single argument,
even if it contains spaces.
*/
static string[] s_supportedGenerators = new[] { "cpp", "csharp", "java",
"javanano", "js", "objc",
"php", "python", "ruby" };
static readonly TimeSpan s_regexTimeout = TimeSpan.FromMilliseconds(100);
static readonly List<ErrorListFilter> s_errorListFilters = new List<ErrorListFilter>()
{
// Example warning with location
//../Protos/greet.proto(19) : warning in column=5 : warning : When enum name is stripped and label is PascalCased (Zero),
// this value label conflicts with Zero. This will make the proto fail to compile for some languages, such as C#.
new ErrorListFilter
{
Pattern = new Regex(
pattern: "^(?'FILENAME'.+?)\\((?'LINE'\\d+)\\) ?: ?warning in column=(?'COLUMN'\\d+) ?: ?(?'TEXT'.*)",
options: RegexOptions.Compiled | RegexOptions.IgnoreCase,
matchTimeout: s_regexTimeout),
LogAction = (log, match) =>
{
int.TryParse(match.Groups["LINE"].Value, out var line);
int.TryParse(match.Groups["COLUMN"].Value, out var column);
log.LogWarning(
subcategory: null,
warningCode: null,
helpKeyword: null,
file: match.Groups["FILENAME"].Value,
lineNumber: line,
columnNumber: column,
endLineNumber: 0,
endColumnNumber: 0,
message: match.Groups["TEXT"].Value);
}
},
// Example error with location
//../Protos/greet.proto(14) : error in column=10: "name" is already defined in "Greet.HelloRequest".
new ErrorListFilter
{
Pattern = new Regex(
pattern: "^(?'FILENAME'.+?)\\((?'LINE'\\d+)\\) ?: ?error in column=(?'COLUMN'\\d+) ?: ?(?'TEXT'.*)",
options: RegexOptions.Compiled | RegexOptions.IgnoreCase,
matchTimeout: s_regexTimeout),
LogAction = (log, match) =>
{
int.TryParse(match.Groups["LINE"].Value, out var line);
int.TryParse(match.Groups["COLUMN"].Value, out var column);
log.LogError(
subcategory: null,
errorCode: null,
helpKeyword: null,
file: match.Groups["FILENAME"].Value,
lineNumber: line,
columnNumber: column,
endLineNumber: 0,
endColumnNumber: 0,
message: match.Groups["TEXT"].Value);
}
},
// Example warning without location
//../Protos/greet.proto: warning: Import google/protobuf/empty.proto but not used.
new ErrorListFilter
{
Pattern = new Regex(
pattern: "^(?'FILENAME'.+?): ?warning: ?(?'TEXT'.*)",
options: RegexOptions.Compiled | RegexOptions.IgnoreCase,
matchTimeout: s_regexTimeout),
LogAction = (log, match) =>
{
log.LogWarning(
subcategory: null,
warningCode: null,
helpKeyword: null,
file: match.Groups["FILENAME"].Value,
lineNumber: 0,
columnNumber: 0,
endLineNumber: 0,
endColumnNumber: 0,
message: match.Groups["TEXT"].Value);
}
},
// Example error without location
//../Protos/greet.proto: Import "google/protobuf/empty.proto" was listed twice.
new ErrorListFilter
{
Pattern = new Regex(
pattern: "^(?'FILENAME'.+?): ?(?'TEXT'.*)",
options: RegexOptions.Compiled | RegexOptions.IgnoreCase,
matchTimeout: s_regexTimeout),
LogAction = (log, match) =>
{
log.LogError(
subcategory: null,
errorCode: null,
helpKeyword: null,
file: match.Groups["FILENAME"].Value,
lineNumber: 0,
columnNumber: 0,
endLineNumber: 0,
endColumnNumber: 0,
message: match.Groups["TEXT"].Value);
}
}
};
/// <summary>
/// Code generator.
/// </summary>
[Required]
public string Generator { get; set; }
/// <summary>
/// Protobuf files to compile.
/// </summary>
[Required]
public ITaskItem[] Protobuf { get; set; }
/// <summary>
/// Directory where protoc dependency files are cached. If provided, dependency
/// output filename is autogenerated from source directory hash and file name.
/// Mutually exclusive with DependencyOut.
/// Switch: --dependency_out (with autogenerated file name).
/// </summary>
public string ProtoDepDir { get; set; }
/// <summary>
/// Dependency file full name. Mutually exclusive with ProtoDepDir.
/// Autogenerated file name is available in this property after execution.
/// Switch: --dependency_out.
/// </summary>
[Output]
public string DependencyOut { get; set; }
/// <summary>
/// The directories to search for imports. Directories will be searched
/// in order. If not given, the current working directory is used.
/// Switch: --proto_path.
/// </summary>
public string[] ProtoPath { get; set; }
/// <summary>
/// Generated code directory. The generator property determines the language.
/// Switch: --GEN-out= (for different generators GEN).
/// </summary>
[Required]
public string OutputDir { get; set; }
/// <summary>
/// Codegen options. See also OptionsFromMetadata.
/// Switch: --GEN_out= (for different generators GEN).
/// </summary>
public string[] OutputOptions { get; set; }
/// <summary>
/// Full path to the gRPC plugin executable. If specified, gRPC generation
/// is enabled for the files.
/// Switch: --plugin=protoc-gen-grpc=
/// </summary>
public string GrpcPluginExe { get; set; }
/// <summary>
/// Generated gRPC directory. The generator property determines the
/// language. If gRPC is enabled but this is not given, OutputDir is used.
/// Switch: --grpc_out=
/// </summary>
public string GrpcOutputDir { get; set; }
/// <summary>
/// gRPC Codegen options. See also OptionsFromMetadata.
/// --grpc_opt=opt1,opt2=val (comma-separated).
/// </summary>
public string[] GrpcOutputOptions { get; set; }
/// <summary>
/// List of files written in addition to generated outputs. Includes a
/// single item for the dependency file if written.
/// </summary>
[Output]
public ITaskItem[] AdditionalFileWrites { get; private set; }
/// <summary>
/// List of language files generated by protoc. Empty unless DependencyOut
/// or ProtoDepDir is set, since the file writes are extracted from protoc
/// dependency output file.
/// </summary>
[Output]
public ITaskItem[] GeneratedFiles { get; private set; }
// Hide this property from MSBuild, we should never use a shell script.
private new bool UseCommandProcessor { get; set; }
protected override string ToolName => Platform.IsWindows ? "protoc.exe" : "protoc";
// Since we never try to really locate protoc.exe somehow, just try ToolExe
// as the full tool location. It will be either just protoc[.exe] from
// ToolName above if not set by the user, or a user-supplied full path. The
// base class will then resolve the former using system PATH.
protected override string GenerateFullPathToTool() => ToolExe;
// Log protoc errors with the High priority (bold white in MsBuild,
// printed with -v:n, and shown in the Output windows in VS).
protected override MessageImportance StandardErrorLoggingImportance => MessageImportance.High;
// Called by base class to validate arguments and make them consistent.
protected override bool ValidateParameters()
{
// Part of proto command line switches, must be lowercased.
Generator = Generator.ToLowerInvariant();
if (!System.Array.Exists(s_supportedGenerators, g => g == Generator))
{
Log.LogError("Invalid value for Generator='{0}'. Supported generators: {1}",
Generator, string.Join(", ", s_supportedGenerators));
}
if (ProtoDepDir != null && DependencyOut != null)
{
Log.LogError("Properties ProtoDepDir and DependencyOut may not be both specified");
}
if (Protobuf.Length > 1 && (ProtoDepDir != null || DependencyOut != null))
{
Log.LogError("Proto compiler currently allows only one input when " +
"--dependency_out is specified (via ProtoDepDir or DependencyOut). " +
"Tracking issue: https://github.com/google/protobuf/pull/3959");
}
// Use ProtoDepDir to autogenerate DependencyOut
if (ProtoDepDir != null)
{
DependencyOut = DepFileUtil.GetDepFilenameForProto(ProtoDepDir, Protobuf[0].ItemSpec);
}
if (GrpcPluginExe == null)
{
GrpcOutputOptions = null;
GrpcOutputDir = null;
}
else if (GrpcOutputDir == null)
{
// Use OutputDir for gRPC output if not specified otherwise by user.
GrpcOutputDir = OutputDir;
}
return !Log.HasLoggedErrors && base.ValidateParameters();
}
// Protoc chokes on BOM, naturally. I would!
static readonly Encoding s_utf8WithoutBom = new UTF8Encoding(false);
protected override Encoding ResponseFileEncoding => s_utf8WithoutBom;
// Protoc takes one argument per line from the response file, and does not
// require any quoting whatsoever. Otherwise, this is similar to the
// standard CommandLineBuilder
class ProtocResponseFileBuilder
{
StringBuilder _data = new StringBuilder(1000);
public override string ToString() => _data.ToString();
// If 'value' is not empty, append '--name=value\n'.
public void AddSwitchMaybe(string name, string value)
{
if (!string.IsNullOrEmpty(value))
{
_data.Append("--").Append(name).Append("=")
.Append(value).Append('\n');
}
}
// Add switch with the 'values' separated by commas, for options.
public void AddSwitchMaybe(string name, string[] values)
{
if (values?.Length > 0)
{
_data.Append("--").Append(name).Append("=")
.Append(string.Join(",", values)).Append('\n');
}
}
// Add a positional argument to the file data.
public void AddArg(string arg)
{
_data.Append(arg).Append('\n');
}
};
// Called by the base ToolTask to get response file contents.
protected override string GenerateResponseFileCommands()
{
var cmd = new ProtocResponseFileBuilder();
cmd.AddSwitchMaybe(Generator + "_out", TrimEndSlash(OutputDir));
cmd.AddSwitchMaybe(Generator + "_opt", OutputOptions);
cmd.AddSwitchMaybe("plugin=protoc-gen-grpc", GrpcPluginExe);
cmd.AddSwitchMaybe("grpc_out", TrimEndSlash(GrpcOutputDir));
cmd.AddSwitchMaybe("grpc_opt", GrpcOutputOptions);
if (ProtoPath != null)
{
foreach (string path in ProtoPath)
cmd.AddSwitchMaybe("proto_path", TrimEndSlash(path));
}
cmd.AddSwitchMaybe("dependency_out", DependencyOut);
cmd.AddSwitchMaybe("error_format", "msvs");
foreach (var proto in Protobuf)
{
cmd.AddArg(proto.ItemSpec);
}
return cmd.ToString();
}
// Protoc cannot digest trailing slashes in directory names,
// curiously under Linux, but not in Windows.
static string TrimEndSlash(string dir)
{
if (dir == null || dir.Length <= 1)
{
return dir;
}
string trim = dir.TrimEnd('/', '\\');
// Do not trim the root slash, drive letter possible.
if (trim.Length == 0)
{
// Slashes all the way down.
return dir.Substring(0, 1);
}
if (trim.Length == 2 && dir.Length > 2 && trim[1] == ':')
{
// We have a drive letter and root, e. g. 'C:\'
return dir.Substring(0, 3);
}
return trim;
}
// Called by the base class to log tool's command line.
//
// Protoc command file is peculiar, with one argument per line, separated
// by newlines. Unwrap it for log readability into a single line, and also
// quote arguments, lest it look weird and so it may be copied and pasted
// into shell. Since this is for logging only, correct enough is correct.
protected override void LogToolCommand(string cmd)
{
var printer = new StringBuilder(1024);
// Print 'str' slice into 'printer', wrapping in quotes if contains some
// interesting characters in file names, or if empty string. The list of
// characters requiring quoting is not by any means exhaustive; we are
// just striving to be nice, not guaranteeing to be nice.
var quotable = new[] { ' ', '!', '$', '&', '\'', '^' };
void PrintQuoting(string str, int start, int count)
{
bool wrap = count == 0 || str.IndexOfAny(quotable, start, count) >= 0;
if (wrap) printer.Append('"');
printer.Append(str, start, count);
if (wrap) printer.Append('"');
}
for (int ib = 0, ie; (ie = cmd.IndexOf('\n', ib)) >= 0; ib = ie + 1)
{
// First line only contains both the program name and the first switch.
// We can rely on at least the '--out_dir' switch being always present.
if (ib == 0)
{
int iep = cmd.IndexOf(" --");
if (iep > 0)
{
PrintQuoting(cmd, 0, iep);
ib = iep + 1;
}
}
printer.Append(' ');
if (cmd[ib] == '-')
{
// Print switch unquoted, including '=' if any.
int iarg = cmd.IndexOf('=', ib, ie - ib);
if (iarg < 0)
{
// Bare switch without a '='.
printer.Append(cmd, ib, ie - ib);
continue;
}
printer.Append(cmd, ib, iarg + 1 - ib);
ib = iarg + 1;
}
// A positional argument or switch value.
PrintQuoting(cmd, ib, ie - ib);
}
base.LogToolCommand(printer.ToString());
}
protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
{
foreach (ErrorListFilter filter in s_errorListFilters)
{
Match match = filter.Pattern.Match(singleLine);
if (match.Success)
{
filter.LogAction(Log, match);
return;
}
}
base.LogEventsFromTextOutput(singleLine, messageImportance);
}
// Main task entry point.
public override bool Execute()
{
base.UseCommandProcessor = false;
bool ok = base.Execute();
if (!ok)
{
return false;
}
// Read dependency output file from the compiler to retrieve the
// definitive list of created files. Report the dependency file
// itself as having been written to.
if (DependencyOut != null)
{
string[] outputs = DepFileUtil.ReadDependencyOutputs(DependencyOut, Log);
if (HasLoggedErrors)
{
return false;
}
GeneratedFiles = new ITaskItem[outputs.Length];
for (int i = 0; i < outputs.Length; i++)
{
GeneratedFiles[i] = new TaskItem(outputs[i]);
}
AdditionalFileWrites = new ITaskItem[] { new TaskItem(DependencyOut) };
}
return true;
}
class ErrorListFilter
{
public Regex Pattern { get; set; }
public Action<TaskLoggingHelper, Match> LogAction { get; set; }
}
};
}
| |
using System;
using System.Collections;
namespace LumiSoft.Net.Mime
{
/// <summary>
/// Rfc 2822 3.4 address-list. Rfc defines two types of addresses mailbox and group.
/// <p/>
/// <p style="margin-top: 0; margin-bottom: 0"/><b>address-list</b> syntax: address *("," address).
/// <p style="margin-top: 0; margin-bottom: 0"/><b>address</b> syntax: mailbox / group.
/// <p style="margin-top: 0; margin-bottom: 0"/><b>mailbox</b> syntax: ['"'dispaly-name'"' ]<localpart@domain>.
/// <p style="margin-top: 0; margin-bottom: 0"/><b>group</b> syntax: '"'dispaly-name'":' [mailbox *(',' mailbox)]';'.
/// </summary>
public class AddressList : IEnumerable
{
private HeaderField m_HeaderField = null;
private ArrayList m_pAddresses = null;
/// <summary>
/// Default constructor.
/// </summary>
public AddressList()
{
m_pAddresses = new ArrayList();
}
#region method Add
/// <summary>
/// Adds a new address to the end of the collection.
/// </summary>
/// <param name="address">Address to add.</param>
public void Add(Address address)
{
address.Owner = this;
m_pAddresses.Add(address);
OnCollectionChanged();
}
#endregion
#region method Insert
/// <summary>
/// Inserts a new address into the collection at the specified location.
/// </summary>
/// <param name="index">The location in the collection where you want to add the address.</param>
/// <param name="address">Address to add.</param>
public void Insert(int index,Address address)
{
address.Owner = this;
m_pAddresses.Insert(index,address);
OnCollectionChanged();
}
#endregion
#region method Remove
/// <summary>
/// Removes address at the specified index from the collection.
/// </summary>
/// <param name="index">Index of the address which to remove.</param>
public void Remove(int index)
{
Remove((Address)m_pAddresses[index]);
}
/// <summary>
/// Removes specified address from the collection.
/// </summary>
/// <param name="address">Address to remove.</param>
public void Remove(Address address)
{
address.Owner = null;
m_pAddresses.Remove(address);
OnCollectionChanged();
}
#endregion
#region method Clear
/// <summary>
/// Clears the collection of all addresses.
/// </summary>
public void Clear()
{
foreach(Address address in m_pAddresses){
address.Owner = null;
}
m_pAddresses.Clear();
OnCollectionChanged();
}
#endregion
#region method Parse
/// <summary>
/// Parses address-list from string.
/// </summary>
/// <param name="addressList">Address list string.</param>
/// <returns></returns>
public void Parse(string addressList)
{
addressList = addressList.Trim();
StringReader reader = new StringReader(addressList);
while(reader.SourceString.Length > 0){
// See if mailbox or group. If ',' is before ':', then mailbox
// Example: xxx@domain.com, group:xxxgroup@domain.com;
int commaIndex = TextUtils.QuotedIndexOf(reader.SourceString,',');
int colonIndex = TextUtils.QuotedIndexOf(reader.SourceString,':');
// Mailbox
if(colonIndex == -1 || (commaIndex < colonIndex && commaIndex != -1)){
// Read to ',' or to end if last element
m_pAddresses.Add(MailboxAddress.Parse(reader.QuotedReadToDelimiter(',')));
}
// Group
else{
// Read to ';', this is end of group
m_pAddresses.Add(GroupAddress.Parse(reader.QuotedReadToDelimiter(';')));
// If there are next items, remove first comma because it's part of group address
if(reader.SourceString.Length > 0){
reader.QuotedReadToDelimiter(',');
}
}
}
OnCollectionChanged();
}
#endregion
#region method ToAddressListString
/// <summary>
/// Convert addresses to Rfc 2822 address-list string.
/// </summary>
/// <returns></returns>
public string ToAddressListString()
{
string retVal = "";
for(int i=0;i<m_pAddresses.Count;i++){
if(m_pAddresses[i] is MailboxAddress){
// For last address don't add , and <TAB>
if(i == (m_pAddresses.Count - 1)){
retVal += ((MailboxAddress)m_pAddresses[i]).MailboxString;
}
else{
retVal += ((MailboxAddress)m_pAddresses[i]).MailboxString + ",\t";
}
}
else if(m_pAddresses[i] is GroupAddress){
// For last address don't add , and <TAB>
if(i == (m_pAddresses.Count - 1)){
retVal += ((GroupAddress)m_pAddresses[i]).GroupString;
}
else{
retVal += ((GroupAddress)m_pAddresses[i]).GroupString + ",\t";
}
}
}
return retVal;
}
#endregion
#region internal method OnCollectionChanged
/// <summary>
/// This called when collection has changed. Item is added,deleted,changed or collection cleared.
/// </summary>
internal void OnCollectionChanged()
{
// AddressList is bounded to HeaderField, update header field value
if(m_HeaderField != null){
m_HeaderField.Value = this.ToAddressListString();
}
}
#endregion
#region interface IEnumerator
/// <summary>
/// Gets enumerator.
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return m_pAddresses.GetEnumerator();
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets all mailbox addresses. Note: group address mailbox addresses are also included.
/// </summary>
public MailboxAddress[] Mailboxes
{
get{
ArrayList adressesAll = new ArrayList();
foreach(Address adress in this){
if(adress.IsGroupAddress){
adressesAll.Add((MailboxAddress)adress);
}
else{
foreach(Address groupChildAddress in ((GroupAddress)adress).GroupMembers){
adressesAll.Add((MailboxAddress)groupChildAddress);
}
}
}
MailboxAddress[] retVal = new MailboxAddress[adressesAll.Count];
adressesAll.CopyTo(retVal);
return retVal;
}
}
/// <summary>
/// Gets address from specified index.
/// </summary>
public Address this[int index]
{
get{ return (Address)m_pAddresses[index]; }
}
/// <summary>
/// Gets address count in the collection.
/// </summary>
public int Count
{
get{ return m_pAddresses.Count; }
}
/// <summary>
/// Bound address-list to specified header field.
/// </summary>
internal HeaderField BoundedHeaderField
{
get{ return m_HeaderField; }
set{m_HeaderField = value; }
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Text;
namespace System.IO
{
public static partial class Path
{
public static readonly char DirectorySeparatorChar = '\\';
public static readonly char VolumeSeparatorChar = ':';
public static readonly char PathSeparator = ';';
private const string DirectorySeparatorCharAsString = "\\";
private static readonly char[] InvalidFileNameChars =
{
'\"', '<', '>', '|', '\0',
(char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
(char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
(char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
(char)31, ':', '*', '?', '\\', '/'
};
// The max total path is 260, and the max individual component length is 255.
// For example, D:\<256 char file name> isn't legal, even though it's under 260 chars.
internal static readonly int MaxPath = 260;
internal static readonly int MaxComponentLength = 255;
internal static readonly int MaxLongPath = short.MaxValue;
private static bool IsDirectoryOrVolumeSeparator(char c)
{
return PathInternal.IsDirectorySeparator(c) || VolumeSeparatorChar == c;
}
// Expands the given path to a fully qualified path.
[System.Security.SecuritySafeCritical]
public static string GetFullPath(string path)
{
if (path == null)
throw new ArgumentNullException("path");
string fullPath = NormalizePath(path, fullCheck: true);
// Emulate FileIOPermissions checks, retained for compatibility (normal invalid characters have already been checked)
if (PathInternal.HasAdditionalIllegalCharacters(fullPath))
throw new ArgumentException(SR.Argument_InvalidPathChars, "path");
return fullPath;
}
/// <summary>
/// Checks for known bad extended paths (paths that start with \\?\)
/// </summary>
/// <param name="fullCheck">Check for invalid characters if true.</param>
/// <returns>'true' if the path passes validity checks.</returns>
private static bool ValidateExtendedPath(string path, bool fullCheck)
{
if (path.Length == PathInternal.ExtendedPathPrefix.Length)
{
// Effectively empty and therefore invalid
return false;
}
if (path.StartsWith(PathInternal.UncExtendedPathPrefix, StringComparison.Ordinal))
{
// UNC specific checks
if (path.Length == PathInternal.UncExtendedPathPrefix.Length || path[PathInternal.UncExtendedPathPrefix.Length] == DirectorySeparatorChar)
{
// Effectively empty and therefore invalid (\\?\UNC\ or \\?\UNC\\)
return false;
}
int serverShareSeparator = path.IndexOf(DirectorySeparatorChar, PathInternal.UncExtendedPathPrefix.Length);
if (serverShareSeparator == -1 || serverShareSeparator == path.Length - 1)
{
// Need at least a Server\Share
return false;
}
}
// Segments can't be empty "\\" or contain *just* "." or ".."
char twoBack = '?';
char oneBack = DirectorySeparatorChar;
char currentCharacter;
bool periodSegment = false;
for (int i = PathInternal.ExtendedPathPrefix.Length; i < path.Length; i++)
{
currentCharacter = path[i];
switch (currentCharacter)
{
case '\\':
if (oneBack == DirectorySeparatorChar || periodSegment)
throw new ArgumentException(SR.Arg_PathIllegal);
periodSegment = false;
break;
case '.':
periodSegment = (oneBack == DirectorySeparatorChar || (twoBack == DirectorySeparatorChar && oneBack == '.'));
break;
default:
periodSegment = false;
break;
}
twoBack = oneBack;
oneBack = currentCharacter;
}
if (periodSegment)
{
return false;
}
if (fullCheck)
{
// Look for illegal path characters.
PathInternal.CheckInvalidPathChars(path);
}
return true;
}
private static string NormalizeExtendedPath(string path, bool fullCheck)
{
// If the path is in extended syntax, we don't need to normalize, but we still do some basic validity checks
if (!ValidateExtendedPath(path, fullCheck))
{
throw new ArgumentException(SR.Arg_PathIllegal);
}
// \\?\GLOBALROOT gives access to devices out of the scope of the current user, we
// don't want to allow this for security reasons.
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#nt_namespaces
if (path.StartsWith(@"\\?\globalroot", StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.Arg_PathGlobalRoot);
return path;
}
private static string NormalizePath(string path, bool fullCheck = true, bool expandShortPaths = true)
{
Debug.Assert(path != null, "path can't be null");
bool isExtended = PathInternal.IsExtended(path);
if (fullCheck)
{
// Embedded null characters are the only invalid character case we want to check up front.
// This is because the nulls will signal the end of the string to Win32 and therefore have
// unpredictable results. Other invalid characters we give a chance to be normalized out.
if (path.IndexOf('\0') != -1)
throw new ArgumentException(SR.Argument_InvalidPathChars, "path");
// Toss out paths with colons that aren't a valid drive specifier.
// Cannot start with a colon and can only be of the form "C:" or "\\?\C:".
// (Note that we used to explicitly check "http:" and "file:"- these are caught by this check now.)
int startIndex = PathInternal.PathStartSkip(path) + 2;
if (isExtended)
{
startIndex += PathInternal.ExtendedPathPrefix.Length;
}
if ((path.Length > 0 && path[0] == VolumeSeparatorChar)
|| (path.Length >= startIndex && path[startIndex - 1] == VolumeSeparatorChar && !PathInternal.IsValidDriveChar(path[startIndex - 2]))
|| (path.Length > startIndex && path.IndexOf(VolumeSeparatorChar, startIndex) != -1))
{
throw new NotSupportedException(SR.Argument_PathFormatNotSupported);
}
}
if (isExtended)
{
return NormalizeExtendedPath(path, fullCheck);
}
else
{
// Technically this doesn't matter but we used to throw for this case
if (String.IsNullOrWhiteSpace(path))
throw new ArgumentException(SR.Arg_PathIllegal);
return PathHelper.Normalize(path, fullCheck, expandShortPaths);
}
}
[System.Security.SecuritySafeCritical]
public static string GetTempPath()
{
StringBuilder sb = StringBuilderCache.Acquire(MaxPath);
uint r = Interop.mincore.GetTempPathW(MaxPath, sb);
if (r == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
return GetFullPath(StringBuilderCache.GetStringAndRelease(sb));
}
[System.Security.SecurityCritical]
private static string InternalGetTempFileName(bool checkHost)
{
// checkHost was originally intended for file security checks, but is ignored.
string path = GetTempPath();
StringBuilder sb = StringBuilderCache.Acquire(MaxPath);
uint r = Interop.mincore.GetTempFileNameW(path, "tmp", 0, sb);
if (r == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
return StringBuilderCache.GetStringAndRelease(sb);
}
// Tests if the given path contains a root. A path is considered rooted
// if it starts with a backslash ("\") or a drive letter and a colon (":").
public static bool IsPathRooted(string path)
{
if (path != null)
{
PathInternal.CheckInvalidPathChars(path);
int length = path.Length;
if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])) ||
(length >= 2 && path[1] == VolumeSeparatorChar))
return true;
}
return false;
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null.
public static string GetPathRoot(string path)
{
if (path == null) return null;
PathInternal.CheckInvalidPathChars(path);
int pathRoot = PathInternal.GetRootLength(path);
// Need to return the normalized directory separator
return pathRoot <= 0 ? string.Empty : path.Substring(0, pathRoot).Replace(AltDirectorySeparatorChar, DirectorySeparatorChar);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace Internal.IL
{
// Known shortcomings:
// - Escaping identifier names is missing (special characters and ILASM identifier names)
// - Array bounds in signatures missing
// - Custom modifiers and PINNED constraint not decoded in signatures
// - Calling conventions in signatures not decoded
// - Vararg signatures
// - Floating point numbers are not represented in roundtrippable format
/// <summary>
/// Helper struct to disassemble IL instructions into a textual representation.
/// </summary>
public struct ILDisassember
{
private byte[] _ilBytes;
private MethodIL _methodIL;
private ILTypeNameFormatter _typeNameFormatter;
private int _currentOffset;
public ILDisassember(MethodIL methodIL)
{
_methodIL = methodIL;
_ilBytes = methodIL.GetILBytes();
_currentOffset = 0;
_typeNameFormatter = null;
}
#region Type/member/signature name formatting
private ILTypeNameFormatter TypeNameFormatter
{
get
{
if (_typeNameFormatter == null)
{
// Find the owning module so that the type name formatter can remove
// redundant assembly name qualifiers in type names.
TypeDesc owningTypeDefinition = _methodIL.OwningMethod.OwningType;
ModuleDesc owningModule = owningTypeDefinition is MetadataType ?
((MetadataType)owningTypeDefinition).Module : null;
_typeNameFormatter = new ILTypeNameFormatter(owningModule);
}
return _typeNameFormatter;
}
}
public void AppendType(StringBuilder sb, TypeDesc type, bool forceValueClassPrefix = true)
{
// Types referenced from the IL show as instantiated over generic parameter.
// E.g. "initobj !0" becomes "initobj !T"
TypeDesc typeInContext = type.InstantiateSignature(
_methodIL.OwningMethod.OwningType.Instantiation, _methodIL.OwningMethod.Instantiation);
if (typeInContext.HasInstantiation || forceValueClassPrefix)
this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, typeInContext);
else
this.TypeNameFormatter.AppendName(sb, typeInContext);
}
private void AppendOwningType(StringBuilder sb, TypeDesc type)
{
// Special case primitive types: we don't want to use short names here
if (type.IsPrimitive || type.IsString || type.IsObject)
_typeNameFormatter.AppendNameForNamespaceTypeWithoutAliases(sb, (MetadataType)type);
else
AppendType(sb, type, false);
}
private void AppendMethodSignature(StringBuilder sb, MethodDesc method)
{
// If this is an instantiated generic method, the formatted signature should
// be uninstantiated (e.g. "void Foo::Bar<int>(!!0 param)", not "void Foo::Bar<int>(int param)")
MethodSignature signature = method.GetMethodDefinition().Signature;
AppendSignaturePrefix(sb, signature);
sb.Append(' ');
AppendOwningType(sb, method.OwningType);
sb.Append("::");
sb.Append(method.Name);
if (method.HasInstantiation)
{
sb.Append('<');
for (int i = 0; i < method.Instantiation.Length; i++)
{
if (i != 0)
sb.Append(", ");
_typeNameFormatter.AppendNameWithValueClassPrefix(sb, method.Instantiation[i]);
}
sb.Append('>');
}
sb.Append('(');
AppendSignatureArgumentList(sb, signature);
sb.Append(')');
}
private void AppendMethodSignature(StringBuilder sb, MethodSignature signature)
{
AppendSignaturePrefix(sb, signature);
sb.Append('(');
AppendSignatureArgumentList(sb, signature);
sb.Append(')');
}
private void AppendSignaturePrefix(StringBuilder sb, MethodSignature signature)
{
if (!signature.IsStatic)
sb.Append("instance ");
this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, signature.ReturnType);
}
private void AppendSignatureArgumentList(StringBuilder sb, MethodSignature signature)
{
for (int i = 0; i < signature.Length; i++)
{
if (i != 0)
sb.Append(", ");
this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, signature[i]);
}
}
private void AppendFieldSignature(StringBuilder sb, FieldDesc field)
{
this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, field.FieldType);
sb.Append(' ');
AppendOwningType(sb, field.OwningType);
sb.Append("::");
sb.Append(field.Name);
}
private void AppendStringLiteral(StringBuilder sb, string s)
{
sb.Append('"');
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '\\')
sb.Append("\\\\");
else if (s[i] == '\t')
sb.Append("\\t");
else if (s[i] == '"')
sb.Append("\\\"");
else if (s[i] == '\n')
sb.Append("\\n");
else
sb.Append(s[i]);
}
sb.Append('"');
}
private void AppendToken(StringBuilder sb, int token)
{
object obj = _methodIL.GetObject(token);
if (obj is MethodDesc)
AppendMethodSignature(sb, (MethodDesc)obj);
else if (obj is FieldDesc)
AppendFieldSignature(sb, (FieldDesc)obj);
else if (obj is MethodSignature)
AppendMethodSignature(sb, (MethodSignature)obj);
else if (obj is TypeDesc)
AppendType(sb, (TypeDesc)obj, false);
else
{
Debug.Assert(obj is string, "NYI: " + obj.GetType());
AppendStringLiteral(sb, (string)obj);
}
}
#endregion
#region Instruction decoding
private byte ReadILByte()
{
return _ilBytes[_currentOffset++];
}
private UInt16 ReadILUInt16()
{
UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8));
_currentOffset += 2;
return val;
}
private UInt32 ReadILUInt32()
{
UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24));
_currentOffset += 4;
return val;
}
private int ReadILToken()
{
return (int)ReadILUInt32();
}
private ulong ReadILUInt64()
{
ulong value = ReadILUInt32();
value |= (((ulong)ReadILUInt32()) << 32);
return value;
}
private unsafe float ReadILFloat()
{
uint value = ReadILUInt32();
return *(float*)(&value);
}
private unsafe double ReadILDouble()
{
ulong value = ReadILUInt64();
return *(double*)(&value);
}
public static void AppendOffset(StringBuilder sb, int offset)
{
sb.Append("IL_");
sb.AppendFormat("{0:X4}", offset);
}
private static void PadForInstructionArgument(StringBuilder sb)
{
if (sb.Length < 22)
sb.Append(' ', 22 - sb.Length);
else
sb.Append(' ');
}
public bool HasNextInstruction
{
get
{
return _currentOffset < _ilBytes.Length;
}
}
public int CodeSize
{
get
{
return _ilBytes.Length;
}
}
public string GetNextInstruction()
{
StringBuilder decodedInstruction = new StringBuilder();
AppendOffset(decodedInstruction, _currentOffset);
decodedInstruction.Append(": ");
again:
ILOpcode opCode = (ILOpcode)ReadILByte();
if (opCode == ILOpcode.prefix1)
{
opCode = (ILOpcode)(0x100 + ReadILByte());
}
// Quick and dirty way to get the opcode name is to convert the enum value to string.
// We need some adjustments though.
string opCodeString = opCode.ToString().Replace("_", ".");
if (opCodeString.EndsWith("."))
opCodeString = opCodeString.Substring(0, opCodeString.Length - 1);
decodedInstruction.Append(opCodeString);
switch (opCode)
{
case ILOpcode.ldarg_s:
case ILOpcode.ldarga_s:
case ILOpcode.starg_s:
case ILOpcode.ldloc_s:
case ILOpcode.ldloca_s:
case ILOpcode.stloc_s:
case ILOpcode.ldc_i4_s:
PadForInstructionArgument(decodedInstruction);
decodedInstruction.Append(ReadILByte().ToStringInvariant());
return decodedInstruction.ToString();
case ILOpcode.unaligned:
decodedInstruction.Append(' ');
decodedInstruction.Append(ReadILByte().ToStringInvariant());
decodedInstruction.Append(' ');
goto again;
case ILOpcode.ldarg:
case ILOpcode.ldarga:
case ILOpcode.starg:
case ILOpcode.ldloc:
case ILOpcode.ldloca:
case ILOpcode.stloc:
PadForInstructionArgument(decodedInstruction);
decodedInstruction.Append(ReadILUInt16().ToStringInvariant());
return decodedInstruction.ToString();
case ILOpcode.ldc_i4:
PadForInstructionArgument(decodedInstruction);
decodedInstruction.Append(ReadILUInt32().ToStringInvariant());
return decodedInstruction.ToString();
case ILOpcode.ldc_r4:
PadForInstructionArgument(decodedInstruction);
decodedInstruction.Append(ReadILFloat().ToStringInvariant());
return decodedInstruction.ToString();
case ILOpcode.ldc_i8:
PadForInstructionArgument(decodedInstruction);
decodedInstruction.Append(ReadILUInt64().ToStringInvariant());
return decodedInstruction.ToString();
case ILOpcode.ldc_r8:
PadForInstructionArgument(decodedInstruction);
decodedInstruction.Append(ReadILDouble().ToStringInvariant());
return decodedInstruction.ToString();
case ILOpcode.jmp:
case ILOpcode.call:
case ILOpcode.calli:
case ILOpcode.callvirt:
case ILOpcode.cpobj:
case ILOpcode.ldobj:
case ILOpcode.ldstr:
case ILOpcode.newobj:
case ILOpcode.castclass:
case ILOpcode.isinst:
case ILOpcode.unbox:
case ILOpcode.ldfld:
case ILOpcode.ldflda:
case ILOpcode.stfld:
case ILOpcode.ldsfld:
case ILOpcode.ldsflda:
case ILOpcode.stsfld:
case ILOpcode.stobj:
case ILOpcode.box:
case ILOpcode.newarr:
case ILOpcode.ldelema:
case ILOpcode.ldelem:
case ILOpcode.stelem:
case ILOpcode.unbox_any:
case ILOpcode.refanyval:
case ILOpcode.mkrefany:
case ILOpcode.ldtoken:
case ILOpcode.ldftn:
case ILOpcode.ldvirtftn:
case ILOpcode.initobj:
case ILOpcode.constrained:
case ILOpcode.sizeof_:
PadForInstructionArgument(decodedInstruction);
AppendToken(decodedInstruction, ReadILToken());
return decodedInstruction.ToString();
case ILOpcode.br_s:
case ILOpcode.leave_s:
case ILOpcode.brfalse_s:
case ILOpcode.brtrue_s:
case ILOpcode.beq_s:
case ILOpcode.bge_s:
case ILOpcode.bgt_s:
case ILOpcode.ble_s:
case ILOpcode.blt_s:
case ILOpcode.bne_un_s:
case ILOpcode.bge_un_s:
case ILOpcode.bgt_un_s:
case ILOpcode.ble_un_s:
case ILOpcode.blt_un_s:
PadForInstructionArgument(decodedInstruction);
AppendOffset(decodedInstruction, (sbyte)ReadILByte() + _currentOffset);
return decodedInstruction.ToString();
case ILOpcode.br:
case ILOpcode.leave:
case ILOpcode.brfalse:
case ILOpcode.brtrue:
case ILOpcode.beq:
case ILOpcode.bge:
case ILOpcode.bgt:
case ILOpcode.ble:
case ILOpcode.blt:
case ILOpcode.bne_un:
case ILOpcode.bge_un:
case ILOpcode.bgt_un:
case ILOpcode.ble_un:
case ILOpcode.blt_un:
PadForInstructionArgument(decodedInstruction);
AppendOffset(decodedInstruction, (int)ReadILUInt32() + _currentOffset);
return decodedInstruction.ToString();
case ILOpcode.switch_:
{
decodedInstruction.Clear();
decodedInstruction.Append("switch (");
uint count = ReadILUInt32();
int jmpBase = _currentOffset + (int)(4 * count);
for (uint i = 0; i < count; i++)
{
if (i != 0)
decodedInstruction.Append(", ");
int delta = (int)ReadILUInt32();
AppendOffset(decodedInstruction, jmpBase + delta);
}
decodedInstruction.Append(")");
return decodedInstruction.ToString();
}
default:
return decodedInstruction.ToString();
}
}
#endregion
#region Helpers
private class ILTypeNameFormatter : TypeNameFormatter
{
private ModuleDesc _thisModule;
public ILTypeNameFormatter(ModuleDesc thisModule)
{
_thisModule = thisModule;
}
public void AppendNameWithValueClassPrefix(StringBuilder sb, TypeDesc type)
{
if (!type.IsSignatureVariable
&& type.IsDefType
&& !type.IsPrimitive
&& !type.IsObject
&& !type.IsString)
{
string prefix = type.IsValueType ? "valuetype " : "class ";
sb.Append(prefix);
AppendName(sb, type);
}
else
{
AppendName(sb, type);
}
}
public override void AppendName(StringBuilder sb, PointerType type)
{
AppendNameWithValueClassPrefix(sb, type.ParameterType);
sb.Append('*');
}
public override void AppendName(StringBuilder sb, FunctionPointerType type)
{
MethodSignature signature = type.Signature;
sb.Append("method ");
if (!signature.IsStatic)
sb.Append("instance ");
// TODO: rest of calling conventions
AppendName(sb, signature.ReturnType);
sb.Append(" *(");
for (int i = 0; i < signature.Length; i++)
{
if (i > 0)
sb.Append(", ");
AppendName(sb, signature[i]);
}
sb.Append(')');
}
public override void AppendName(StringBuilder sb, SignatureMethodVariable type)
{
sb.Append("!!");
sb.Append(type.Index.ToStringInvariant());
}
public override void AppendName(StringBuilder sb, SignatureTypeVariable type)
{
sb.Append("!");
sb.Append(type.Index.ToStringInvariant());
}
public override void AppendName(StringBuilder sb, GenericParameterDesc type)
{
string prefix = type.Kind == GenericParameterKind.Type ? "!" : "!!";
sb.Append(prefix);
sb.Append(type.Name);
}
protected override void AppendNameForInstantiatedType(StringBuilder sb, DefType type)
{
AppendName(sb, type.GetTypeDefinition());
sb.Append('<');
for (int i = 0; i < type.Instantiation.Length; i++)
{
if (i > 0)
sb.Append(", ");
AppendNameWithValueClassPrefix(sb, type.Instantiation[i]);
}
sb.Append('>');
}
public override void AppendName(StringBuilder sb, ByRefType type)
{
AppendNameWithValueClassPrefix(sb, type.ParameterType);
sb.Append('&');
}
public override void AppendName(StringBuilder sb, ArrayType type)
{
AppendNameWithValueClassPrefix(sb, type.ElementType);
sb.Append('[');
sb.Append(',', type.Rank - 1);
sb.Append(']');
}
protected override void AppendNameForNamespaceType(StringBuilder sb, DefType type)
{
switch (type.Category)
{
case TypeFlags.Void:
sb.Append("void");
return;
case TypeFlags.Boolean:
sb.Append("bool");
return;
case TypeFlags.Char:
sb.Append("char");
return;
case TypeFlags.SByte:
sb.Append("int8");
return;
case TypeFlags.Byte:
sb.Append("uint8");
return;
case TypeFlags.Int16:
sb.Append("int16");
return;
case TypeFlags.UInt16:
sb.Append("uint16");
return;
case TypeFlags.Int32:
sb.Append("int32");
return;
case TypeFlags.UInt32:
sb.Append("uint32");
return;
case TypeFlags.Int64:
sb.Append("int64");
return;
case TypeFlags.UInt64:
sb.Append("uint64");
return;
case TypeFlags.IntPtr:
sb.Append("native int");
return;
case TypeFlags.UIntPtr:
sb.Append("native uint");
return;
case TypeFlags.Single:
sb.Append("float32");
return;
case TypeFlags.Double:
sb.Append("float64");
return;
}
if (type.IsString)
{
sb.Append("string");
return;
}
if (type.IsObject)
{
sb.Append("object");
return;
}
AppendNameForNamespaceTypeWithoutAliases(sb, type);
}
public void AppendNameForNamespaceTypeWithoutAliases(StringBuilder sb, DefType type)
{
ModuleDesc owningModule = (type as MetadataType)?.Module;
if (owningModule != null && owningModule != _thisModule)
{
Debug.Assert(owningModule is IAssemblyDesc);
string owningModuleName = ((IAssemblyDesc)owningModule).GetName().Name;
sb.Append('[');
sb.Append(owningModuleName);
sb.Append(']');
}
string ns = type.Namespace;
if (ns.Length > 0)
{
sb.Append(ns);
sb.Append('.');
}
sb.Append(type.Name);
}
protected override void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType)
{
AppendName(sb, containingType);
sb.Append('/');
sb.Append(nestedType.Name);
}
}
#endregion
}
}
| |
using System.Globalization;
namespace Lucene.Net.Util
{
/*
* 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.
*/
public static class CultureInfoSupport
{
#if !FEATURE_CULTUREINFO_GETCULTURES
#region culturePool
private static readonly string[] specificCulturePool =
{
"fr-KM",
"fr-LU",
"fr-MA",
"fr-MC",
"fr-MF",
"fr-MG",
"fr-ML",
"fr-MQ",
"fr-MR",
"fr-MU",
"fr-NC",
"fr-NE",
"fr-PF",
"fr-PM",
"fr-RE",
"fr-RW",
"fr-SC",
"fr-SN",
"fr-SY",
"fr-TD",
"fr-TG",
"fr-TN",
"fr-VU",
"fr-WF",
"fr-YT",
"fur-IT",
"fy-NL",
"ga-IE",
"gd-GB",
"gl-ES",
"gn-PY",
"gsw-CH",
"gsw-FR",
"gsw-LI",
"gu-IN",
"guz-KE",
"gv-IM",
"ha-Latn-GH",
"ha-Latn-NE",
"ha-Latn-NG",
"haw-US",
"he-IL",
"hi-IN",
"hr-BA",
"hr-HR",
"hsb-DE",
"hu-HU",
"hy-AM",
"ia-001",
"ia-FR",
"ibb-NG",
"id-ID",
"ig-NG",
"ii-CN",
"is-IS",
"it-CH",
"it-IT",
"it-SM",
"iu-Cans-CA",
"iu-Latn-CA",
"ja-JP",
"jgo-CM",
"jmc-TZ",
"jv-Java-ID",
"jv-Latn-ID",
"ka-GE",
"kab-DZ",
"kam-KE",
"kde-TZ",
"kea-CV",
"khq-ML",
"ki-KE",
"kk-KZ",
"kkj-CM",
"kl-GL",
"kln-KE",
"km-KH",
"kn-IN",
"ko-KP",
"ko-KR",
"kok-IN",
"kr-NG",
"ks-Arab-IN",
"ks-Deva-IN",
"ksb-TZ",
"ksf-CM",
"ksh-DE",
"ku-Arab-IQ",
"ku-Arab-IR",
"kw-GB",
"ky-KG",
"la-001",
"lag-TZ",
"lb-LU",
"lg-UG",
"lkt-US",
"ln-AO",
"ln-CD",
"ln-CF",
"ln-CG",
"lo-LA",
"lrc-IQ",
"lrc-IR",
"lt-LT",
"lu-CD",
"luo-KE",
"luy-KE",
"lv-LV",
"mas-KE",
"mas-TZ",
"mer-KE",
"mfe-MU",
"mg-MG",
"mgh-MZ",
"mgo-CM",
"mi-NZ",
"mk-MK",
"ml-IN",
"mn-MN",
"mn-Mong-CN",
"mn-Mong-MN",
"mni-IN",
"moh-CA",
"mr-IN",
"ms-BN",
"ms-MY",
"ms-SG",
"mt-MT",
"mua-CM",
"my-MM",
"mzn-IR",
"naq-NA",
"nb-NO",
"nb-SJ",
"nd-ZW",
"ne-IN",
"ne-NP",
"nl-AW",
"nl-BE",
"nl-BQ",
"nl-CW",
"nl-NL",
"nl-SR",
"nl-SX",
"nmg-CM",
"nn-NO",
"nnh-CM",
"nqo-GN",
"nr-ZA",
"nso-ZA",
"nus-SS",
"nyn-UG",
"oc-FR",
"om-ET",
"om-KE",
"or-IN",
"os-GE",
"os-RU",
"pa-Arab-PK",
"pa-IN",
"pap-029",
"pl-PL",
"prg-001",
"prs-AF",
"ps-AF",
"pt-AO",
"pt-BR",
"pt-CV",
"pt-GW",
"pt-MO",
"pt-MZ",
"pt-PT",
"pt-ST",
"pt-TL",
"quc-Latn-GT",
"quz-BO",
"quz-EC",
"quz-PE",
"rm-CH",
"rn-BI",
"ro-MD",
"ro-RO",
"rof-TZ",
"ru-BY",
"ru-KG",
"ru-KZ",
"ru-MD",
"ru-RU",
"ru-UA",
"rw-RW",
"rwk-TZ",
"sa-IN",
"sah-RU",
"saq-KE",
"sbp-TZ",
"sd-Arab-PK",
"sd-Deva-IN",
"se-FI",
"se-NO",
"se-SE",
"seh-MZ",
"ses-ML",
"sg-CF",
"shi-Latn-MA",
"shi-Tfng-MA",
"si-LK",
"sk-SK",
"sl-SI",
"sma-NO",
"sma-SE",
"smj-NO",
"smj-SE",
"smn-FI",
"sms-FI",
"sn-Latn-ZW",
"so-DJ",
"so-ET",
"so-KE",
"so-SO",
"sq-AL",
"sq-MK",
"sq-XK",
"sr-Cyrl-BA",
"sr-Cyrl-ME",
"sr-Cyrl-RS",
"sr-Cyrl-XK",
"sr-Latn-BA",
"sr-Latn-ME",
"sr-Latn-RS",
"sr-Latn-XK",
"ss-SZ",
"ss-ZA",
"ssy-ER",
"st-LS",
"st-ZA",
"sv-AX",
"sv-FI",
"sv-SE",
"sw-CD",
"sw-KE",
"sw-TZ",
"sw-UG",
"syr-SY",
"ta-IN",
"ta-LK",
"ta-MY",
"ta-SG",
"te-IN",
"teo-KE",
"teo-UG",
"tg-Cyrl-TJ",
"th-TH",
"ti-ER",
"ti-ET",
"tig-ER",
"tk-TM",
"tn-BW",
"tn-ZA",
"to-TO",
"tr-CY",
"tr-TR",
"ts-ZA",
"tt-RU",
"twq-NE",
"tzm-Arab-MA",
"tzm-Latn-DZ",
"tzm-Latn-MA",
"tzm-Tfng-MA",
"ug-CN",
"uk-UA",
"ur-IN",
"ur-PK",
"uz-Arab-AF",
"uz-Cyrl-UZ",
"uz-Latn-UZ",
"vai-Latn-LR",
"vai-Vaii-LR",
"ve-ZA",
"vi-VN",
"vo-001",
"vun-TZ",
"wae-CH",
"wal-ET",
"wo-SN",
"xh-ZA",
"xog-UG",
"yav-CM",
"yi-001",
"yo-BJ",
"yo-NG",
"zgh-Tfng-MA",
"zh-CN",
"zh-Hans-HK",
"zh-Hans-MO",
"zh-HK",
"zh-MO",
"zh-SG",
"zh-TW",
"zu-ZA"
};
private static readonly string[] neutralCulturePool =
{
"aa",
"af",
"agq",
"ak",
"am",
"ar",
"arn",
"as",
"asa",
"ast",
"az",
"az-Cyrl",
"az-Latn",
"ba",
"bas",
"be",
"bem",
"bez",
"bg",
"bin",
"bm",
"bm-Latn",
"bn",
"bo",
"br",
"brx",
"bs",
"bs-Cyrl",
"bs-Latn",
"byn",
"ca",
"ce",
"cgg",
"chr",
"chr-Cher",
"co",
"cs",
"cu",
"cy",
"da",
"dav",
"de",
"dje",
"dsb",
"dua",
"dv",
"dyo",
"dz",
"ebu",
"ee",
"el",
"en",
"eo",
"es",
"et",
"eu",
"ewo",
"fa",
"ff",
"ff-Latn",
"fi",
"fil",
"fo",
"fr",
"fur",
"fy",
"ga",
"gd",
"gl",
"gn",
"gsw",
"gu",
"guz",
"gv",
"ha",
"ha-Latn",
"haw",
"he",
"hi",
"hr",
"hsb",
"hu",
"hy",
"ia",
"ibb",
"id",
"ig",
"ii",
"is",
"it",
"iu",
"iu-Cans",
"iu-Latn",
"ja",
"jgo",
"jmc",
"jv",
"jv-Java",
"jv-Latn",
"ka",
"kab",
"kam",
"kde",
"kea",
"khq",
"ki",
"kk",
"kkj",
"kl",
"kln",
"km",
"kn",
"ko",
"kok",
"kr",
"ks",
"ks-Arab",
"ks-Deva",
"ksb",
"ksf",
"ksh",
"ku",
"ku-Arab",
"kw",
"ky",
"la",
"lag",
"lb",
"lg",
"lkt",
"ln",
"lo",
"lrc",
"lt",
"lu",
"luo",
"luy",
"lv",
"mas",
"mer",
"mfe",
"mg",
"mgh",
"mgo",
"mi",
"mk",
"ml",
"mn",
"mn-Cyrl",
"mn-Mong",
"mni",
"moh",
"mr",
"ms",
"mt",
"mua",
"my",
"mzn",
"naq",
"nb",
"nd",
"ne",
"nl",
"nmg",
"nn",
"nnh",
"no",
"nqo",
"nr",
"nso",
"nus",
"nyn",
"oc",
"om",
"or",
"os",
"pa",
"pa-Arab",
"pap",
"pl",
"prg",
"prs",
"ps",
"pt",
"quc",
"quc-Latn",
"quz",
"rm",
"rn",
"ro",
"rof",
"ru",
"rw",
"rwk",
"sa",
"sah",
"saq",
"sbp",
"sd",
"sd-Arab",
"sd-Deva",
"se",
"seh",
"ses",
"sg",
"shi",
"shi-Latn",
"shi-Tfng",
"si",
"sk",
"sl",
"sma",
"smj",
"smn",
"sms",
"sn",
"sn-Latn",
"so",
"sq",
"sr",
"sr-Cyrl",
"sr-Latn",
"ss",
"ssy",
"st",
"sv",
"sw",
"syr",
"ta",
"te",
"teo",
"tg",
"tg-Cyrl",
"th",
"ti",
"tig",
"tk",
"tn",
"to",
"tr",
"ts",
"tt",
"twq",
"tzm",
"tzm-Arab",
"tzm-Latn",
"tzm-Tfng",
"ug",
"uk",
"ur",
"uz",
"uz-Arab",
"uz-Cyrl",
"uz-Latn",
"vai",
"vai-Latn",
"vai-Vaii",
"ve",
"vi",
"vo",
"vun",
"wae",
"wal",
"wo",
"xh",
"xog",
"yav",
"yi",
"yo",
"zgh",
"zgh-Tfng",
"zh",
"zh-Hans",
"zh-Hant",
"zu",
"zh-CHS",
"zh-CHT"
};
#endregion culturePool
private static readonly CultureInfo[] supportedSpecificCultures = LoadSupportedCultures(specificCulturePool);
private static readonly CultureInfo[] supportedNeutralCultures = LoadSupportedCultures(neutralCulturePool);
private static CultureInfo[] LoadSupportedCultures(string[] culturePool)
{
var cultures = new List<CultureInfo>();
foreach (var culture in culturePool)
{
try
{
cultures.Add(new CultureInfo(culture));
}
catch (Exception)
{
// ignore
}
}
return cultures.ToArray();
}
#endif
public static CultureInfo[] GetNeutralAndSpecificCultures()
{
#if !FEATURE_CULTUREINFO_GETCULTURES
return supportedSpecificCultures.Union(supportedNeutralCultures).ToArray();
#else
return CultureInfo.GetCultures(CultureTypes.SpecificCultures | CultureTypes.NeutralCultures);
#endif
}
}
}
| |
#region MIT license
//
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#endregion
using System;
using System.Data;
using System.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
using DbLinq.Data.Linq.SqlClient;
using DbLinq.Util;
using DbLinq.Vendor;
#if MONO_STRICT
using DataContext = System.Data.Linq.DataContext;
#else
using DataContext = DbLinq.Data.Linq.DataContext;
#endif
namespace DbLinq.Ingres
{
/// <summary>
/// Ingres - specific code.
/// </summary>
[Vendor(typeof(IngresProvider))]
#if !MONO_STRICT
public
#endif
class IngresVendor : Vendor.Implementation.Vendor
{
public override string VendorName { get { return "Ingres"; } }
protected readonly IngresSqlProvider sqlProvider = new IngresSqlProvider();
public override ISqlProvider SqlProvider { get { return sqlProvider; } }
//private string lastIdExpression = null;
private bool isReplaceable(IDbDataParameter param)
{
switch (param.DbType)
{
case DbType.String:
case DbType.Int16:
case DbType.Int32:
case DbType.Int64:
case DbType.Double:
return true;
}
return false;
}
private string getParamValueAsString(IDbDataParameter param)
{
switch (param.DbType)
{
case DbType.String:
return " '" + param.Value.ToString() + "' ";
case DbType.Int16:
case DbType.Int32:
case DbType.Int64:
case DbType.Double:
return param.Value.ToString();
}
throw new Exception("Not prepared to convert " + param.DbType.ToString());
}
protected void SetParameterType(IDbDataParameter parameter, PropertyInfo property, string literal)
{
object dbType = Enum.Parse(property.PropertyType, literal);
property.GetSetMethod().Invoke(parameter, new object[] { dbType });
}
protected void SetParameterType(IDbDataParameter parameter, string literal)
{
SetParameterType(parameter, parameter.GetType().GetProperty("IngresDbType"), literal);
}
/// <summary>
/// call mysql stored proc or stored function,
/// optionally return DataSet, and collect return params.
/// </summary>
public override System.Data.Linq.IExecuteResult ExecuteMethodCall(DataContext context, MethodInfo method
, params object[] inputValues)
{
if (method == null)
throw new ArgumentNullException("L56 Null 'method' parameter");
//check to make sure there is exactly one [FunctionEx]? that's below.
//FunctionAttribute functionAttrib = GetFunctionAttribute(method);
var functionAttrib = context.Mapping.GetFunction(method);
ParameterInfo[] paramInfos = method.GetParameters();
//int numRequiredParams = paramInfos.Count(p => p.IsIn || p.IsRetval);
//if (numRequiredParams != inputValues.Length)
// throw new ArgumentException("L161 Argument count mismatch");
string sp_name = functionAttrib.MappedName;
using (IDbCommand command = context.Connection.CreateCommand())
{
command.CommandText = sp_name;
//MySqlCommand command = new MySqlCommand("select hello0()");
int currInputIndex = 0;
List<string> paramNames = new List<string>();
for (int i = 0; i < paramInfos.Length; i++)
{
ParameterInfo paramInfo = paramInfos[i];
//TODO: check to make sure there is exactly one [Parameter]?
ParameterAttribute paramAttrib = paramInfo.GetCustomAttributes(false).OfType<ParameterAttribute>().Single();
//string paramName = "?" + paramAttrib.Name; //eg. '?param1' MYSQL
string paramName = ":" + paramAttrib.Name; //eg. '?param1' PostgreSQL
paramNames.Add(paramName);
System.Data.ParameterDirection direction = GetDirection(paramInfo, paramAttrib);
//MySqlDbType dbType = MySqlTypeConversions.ParseType(paramAttrib.DbType);
IDbDataParameter cmdParam = command.CreateParameter();
cmdParam.ParameterName = paramName;
//cmdParam.Direction = System.Data.ParameterDirection.Input;
if (direction == ParameterDirection.Input || direction == ParameterDirection.InputOutput)
{
object inputValue = inputValues[currInputIndex++];
cmdParam.Value = inputValue;
}
else
{
cmdParam.Value = null;
}
cmdParam.Direction = direction;
command.Parameters.Add(cmdParam);
}
if (!functionAttrib.IsComposable)
{
//procedures: under the hood, this seems to prepend 'CALL '
command.CommandType = System.Data.CommandType.StoredProcedure;
}
else
{
//functions: 'SELECT myFunction()' or 'SELECT hello(?s)'
string cmdText = "SELECT " + command.CommandText + "($args)";
cmdText = cmdText.Replace("$args", string.Join(",", paramNames.ToArray()));
command.CommandText = cmdText;
}
if (method.ReturnType == typeof(DataSet))
{
//unknown shape of resultset:
System.Data.DataSet dataSet = new DataSet();
IDbDataAdapter adapter = CreateDataAdapter(context);
adapter.SelectCommand = command;
adapter.Fill(dataSet);
List<object> outParamValues = CopyOutParams(paramInfos, command.Parameters);
return new ProcedureResult(dataSet, outParamValues.ToArray());
}
else
{
object obj = command.ExecuteScalar();
List<object> outParamValues = CopyOutParams(paramInfos, command.Parameters);
return new ProcedureResult(obj, outParamValues.ToArray());
}
}
}
static ParameterDirection GetDirection(ParameterInfo paramInfo, ParameterAttribute paramAttrib)
{
//strange hack to determine what's a ref, out parameter:
//http://lists.ximian.com/pipermain/mono-list/2003-March/012751.html
bool hasAmpersand = paramInfo.ParameterType.FullName.Contains('&');
if (paramInfo.IsOut)
return ParameterDirection.Output;
if (hasAmpersand)
return ParameterDirection.InputOutput;
return ParameterDirection.Input;
}
/// <summary>
/// Collect all Out or InOut param values, casting them to the correct .net type.
/// </summary>
static List<object> CopyOutParams(ParameterInfo[] paramInfos, IDataParameterCollection paramSet)
{
List<object> outParamValues = new List<object>();
//Type type_t = typeof(T);
int i = -1;
foreach (IDbDataParameter param in paramSet)
{
i++;
if (param.Direction == ParameterDirection.Input)
{
outParamValues.Add("unused");
continue;
}
object val = param.Value;
Type desired_type = paramInfos[i].ParameterType;
if (desired_type.Name.EndsWith("&"))
{
//for ref and out parameters, we need to tweak ref types, e.g.
// "System.Int32&, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
string fullName1 = desired_type.AssemblyQualifiedName;
string fullName2 = fullName1.Replace("&", "");
desired_type = Type.GetType(fullName2);
}
try
{
//fi.SetValue(t, val); //fails with 'System.Decimal cannot be converted to Int32'
//DbLinq.util.FieldUtils.SetObjectIdField(t, fi, val);
//object val2 = DbLinq.Util.FieldUtils.CastValue(val, desired_type);
object val2 = TypeConvert.To(val, desired_type);
outParamValues.Add(val2);
}
catch (Exception ex)
{
//fails with 'System.Decimal cannot be converted to Int32'
Console.WriteLine("CopyOutParams ERROR L245: failed on CastValue(): " + ex.Message);
}
}
return outParamValues;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Lexemes.cs" company="Hukano">
// Copyright (c) Hukano. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Sundew.Quantities.Parsing.LexicalAnalysis;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
/// <summary>
/// Contains <see cref="Lexeme"/>s for a parser.
/// </summary>
public sealed class Lexemes : IEnumerable<Lexeme>
{
private LinkedListNode<Lexeme> currentLexeme;
/// <summary>
/// Initializes a new instance of the <see cref="Lexemes"/> class.
/// </summary>
/// <param name="lexemes">The lexemes.</param>
public Lexemes(LinkedList<Lexeme> lexemes)
{
this.currentLexeme = lexemes.First;
}
/// <summary>
/// Gets the current.
/// </summary>
/// <value>
/// The current.
/// </value>
public Lexeme Current => this.currentLexeme?.Value;
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns>An <see cref="IEnumerator{Lexeme}"/>.</returns>
public IEnumerator<Lexeme> GetEnumerator()
{
return this.currentLexeme.List.GetEnumerator();
}
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns>An <see cref="IEnumerator"/>.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Accepts the token from.
/// </summary>
/// <param name="tokenRegex">The token regex.</param>
/// <param name="token">The token.</param>
/// <returns>
/// <c>true</c> if the specified token regex matches the token, otherwise <c>false</c>.
/// </returns>
public bool AcceptTokenFrom(Regex tokenRegex, out string token)
{
return this.AcceptTokenFrom(tokenRegex, true, out token);
}
/// <summary>
/// Accepts the token from a regex.
/// </summary>
/// <param name="tokenRegex">The token regex.</param>
/// <param name="ignoreWhiteSpace">if set to <c>true</c> white space will be ignored.</param>
/// <param name="token">The token.</param>
/// <returns>
/// <c>true</c> if the specified token regex matches the token, otherwise <c>false</c>.
/// </returns>
public bool AcceptTokenFrom(Regex tokenRegex, bool ignoreWhiteSpace, out string token)
{
var ignoredWhiteSpace = this.TryIgnoreWhiteSpace(ignoreWhiteSpace, this.Current);
var match = tokenRegex.Match(this.Current.Token);
if (match.Success)
{
token = match.Value;
this.MoveToNext();
return true;
}
if (ignoredWhiteSpace)
{
this.MoveToPrevious();
}
token = null;
return false;
}
/// <summary>
/// Accepts the token from a registry.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="possibleTokens">The possible tokens.</param>
/// <param name="result">The result.</param>
/// <returns><c>true</c> if the specified lexeme registry contains the token, otherwise <c>false</c>.</returns>
public bool AcceptTokenFrom<TResult>(ILexemeRegistry<TResult> possibleTokens, out TResult result)
{
return this.AcceptTokenFrom(possibleTokens, true, out result);
}
/// <summary>
/// Accepts the token from.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="possibleTokens">The possible tokens.</param>
/// <param name="ignoreWhiteSpace">if set to <c>true</c> white space will be ignored.</param>
/// <param name="result">The result.</param>
/// <returns>
/// <c>true</c> if the token was accepted, otherwise <c>false</c>.
/// </returns>
public bool AcceptTokenFrom<TResult>(
ILexemeRegistry<TResult> possibleTokens,
bool ignoreWhiteSpace,
out TResult result)
{
var ignoredWhiteSpace = this.TryIgnoreWhiteSpace(ignoreWhiteSpace, this.Current);
if (possibleTokens.TryGet(this.Current.Token, out result))
{
this.MoveToNext();
return true;
}
if (ignoredWhiteSpace)
{
this.MoveToPrevious();
}
return false;
}
/// <summary>
/// Accepts the token.
/// </summary>
/// <param name="token">The token.</param>
/// <param name="ignoreWhiteSpace">if set to <c>true</c> white space will be ignored.</param>
/// <returns>
/// <c>true</c> if the specified token is accepted, otherwise <c>false</c>.
/// </returns>
public bool AcceptToken(string token, bool ignoreWhiteSpace = true)
{
var ignoredWhiteSpace = this.TryIgnoreWhiteSpace(ignoreWhiteSpace, this.Current);
if (this.Current.Token == token)
{
this.MoveToNext();
return true;
}
if (ignoredWhiteSpace)
{
this.MoveToPrevious();
}
return false;
}
/// <summary>
/// Accepts the type of the token.
/// </summary>
/// <param name="tokenType">Type of the token.</param>
/// <returns>
/// <c>true</c> if the specified token type is accepted, otherwise <c>false</c>.
/// </returns>
public bool AcceptTokenType(TokenType tokenType)
{
return this.AcceptTokenType(tokenType, true, out _);
}
/// <summary>
/// Accepts the type of the token.
/// </summary>
/// <param name="tokenType">Type of the token.</param>
/// <param name="token">The token.</param>
/// <returns><c>true</c> if the specified token type is accepted, otherwise <c>false</c>.</returns>
public bool AcceptTokenType(TokenType tokenType, out string token)
{
return this.AcceptTokenType(tokenType, true, out token);
}
/// <summary>
/// Accepts the type of the token.
/// </summary>
/// <param name="tokenType">Type of the token.</param>
/// <param name="ignoreWhiteSpace">if set to <c>true</c> white space will be ignored.</param>
/// <param name="token">The token.</param>
/// <returns><c>true</c> if the specified token type is accepted, otherwise <c>false</c>.</returns>
public bool AcceptTokenType(TokenType tokenType, bool ignoreWhiteSpace, out string token)
{
if (tokenType == TokenType.WhiteSpace)
{
ignoreWhiteSpace = false;
}
var ignoredWhiteSpace = this.TryIgnoreWhiteSpace(ignoreWhiteSpace, this.Current);
var lexeme = this.Current;
if (lexeme.TokenType == tokenType)
{
token = lexeme.Token;
this.MoveToNext();
return true;
}
if (ignoredWhiteSpace)
{
this.MoveToPrevious();
}
token = null;
return false;
}
/// <summary>
/// Moves to previous.
/// </summary>
/// <returns>The previous <see cref="Lexeme"/>.</returns>
public Lexeme MoveToPrevious()
{
this.currentLexeme = this.currentLexeme.Previous;
return this.currentLexeme.Value;
}
private bool TryIgnoreWhiteSpace(bool ignoreWhiteSpace, Lexeme lexeme)
{
if (ignoreWhiteSpace && lexeme.TokenType == TokenType.WhiteSpace)
{
this.MoveToNext();
return true;
}
return false;
}
private void MoveToNext()
{
this.currentLexeme = this.currentLexeme.Next;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/privacy/dlp/v2beta1/dlp.proto
// Original file comments:
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Google.Cloud.Dlp.V2Beta1 {
/// <summary>
/// The DLP API is a service that allows clients
/// to detect the presence of Personally Identifiable Information (PII) and other
/// privacy-sensitive data in user-supplied, unstructured data streams, like text
/// blocks or images.
/// The service also includes methods for sensitive data redaction and
/// scheduling of data scans on Google Cloud Platform based data sets.
/// </summary>
public static partial class DlpService
{
static readonly string __ServiceName = "google.privacy.dlp.v2beta1.DlpService";
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.InspectContentRequest> __Marshaller_InspectContentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.InspectContentRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.InspectContentResponse> __Marshaller_InspectContentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.InspectContentResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.RedactContentRequest> __Marshaller_RedactContentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.RedactContentRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.RedactContentResponse> __Marshaller_RedactContentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.RedactContentResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentRequest> __Marshaller_DeidentifyContentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentResponse> __Marshaller_DeidentifyContentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.CreateInspectOperationRequest> __Marshaller_CreateInspectOperationRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.CreateInspectOperationRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.LongRunning.Operation> __Marshaller_Operation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.Operation.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.AnalyzeDataSourceRiskRequest> __Marshaller_AnalyzeDataSourceRiskRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.AnalyzeDataSourceRiskRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsRequest> __Marshaller_ListInspectFindingsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsResponse> __Marshaller_ListInspectFindingsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesRequest> __Marshaller_ListInfoTypesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesResponse> __Marshaller_ListInfoTypesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesRequest> __Marshaller_ListRootCategoriesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesResponse> __Marshaller_ListRootCategoriesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesResponse.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Cloud.Dlp.V2Beta1.InspectContentRequest, global::Google.Cloud.Dlp.V2Beta1.InspectContentResponse> __Method_InspectContent = new grpc::Method<global::Google.Cloud.Dlp.V2Beta1.InspectContentRequest, global::Google.Cloud.Dlp.V2Beta1.InspectContentResponse>(
grpc::MethodType.Unary,
__ServiceName,
"InspectContent",
__Marshaller_InspectContentRequest,
__Marshaller_InspectContentResponse);
static readonly grpc::Method<global::Google.Cloud.Dlp.V2Beta1.RedactContentRequest, global::Google.Cloud.Dlp.V2Beta1.RedactContentResponse> __Method_RedactContent = new grpc::Method<global::Google.Cloud.Dlp.V2Beta1.RedactContentRequest, global::Google.Cloud.Dlp.V2Beta1.RedactContentResponse>(
grpc::MethodType.Unary,
__ServiceName,
"RedactContent",
__Marshaller_RedactContentRequest,
__Marshaller_RedactContentResponse);
static readonly grpc::Method<global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentRequest, global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentResponse> __Method_DeidentifyContent = new grpc::Method<global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentRequest, global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentResponse>(
grpc::MethodType.Unary,
__ServiceName,
"DeidentifyContent",
__Marshaller_DeidentifyContentRequest,
__Marshaller_DeidentifyContentResponse);
static readonly grpc::Method<global::Google.Cloud.Dlp.V2Beta1.CreateInspectOperationRequest, global::Google.LongRunning.Operation> __Method_CreateInspectOperation = new grpc::Method<global::Google.Cloud.Dlp.V2Beta1.CreateInspectOperationRequest, global::Google.LongRunning.Operation>(
grpc::MethodType.Unary,
__ServiceName,
"CreateInspectOperation",
__Marshaller_CreateInspectOperationRequest,
__Marshaller_Operation);
static readonly grpc::Method<global::Google.Cloud.Dlp.V2Beta1.AnalyzeDataSourceRiskRequest, global::Google.LongRunning.Operation> __Method_AnalyzeDataSourceRisk = new grpc::Method<global::Google.Cloud.Dlp.V2Beta1.AnalyzeDataSourceRiskRequest, global::Google.LongRunning.Operation>(
grpc::MethodType.Unary,
__ServiceName,
"AnalyzeDataSourceRisk",
__Marshaller_AnalyzeDataSourceRiskRequest,
__Marshaller_Operation);
static readonly grpc::Method<global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsRequest, global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsResponse> __Method_ListInspectFindings = new grpc::Method<global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsRequest, global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ListInspectFindings",
__Marshaller_ListInspectFindingsRequest,
__Marshaller_ListInspectFindingsResponse);
static readonly grpc::Method<global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesRequest, global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesResponse> __Method_ListInfoTypes = new grpc::Method<global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesRequest, global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ListInfoTypes",
__Marshaller_ListInfoTypesRequest,
__Marshaller_ListInfoTypesResponse);
static readonly grpc::Method<global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesRequest, global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesResponse> __Method_ListRootCategories = new grpc::Method<global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesRequest, global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ListRootCategories",
__Marshaller_ListRootCategoriesRequest,
__Marshaller_ListRootCategoriesResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Dlp.V2Beta1.DlpReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of DlpService</summary>
public abstract partial class DlpServiceBase
{
/// <summary>
/// Finds potentially sensitive info in a list of strings.
/// This method has limits on input size, processing time, and output size.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Dlp.V2Beta1.InspectContentResponse> InspectContent(global::Google.Cloud.Dlp.V2Beta1.InspectContentRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Redacts potentially sensitive info from a list of strings.
/// This method has limits on input size, processing time, and output size.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Dlp.V2Beta1.RedactContentResponse> RedactContent(global::Google.Cloud.Dlp.V2Beta1.RedactContentRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// De-identifies potentially sensitive info from a list of strings.
/// This method has limits on input size and output size.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentResponse> DeidentifyContent(global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Schedules a job scanning content in a Google Cloud Platform data
/// repository.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> CreateInspectOperation(global::Google.Cloud.Dlp.V2Beta1.CreateInspectOperationRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Schedules a job to compute risk analysis metrics over content in a Google
/// Cloud Platform repository.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> AnalyzeDataSourceRisk(global::Google.Cloud.Dlp.V2Beta1.AnalyzeDataSourceRiskRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Returns list of results for given inspect operation result set id.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsResponse> ListInspectFindings(global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Returns sensitive information types for given category.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesResponse> ListInfoTypes(global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Returns the list of root categories of sensitive information.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesResponse> ListRootCategories(global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for DlpService</summary>
public partial class DlpServiceClient : grpc::ClientBase<DlpServiceClient>
{
/// <summary>Creates a new client for DlpService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public DlpServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for DlpService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public DlpServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected DlpServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected DlpServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Finds potentially sensitive info in a list of strings.
/// This method has limits on input size, processing time, and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.InspectContentResponse InspectContent(global::Google.Cloud.Dlp.V2Beta1.InspectContentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return InspectContent(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Finds potentially sensitive info in a list of strings.
/// This method has limits on input size, processing time, and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.InspectContentResponse InspectContent(global::Google.Cloud.Dlp.V2Beta1.InspectContentRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_InspectContent, null, options, request);
}
/// <summary>
/// Finds potentially sensitive info in a list of strings.
/// This method has limits on input size, processing time, and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.InspectContentResponse> InspectContentAsync(global::Google.Cloud.Dlp.V2Beta1.InspectContentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return InspectContentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Finds potentially sensitive info in a list of strings.
/// This method has limits on input size, processing time, and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.InspectContentResponse> InspectContentAsync(global::Google.Cloud.Dlp.V2Beta1.InspectContentRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_InspectContent, null, options, request);
}
/// <summary>
/// Redacts potentially sensitive info from a list of strings.
/// This method has limits on input size, processing time, and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.RedactContentResponse RedactContent(global::Google.Cloud.Dlp.V2Beta1.RedactContentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RedactContent(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Redacts potentially sensitive info from a list of strings.
/// This method has limits on input size, processing time, and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.RedactContentResponse RedactContent(global::Google.Cloud.Dlp.V2Beta1.RedactContentRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_RedactContent, null, options, request);
}
/// <summary>
/// Redacts potentially sensitive info from a list of strings.
/// This method has limits on input size, processing time, and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.RedactContentResponse> RedactContentAsync(global::Google.Cloud.Dlp.V2Beta1.RedactContentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RedactContentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Redacts potentially sensitive info from a list of strings.
/// This method has limits on input size, processing time, and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.RedactContentResponse> RedactContentAsync(global::Google.Cloud.Dlp.V2Beta1.RedactContentRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_RedactContent, null, options, request);
}
/// <summary>
/// De-identifies potentially sensitive info from a list of strings.
/// This method has limits on input size and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentResponse DeidentifyContent(global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeidentifyContent(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// De-identifies potentially sensitive info from a list of strings.
/// This method has limits on input size and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentResponse DeidentifyContent(global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_DeidentifyContent, null, options, request);
}
/// <summary>
/// De-identifies potentially sensitive info from a list of strings.
/// This method has limits on input size and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentResponse> DeidentifyContentAsync(global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeidentifyContentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// De-identifies potentially sensitive info from a list of strings.
/// This method has limits on input size and output size.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentResponse> DeidentifyContentAsync(global::Google.Cloud.Dlp.V2Beta1.DeidentifyContentRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_DeidentifyContent, null, options, request);
}
/// <summary>
/// Schedules a job scanning content in a Google Cloud Platform data
/// repository.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.LongRunning.Operation CreateInspectOperation(global::Google.Cloud.Dlp.V2Beta1.CreateInspectOperationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateInspectOperation(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Schedules a job scanning content in a Google Cloud Platform data
/// repository.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.LongRunning.Operation CreateInspectOperation(global::Google.Cloud.Dlp.V2Beta1.CreateInspectOperationRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreateInspectOperation, null, options, request);
}
/// <summary>
/// Schedules a job scanning content in a Google Cloud Platform data
/// repository.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> CreateInspectOperationAsync(global::Google.Cloud.Dlp.V2Beta1.CreateInspectOperationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateInspectOperationAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Schedules a job scanning content in a Google Cloud Platform data
/// repository.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> CreateInspectOperationAsync(global::Google.Cloud.Dlp.V2Beta1.CreateInspectOperationRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreateInspectOperation, null, options, request);
}
/// <summary>
/// Schedules a job to compute risk analysis metrics over content in a Google
/// Cloud Platform repository.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.LongRunning.Operation AnalyzeDataSourceRisk(global::Google.Cloud.Dlp.V2Beta1.AnalyzeDataSourceRiskRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeDataSourceRisk(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Schedules a job to compute risk analysis metrics over content in a Google
/// Cloud Platform repository.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.LongRunning.Operation AnalyzeDataSourceRisk(global::Google.Cloud.Dlp.V2Beta1.AnalyzeDataSourceRiskRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeDataSourceRisk, null, options, request);
}
/// <summary>
/// Schedules a job to compute risk analysis metrics over content in a Google
/// Cloud Platform repository.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> AnalyzeDataSourceRiskAsync(global::Google.Cloud.Dlp.V2Beta1.AnalyzeDataSourceRiskRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeDataSourceRiskAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Schedules a job to compute risk analysis metrics over content in a Google
/// Cloud Platform repository.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> AnalyzeDataSourceRiskAsync(global::Google.Cloud.Dlp.V2Beta1.AnalyzeDataSourceRiskRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeDataSourceRisk, null, options, request);
}
/// <summary>
/// Returns list of results for given inspect operation result set id.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsResponse ListInspectFindings(global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListInspectFindings(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns list of results for given inspect operation result set id.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsResponse ListInspectFindings(global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListInspectFindings, null, options, request);
}
/// <summary>
/// Returns list of results for given inspect operation result set id.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsResponse> ListInspectFindingsAsync(global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListInspectFindingsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns list of results for given inspect operation result set id.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsResponse> ListInspectFindingsAsync(global::Google.Cloud.Dlp.V2Beta1.ListInspectFindingsRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListInspectFindings, null, options, request);
}
/// <summary>
/// Returns sensitive information types for given category.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesResponse ListInfoTypes(global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListInfoTypes(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns sensitive information types for given category.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesResponse ListInfoTypes(global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListInfoTypes, null, options, request);
}
/// <summary>
/// Returns sensitive information types for given category.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesResponse> ListInfoTypesAsync(global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListInfoTypesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns sensitive information types for given category.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesResponse> ListInfoTypesAsync(global::Google.Cloud.Dlp.V2Beta1.ListInfoTypesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListInfoTypes, null, options, request);
}
/// <summary>
/// Returns the list of root categories of sensitive information.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesResponse ListRootCategories(global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListRootCategories(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns the list of root categories of sensitive information.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesResponse ListRootCategories(global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListRootCategories, null, options, request);
}
/// <summary>
/// Returns the list of root categories of sensitive information.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesResponse> ListRootCategoriesAsync(global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListRootCategoriesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns the list of root categories of sensitive information.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesResponse> ListRootCategoriesAsync(global::Google.Cloud.Dlp.V2Beta1.ListRootCategoriesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListRootCategories, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override DlpServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new DlpServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(DlpServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_InspectContent, serviceImpl.InspectContent)
.AddMethod(__Method_RedactContent, serviceImpl.RedactContent)
.AddMethod(__Method_DeidentifyContent, serviceImpl.DeidentifyContent)
.AddMethod(__Method_CreateInspectOperation, serviceImpl.CreateInspectOperation)
.AddMethod(__Method_AnalyzeDataSourceRisk, serviceImpl.AnalyzeDataSourceRisk)
.AddMethod(__Method_ListInspectFindings, serviceImpl.ListInspectFindings)
.AddMethod(__Method_ListInfoTypes, serviceImpl.ListInfoTypes)
.AddMethod(__Method_ListRootCategories, serviceImpl.ListRootCategories).Build();
}
}
}
#endregion
| |
//-----------------------------------------------------------------------
// <copyright file="Frame.cs" company="Google LLC">
//
// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore
{
using System;
using System.Collections.Generic;
using GoogleARCoreInternal;
using UnityEngine;
/// <summary>
/// Provides a snapshot of the state of ARCore at a specific timestamp associated with the
/// current frame. Frame holds information about ARCore's state including tracking status, the
/// pose of the camera relative to the world, estimated lighting parameters, and information on
/// updates to objects (like Planes or Point Clouds) that ARCore is tracking.
/// </summary>
public class Frame
{
//// @cond EXCLUDE_FROM_DOXYGEN
private static List<TrackableHit> s_TmpTrackableHitList = new List<TrackableHit>();
//// @endcond
/// <summary>
/// Gets the pose of the ARCore device for the frame in Unity world coordinates.
/// </summary>
public static Pose Pose
{
get
{
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return Pose.identity;
}
var cameraHandle = nativeSession.FrameApi.AcquireCamera();
Pose result = nativeSession.CameraApi.GetPose(cameraHandle);
nativeSession.CameraApi.Release(cameraHandle);
return result;
}
}
/// <summary>
/// Gets the current light estimate for this frame.
/// </summary>
public static LightEstimate LightEstimate
{
get
{
var nativeSession = LifecycleManager.Instance.NativeSession;
var sessionComponent = LifecycleManager.Instance.SessionComponent;
if (nativeSession == null || sessionComponent == null ||
sessionComponent.SessionConfig.LightEstimationMode ==
LightEstimationMode.Disabled)
{
return new LightEstimate(LightEstimateState.NotValid, 0.0f, Color.black,
Quaternion.LookRotation(Vector3.down), Color.white, null, -1);
}
return nativeSession.FrameApi.GetLightEstimate();
}
}
/// <summary>
/// Performs a raycast against objects being tracked by ARCore.
/// Output the closest hit from the camera.
/// Note that the Unity's screen coordinate (0, 0)
/// starts from bottom left.
/// </summary>
/// <param name="x">Horizontal touch position in Unity's screen coordiante.</param>
/// <param name="y">Vertical touch position in Unity's screen coordiante.</param>
/// <param name="filter">A filter bitmask where each set bit in
/// <see cref="TrackableHitFlags"/>
/// represents a category of raycast hits the method call should consider valid.</param>
/// <param name="hitResult">A <see cref="TrackableHit"/> that will be set if the raycast is
/// successful.</param>
/// <returns><c>true</c> if the raycast had a hit, otherwise <c>false</c>.</returns>
[SuppressMemoryAllocationError(IsWarning = true, Reason = "List could be resized")]
public static bool Raycast(float x, float y, TrackableHitFlags filter,
out TrackableHit hitResult)
{
hitResult = new TrackableHit();
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return false;
}
// Note that the Unity's screen coordinate (0, 0) starts from bottom left.
bool foundHit = nativeSession.HitTestApi.Raycast(
nativeSession.FrameHandle, x, Screen.height - y, filter, s_TmpTrackableHitList);
if (foundHit && s_TmpTrackableHitList.Count != 0)
{
hitResult = s_TmpTrackableHitList[0];
}
return foundHit;
}
/// <summary>
/// Performs a raycast against objects being tracked by ARCore.
/// Output the closest hit from the origin.
/// </summary>
/// <param name="origin">The starting point of the ray in world coordinates.</param>
/// <param name="direction">The direction of the ray.</param>
/// <param name="hitResult">A <see cref="TrackableHit"/> that will be set if the raycast is
/// successful.</param>
/// <param name="maxDistance">The max distance the ray should check for collisions.</param>
/// <param name="filter">A filter bitmask where each set bit in
/// <see cref="TrackableHitFlags"/>
/// represents a category of raycast hits the method call should consider valid.</param>
/// <returns><c>true</c> if the raycast had a hit, otherwise <c>false</c>.</returns>
[SuppressMemoryAllocationError(IsWarning = true, Reason = "List could be resized")]
public static bool Raycast(
Vector3 origin, Vector3 direction, out TrackableHit hitResult,
float maxDistance = Mathf.Infinity,
TrackableHitFlags filter = TrackableHitFlags.Default)
{
hitResult = new TrackableHit();
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return false;
}
bool foundHit =
nativeSession.HitTestApi.Raycast(
nativeSession.FrameHandle, origin, direction, maxDistance, filter,
s_TmpTrackableHitList);
if (foundHit && s_TmpTrackableHitList.Count != 0)
{
hitResult = s_TmpTrackableHitList[0];
}
return foundHit;
}
/// <summary>
/// Performs a raycast against objects being tracked by ARCore.
/// Output all hits from the camera.
/// Note that the Unity's screen coordinate (0, 0)
/// starts from bottom left.
/// </summary>
/// <param name="x">Horizontal touch position in Unity's screen coordiante.</param>
/// <param name="y">Vertical touch position in Unity's screen coordiante.</param>
/// <param name="filter">A filter bitmask where each set bit in
/// <see cref="TrackableHitFlags"/>
/// represents a category of raycast hits the method call should consider valid.</param>
/// <param name="hitResults">A list of <see cref="TrackableHit"/> that will be set if the
/// raycast is successful.</param>
/// <returns><c>true</c> if the raycast had a hit, otherwise <c>false</c>.</returns>
[SuppressMemoryAllocationError(IsWarning = true, Reason = "List could be resized")]
public static bool RaycastAll(
float x, float y, TrackableHitFlags filter, List<TrackableHit> hitResults)
{
hitResults.Clear();
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return false;
}
return nativeSession.HitTestApi.Raycast(
nativeSession.FrameHandle, x, Screen.height - y, filter, hitResults);
}
/// <summary>
/// Performs a raycast against objects being tracked by ARCore.
/// Output all hits from the origin.
/// </summary>
/// <param name="origin">The starting point of the ray in world coordinates.</param>
/// <param name="direction">The direction of the ray.</param>
/// <param name="hitResults">A list of <see cref="TrackableHit"/> that will be set if the
/// raycast is successful.</param>
/// <param name="maxDistance">The max distance the ray should check for collisions.</param>
/// <param name="filter">A filter bitmask where each set bit in
/// <see cref="TrackableHitFlags"/> represents a category
/// of raycast hits the method call should consider valid.</param>
/// <returns><c>true</c> if the raycast had a hit, otherwise <c>false</c>.</returns>
[SuppressMemoryAllocationError(IsWarning = true, Reason = "List could be resized")]
public static bool RaycastAll(
Vector3 origin, Vector3 direction, List<TrackableHit> hitResults,
float maxDistance = Mathf.Infinity,
TrackableHitFlags filter = TrackableHitFlags.Default)
{
hitResults.Clear();
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return false;
}
return nativeSession.HitTestApi.Raycast(
nativeSession.FrameHandle, origin, direction, maxDistance, filter, hitResults);
}
/// <summary>
/// Container for state related to the ARCore camera image metadata for the frame.
/// </summary>
public static class CameraMetadata
{
/// <summary>
/// Get camera image metadata value. The querying value type needs to match the returned
/// type.
/// The type could be checked in CameraMetadata.cs.
/// </summary>
/// <param name="metadataTag">Metadata type.</param>
/// <param name="outMetadataList">Result list of the requested values.</param>
/// <returns><c>true</c> if getting metadata value successfully, otherwise
/// <c>false</c>.</returns>
public static bool TryGetValues(
CameraMetadataTag metadataTag, List<CameraMetadataValue> outMetadataList)
{
outMetadataList.Clear();
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return false;
}
IntPtr metadataHandle = IntPtr.Zero;
if (!nativeSession.FrameApi.AcquireImageMetadata(ref metadataHandle))
{
return false;
}
var isSuccess = nativeSession.CameraMetadataApi.TryGetValues(
metadataHandle, metadataTag, outMetadataList);
nativeSession.CameraMetadataApi.Release(metadataHandle);
return isSuccess;
}
/// <summary>
/// Get all available tags in the current frame's metadata.
/// </summary>
/// <param name="outMetadataTags">Result list of the tags.</param>
/// <returns><c>true</c> if getting tags successfully, otherwise <c>false</c>.</returns>
public static bool GetAllCameraMetadataTags(List<CameraMetadataTag> outMetadataTags)
{
outMetadataTags.Clear();
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return false;
}
IntPtr metadataHandle = IntPtr.Zero;
if (!nativeSession.FrameApi.AcquireImageMetadata(ref metadataHandle))
{
return false;
}
var isSuccess =
nativeSession.CameraMetadataApi.GetAllCameraMetadataTags(
metadataHandle, outMetadataTags);
nativeSession.CameraMetadataApi.Release(metadataHandle);
return isSuccess;
}
}
/// <summary>
/// Container for state related to the ARCore point cloud for the frame.
/// </summary>
public static class PointCloud
{
/// <summary>
/// Gets a value indicating whether new point cloud data became available in the current
/// frame.
/// </summary>
/// <returns><c>true</c> if new point cloud data became available in the current frame,
/// otherwise <c>false</c>.</returns>
public static bool IsUpdatedThisFrame
{
get
{
if (LifecycleManager.Instance.IsSessionChangedThisFrame)
{
return true;
}
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return false;
}
return nativeSession.IsPointCloudNew;
}
}
/// <summary>
/// Gets the count of point cloud points in the frame.
/// </summary>
public static int PointCount
{
get
{
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return 0;
}
return nativeSession.PointCloudApi.GetNumberOfPoints(
nativeSession.PointCloudHandle);
}
}
/// <summary>
/// Gets a point from the point cloud at a given index.
/// The point returned will be a Vector4 in the form <x,y,z,c> where the first three
/// dimensions describe the position of the point in the world and the last represents a
/// confidence estimation in the range [0, 1).
/// </summary>
/// <param name="index">The index of the point cloud point to get.</param>
/// <returns>The point from the point cloud at <c>index</c> along with its
/// confidence.</returns>
/// @deprecated Please use Frame.PointCloud.GetPointAsStruct instead.
[System.Obsolete("Frame.PointCloud.GetPoint has been deprecated. " +
"Please use Frame.PointCloud.GetPointAsStruct instead.")]
public static Vector4 GetPoint(int index)
{
var point = GetPointAsStruct(index);
return new Vector4(
point.Position.x, point.Position.y, point.Position.z, point.Confidence);
}
/// <summary>
/// Gets a point from the point cloud at the given index. If the point is inaccessible
/// due to session state or an out-of-range index a point will be returns with the
/// <c>Id</c> field set to <c>PointCloudPoint.k_InvalidPointId</c>.
/// </summary>
/// <param name="index">The index of the point cloud point to get.</param>
/// <returns>The point from the point cloud at <c>index</c>.</returns>
public static PointCloudPoint GetPointAsStruct(int index)
{
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null || index >= PointCount)
{
return new PointCloudPoint(PointCloudPoint.InvalidPointId, Vector3.zero, 0.0f);
}
return nativeSession.PointCloudApi.GetPoint(nativeSession.PointCloudHandle, index);
}
/// <summary>
/// Copies the point cloud into the supplied parameter <c>points</c>.
/// Each point will be a Vector4 in the form <x,y,z,c> where the first three dimensions
/// describe the position of the point in the world and the last represents a confidence
/// estimation in the range [0, 1).
/// </summary>
/// <param name="points">A list that will be filled with point cloud points by this
/// method call.</param>
/// @deprecated Please copy points manually instead.
[System.Obsolete("Frame.PointCloud.CopyPoints has been deprecated. " +
"Please copy points manually instead.")]
public static void CopyPoints(List<Vector4> points)
{
points.Clear();
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return;
}
for (int i = 0; i < PointCount; i++)
{
var point = GetPointAsStruct(i);
points.Add(new Vector4(
point.Position.x, point.Position.y, point.Position.z, point.Confidence));
}
}
}
/// <summary>
/// Container for state related to the ARCore camera for the frame.
/// </summary>
public static class CameraImage
{
/// <summary>
/// Gets a texture used from the device's rear camera.
/// </summary>
public static Texture Texture
{
get
{
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null || nativeSession.FrameApi.GetTimestamp() == 0)
{
return null;
}
return ARCoreAndroidLifecycleManager.Instance.BackgroundTexture;
}
}
//// @cond EXCLUDE_FROM_DOXYGEN
[Obsolete(
"This field has been deprecated. Please use Frame.CameraImage.TextureDisplayUvs.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented", Justification = "Deprecated")]
public static DisplayUvCoords DisplayUvCoords
{
get
{
return TextureDisplayUvs;
}
}
//// @endcond
/// <summary>
/// Gets UVs that map the orientation and aspect ratio of
/// <see cref="Frame.CameraImage.Texture"/> to those of the device's display.
/// </summary>
public static DisplayUvCoords TextureDisplayUvs
{
get
{
DisplayUvCoords displayUvCoords = DisplayUvCoords.FullScreenUvCoords;
// Use deprecated 'TransformDisplayUvCoords' when running Instant Preview.
if (InstantPreviewManager.IsProvidingPlatform)
{
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return new DisplayUvCoords();
}
var apiCoords = new ApiDisplayUvCoords(
displayUvCoords.TopLeft, displayUvCoords.TopRight,
displayUvCoords.BottomLeft, displayUvCoords.BottomRight);
nativeSession.FrameApi.TransformDisplayUvCoords(ref apiCoords);
return apiCoords.ToDisplayUvCoords();
}
displayUvCoords.TopLeft = TransformCoordinate(
displayUvCoords.TopLeft,
DisplayUvCoordinateType.UnityScreen,
DisplayUvCoordinateType.BackgroundTexture);
displayUvCoords.TopRight = TransformCoordinate(
displayUvCoords.TopRight,
DisplayUvCoordinateType.UnityScreen,
DisplayUvCoordinateType.BackgroundTexture);
displayUvCoords.BottomLeft = TransformCoordinate(
displayUvCoords.BottomLeft,
DisplayUvCoordinateType.UnityScreen,
DisplayUvCoordinateType.BackgroundTexture);
displayUvCoords.BottomRight = TransformCoordinate(
displayUvCoords.BottomRight,
DisplayUvCoordinateType.UnityScreen,
DisplayUvCoordinateType.BackgroundTexture);
return displayUvCoords;
}
}
/// <summary>
/// Gets UVs that map the orientation and aspect ratio of the image returned by
/// <see cref="Frame.CameraImage.AcquireCameraImageBytes"/> to that of the device's display.
/// </summary>
public static DisplayUvCoords ImageDisplayUvs
{
get
{
if (InstantPreviewManager.IsProvidingPlatform)
{
InstantPreviewManager.LogLimitedSupportMessage(
"access CPU image display UVs");
return DisplayUvCoords.FullScreenUvCoords;
}
DisplayUvCoords displayUvCoords = DisplayUvCoords.FullScreenUvCoords;
displayUvCoords.TopLeft = TransformCoordinate(
displayUvCoords.TopLeft,
DisplayUvCoordinateType.UnityScreen,
DisplayUvCoordinateType.BackgroundImage);
displayUvCoords.TopRight = TransformCoordinate(
displayUvCoords.TopRight,
DisplayUvCoordinateType.UnityScreen,
DisplayUvCoordinateType.BackgroundImage);
displayUvCoords.BottomLeft = TransformCoordinate(
displayUvCoords.BottomLeft,
DisplayUvCoordinateType.UnityScreen,
DisplayUvCoordinateType.BackgroundImage);
displayUvCoords.BottomRight = TransformCoordinate(
displayUvCoords.BottomRight,
DisplayUvCoordinateType.UnityScreen,
DisplayUvCoordinateType.BackgroundImage);
return displayUvCoords;
}
}
/// <summary>
/// Gets the unrotated and uncropped intrinsics for the texture (GPU) stream.
/// </summary>
public static CameraIntrinsics TextureIntrinsics
{
get
{
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return new CameraIntrinsics();
}
var cameraHandle = nativeSession.FrameApi.AcquireCamera();
CameraIntrinsics result =
nativeSession.CameraApi.GetTextureIntrinsics(cameraHandle);
nativeSession.CameraApi.Release(cameraHandle);
return result;
}
}
/// <summary>
/// Gets the unrotated and uncropped intrinsics for the image (CPU) stream.
/// </summary>
public static CameraIntrinsics ImageIntrinsics
{
get
{
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return new CameraIntrinsics();
}
var cameraHandle = nativeSession.FrameApi.AcquireCamera();
CameraIntrinsics result =
nativeSession.CameraApi.GetImageIntrinsics(cameraHandle);
nativeSession.CameraApi.Release(cameraHandle);
return result;
}
}
/// <summary>
/// Transforms a coordinate between the <c>source</c> and <c>target</c> display UV
/// coordinate types.
/// </summary>
/// <remarks>
/// This can be used for the conversion of coordinates accessed in the same Unity
/// update.
/// </remarks>
/// <param name="coordinate">The coordinate to transform.</param>
/// <param name="sourceType">The source type of the desired transformation
/// matrix.</param>
/// <param name="targetType">The target type of the desired transformation
/// matrix.</param>
/// <returns>A corresponding position in the target frame.</returns>
public static Vector2 TransformCoordinate(
Vector2 coordinate, DisplayUvCoordinateType sourceType,
DisplayUvCoordinateType targetType)
{
if (InstantPreviewManager.IsProvidingPlatform)
{
InstantPreviewManager.LogLimitedSupportMessage(
"access 'Frame.TransformCoordinate'");
return Vector2.zero;
}
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
Debug.LogError("Cannot transform coordinate when native session is null.");
return Vector2.zero;
}
nativeSession.FrameApi.TransformCoordinates2d(
ref coordinate, sourceType, targetType);
return coordinate;
}
/// <summary>
/// Attempts to acquire the camera image for CPU access that corresponds to the current
/// frame.
/// </summary>
/// <remarks>
/// Depending on device performance, this can fail for several frames after session
/// start, and for a few frames at a time while the session is running.
/// </remarks>
/// <returns>A <c>CameraImageBytes</c> struct with <c>IsAvailable</c> property set to
/// <c>true</c> if successful and <c>false</c> if the image could not be
/// acquired.</returns>
public static GoogleARCore.CameraImageBytes AcquireCameraImageBytes()
{
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null)
{
return new CameraImageBytes(IntPtr.Zero);
}
return nativeSession.FrameApi.AcquireCameraImageBytes();
}
/// <summary>
/// Gets the projection matrix for the frame.
/// </summary>
/// <param name="nearClipping">The near clipping plane for the projection
/// matrix.</param>
/// <param name="farClipping">The far clipping plane for the projection matrix.</param>
/// <returns>The projection matrix for the frame.</returns>
public static Matrix4x4 GetCameraProjectionMatrix(float nearClipping, float farClipping)
{
var nativeSession = LifecycleManager.Instance.NativeSession;
if (nativeSession == null || Texture == null)
{
return Matrix4x4.identity;
}
var cameraHandle = nativeSession.FrameApi.AcquireCamera();
var result = nativeSession.CameraApi.GetProjectionMatrix(
cameraHandle, nearClipping, farClipping);
nativeSession.CameraApi.Release(cameraHandle);
return result;
}
/// <summary>
/// Updates the input texture with the latest depth data from ARCore.
/// If there is no new data, or an error occurs, the contents of the
/// texture will remain unchanged. See <see cref="DepthStatus"/> for a
/// complete list of reasons.
/// </summary>
/// <param name="depthTexture">The texture to hold the depth data.</param>
/// <returns><see cref="DepthStatus"/>.<c>Success</c> if
/// successful.</returns>
public static DepthStatus UpdateDepthTexture(ref Texture2D depthTexture)
{
var nativeSession = LifecycleManager.Instance.NativeSession;
var sessionComponent = LifecycleManager.Instance.SessionComponent;
if (nativeSession == null || sessionComponent == null ||
sessionComponent.SessionConfig.DepthMode == DepthMode.Disabled)
{
return DepthStatus.InternalError;
}
return nativeSession.FrameApi.UpdateDepthTexture(ref depthTexture);
}
}
}
}
| |
//-----------------------------------------------------------------------------
// EditCurve.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Drawing;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;
namespace Xna.Tools
{
/// <summary>
/// This class contains curve editting related information.
/// </summary>
public class EditCurve
{
#region Properties
/// <summary>
/// Sets/Gets Control that owns this EditCurve.
/// </summary>
public Control Owner { get { return owner; } set { owner = value; } }
/// <summary>
/// Sets/Gets Id of this EditCurve.
/// </summary>
public long Id { get { return id; } set { id = value; } }
/// <summary>
/// Sets/Gets Name of this EditCurve.
/// </summary>
public string Name
{
get { return state.Name; }
set { state.Name = value; FireStateChangeEvent(); }
}
/// <summary>
/// Sets/Gets Color of this EditCurve.
/// </summary>
public System.Drawing.Color Color
{
get { return color; }
set { color = value; FireStateChangeEvent(); }
}
/// <summary>
/// Gets EditCurveKeyCollection.
/// </summary>
public EditCurveKeyCollection Keys { get { return keys; } }
/// <summary>
/// Sets/Gets PreLoop
/// </summary>
public CurveLoopType PreLoop
{
get { return OriginalCurve.PreLoop; }
set
{
state.PreLoop = OriginalCurve.PreLoop = value;
FireStateChangeEvent();
}
}
/// <summary>
/// Sets/Gets PostLoop
/// </summary>
public CurveLoopType PostLoop
{
get { return OriginalCurve.PostLoop; }
set {
state.PostLoop = OriginalCurve.PostLoop = value;
FireStateChangeEvent();
}
}
/// <summary>
/// Gets original curve object.
/// </summary>
public Curve OriginalCurve { get { return originalCurve; } }
/// <summary>
/// Sets/Gets Visible that represents this EditCurve rendered or not
/// in CurveControl.
/// </summary>
public bool Visible { get { return visible; } set { visible = value; } }
/// <summary>
/// Sets/Gets Editable that represents this EditCurve could update states.
/// </summary>
public bool Editable { get { return editable; } set { editable = value; } }
/// <summary>
/// Sets/Gets Dirty flag for file saving.
/// </summary>
public bool Dirty { get { return dirty; } set { dirty = value; } }
/// <summary>
/// Get selections.
/// </summary>
public EditCurveKeySelection Selection { get { return selection; } }
/// <summary>
/// Occures after EditCurve state (Name, Visible, Editable, PreLoop,
/// and PostLoop) changed.
/// </summary>
public event EventHandler StateChanged;
#endregion
#region Constructors
public EditCurve(string name, System.Drawing.Color curveColor, CommandHistory commandHistory)
{
originalCurve = new Curve();
this.color = curveColor;
keys = new EditCurveKeyCollection(this);
state.Name = name;
state.PreLoop = OriginalCurve.PreLoop;
state.PostLoop = OriginalCurve.PostLoop;
this.commandHistory = commandHistory;
}
public EditCurve(string name, System.Drawing.Color curveColor, Curve curve,
CommandHistory commandHistory)
{
originalCurve = curve;
this.color = curveColor;
keys = new EditCurveKeyCollection(this);
state.Name = name;
state.PreLoop = OriginalCurve.PreLoop;
state.PostLoop = OriginalCurve.PostLoop;
this.commandHistory = commandHistory;
}
#endregion
public override string ToString()
{
return state.Name;
}
#region Public Methods
/// <summary>
/// Evaluate this curve at given position.
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public float Evaluate(float position)
{
return OriginalCurve.Evaluate(position);
}
/// <summary>
/// Begin update curve parameters.
/// </summary>
/// <remarks>It records curve satte and key values modification between
/// BeginUpdate and EndUpdate method.</remarks>
public void BeginUpdate()
{
if (inUpdating)
throw new InvalidOperationException("BeginUpdate called twice.");
modifiedKeys = new Dictionary<long, EditCurveKey>();
savedState = (EditCurveState)state.Clone();
inUpdating = true;
}
/// <summary>
/// EndUpdate and generate Undo/Redo command buffer if there is any
/// modification happend since BeginUpdate called.
/// </summary>
public void EndUpdate()
{
if (!inUpdating)
throw new InvalidOperationException(
"You must call BeginUpdate before call EndUpdate.");
// Compare modified key values.
if (modifiedKeys != null && modifiedKeys.Count > 0)
{
List<EditCurveKey> oldKeyValues =
new List<EditCurveKey>(modifiedKeys.Count);
List<EditCurveKey> newKeyValues =
new List<EditCurveKey>(modifiedKeys.Count);
foreach (EditCurveKey savedKey in modifiedKeys.Values)
{
EditCurveKey curKey;
if (keys.TryGetValue(savedKey.Id, out curKey))
{
if (!curKey.Equals(savedKey))
{
// Saved value is already cloned.
oldKeyValues.Add(savedKey);
newKeyValues.Add(curKey.Clone());
}
}
}
if (newKeyValues.Count != 0)
{
dirty = true;
if (commandHistory != null)
commandHistory.Add(new EditCurveKeyUpdateCommand(
this, oldKeyValues, newKeyValues));
}
}
modifiedKeys = null;
// Compare states
bool stateChanged = state != savedState;
if (commandHistory != null && stateChanged)
commandHistory.Add(new EditCurveStateChangeCommand(
this, savedState, state));
savedState = null;
inUpdating = false;
if (stateChanged) FireStateChangeEvent();
}
/// <summary>
/// Select keys and key tangents.
/// </summary>
/// <param name="selectRegion">Selection region in unit coordinate.</param>
/// <param name="tangentScale">Tangent scale in unit coordinate.</param>
/// <param name="keyView"></param>
/// <param name="tangentView"></param>
/// <param name="toggleSelection"></param>
/// <param name="singleSelection"></param>
public void Select(BoundingBox selectRegion, Vector2 tangentScale,
EditCurveView keyView, EditCurveView tangentView,
bool toggleSelection, bool singleSelect)
{
if (!Editable) return;
EditCurveKeySelection newSelection = new EditCurveKeySelection();
// Check Intersection of Keys and Tangents.
if (keyView != EditCurveView.Never)
{
ICollection<EditCurveKey> targetKeys =
(keyView == EditCurveView.Always) ?
(ICollection<EditCurveKey>)keys :
(ICollection<EditCurveKey>)selectedKeys.Values;
newSelection.SelectKeys(targetKeys, selectRegion, singleSelect);
}
// Check Tangents if any keys are not selected.
if (newSelection.Count == 0 && tangentView != EditCurveView.Never)
{
ICollection<EditCurveKey> targetKeys
= (tangentView == EditCurveView.Always) ?
(ICollection<EditCurveKey>)keys :
(ICollection<EditCurveKey>)selectedKeys.Values;
newSelection.SelectTangents(targetKeys, selectRegion, tangentScale,
singleSelect);
}
if (toggleSelection)
newSelection = EditCurveKeySelection.ToggleSelection(
selection, newSelection);
ApplySelection(newSelection, true);
}
/// <summary>
/// Clear selection.
/// </summary>
public void ClearSelection()
{
ApplySelection(new EditCurveKeySelection(), true);
}
/// <summary>
/// Apply key selection.
/// </summary>
/// <param name="newSelection"></param>
/// <param name="generateCommand"></param>
public void ApplySelection(EditCurveKeySelection newSelection,
bool generateCommand)
{
// Re-create selected keys and store selection information from
// new selection.
selectedKeys.Clear();;
foreach (long id in newSelection.Keys)
{
EditCurveKey key = keys.GetValue(id);
key.Selection = newSelection[id];
selectedKeys.Add(key.Id, key);
}
// Clear de-selected keys selection information.
foreach (long id in selection.Keys)
{
if (!newSelection.ContainsKey(id))
{
EditCurveKey key;
if ( keys.TryGetValue(id, out key))
key.Selection = EditCurveSelections.None;
}
}
// Invoke selection change event.
if ( generateCommand == true && !newSelection.Equals(selection) &&
commandHistory != null)
commandHistory.Add(new SelectCommand(this, newSelection, selection));
// Update selection.
selection = newSelection;
}
/// <summary>
/// Move selected keys or tangents.
/// </summary>
/// <param name="newPos"></param>
/// <param name="prevPos"></param>
public void Move(Vector2 newPos, Vector2 prevPos)
{
if (!Editable || !Visible) return;
Vector2 delta = newPos - prevPos;
foreach (EditCurveKey key in selectedKeys.Values)
{
MarkModify(key);
int oldIdx = keys.IndexOf(key);
// Move tangents.
if ((key.Selection & (EditCurveSelections.TangentIn |
EditCurveSelections.TangentOut)) != 0)
{
// Compute delta angle.
Vector2 pos = new Vector2(key.Position, key.Value);
float minAngle = MathHelper.ToRadians(MinTangentAngle);
float maxAngle = MathHelper.ToRadians(MaxTangentAngle);
const float epsilon = 1e-5f;
if ((key.Selection & EditCurveSelections.TangentIn) != 0)
{
// Compute delta angle.
double prevAngle =
Math.Atan2(prevPos.Y - pos.Y, pos.X - prevPos.X);
double newAngle =
Math.Atan2(newPos.Y - pos.Y, pos.X - newPos.X);
double da = prevAngle - newAngle;
float d = GetDistanceOfKeys(oldIdx, 0);
if (Math.Abs(d) > epsilon)
{
float tn = key.TangentIn / d;
key.TangentIn = (float)Math.Tan(MathHelper.Clamp(
(float)(Math.Atan(tn) + da), minAngle, maxAngle)) * d;
if (Single.IsNaN(key.TangentIn))
key.TangentIn = key.TangentIn;
key.TangentInType = EditCurveTangent.Fixed;
}
}
if ((key.Selection & EditCurveSelections.TangentOut) != 0)
{
// Compute delta angle.
double prevAngle =
Math.Atan2(prevPos.Y - pos.Y, prevPos.X - pos.X);
double newAngle =
Math.Atan2(newPos.Y - pos.Y, newPos.X - pos.X);
double da = newAngle - prevAngle;
float d = GetDistanceOfKeys(oldIdx, 1);
if (Math.Abs(d) > epsilon)
{
float tn = key.TangentOut / d;
key.TangentOut = (float)Math.Tan(MathHelper.Clamp(
(float)(Math.Atan(tn) + da), minAngle, maxAngle)) * d;
key.TangentOutType = EditCurveTangent.Fixed;
}
}
}
// Move key position.
keys.RemoveAt(oldIdx); // remove key from curve once.
if ((key.Selection & EditCurveSelections.Key) != 0)
{
key.OriginalKey = new CurveKey(
key.Position + delta.X, key.Value + delta.Y,
key.TangentIn, key.TangentOut, key.Continuity);
}
// Then store updated node back to the curve.
keys.Add(key);
// Compute auto-generated tangents.
int newIdx = keys.IndexOf(key);
ComputeTangents(newIdx);
if (newIdx != oldIdx)
ComputeTangents(oldIdx);
}
}
/// <summary>
/// Updated specified key values.
/// </summary>
public void UpdateKey( long keyId, float newPosition, float newValue)
{
if (!Editable || !Visible) return;
EditCurveKey key;
keys.TryGetValue(keyId, out key);
MarkModify(key);
int oldIdx = keys.IndexOf(key);
// Move key position.
keys.RemoveAt(oldIdx); // remove key from curve once.
key.OriginalKey = new CurveKey( newPosition, newValue,
key.TangentIn, key.TangentOut, key.Continuity);
// Then store updated node back to the curve.
keys.Add(key);
// Compute auto-generated tangents.
int newIdx = keys.IndexOf(key);
ComputeTangents(newIdx);
if (newIdx != oldIdx)
ComputeTangents(oldIdx);
dirty = true;
}
/// <summary>
/// Add new key at given position.
/// </summary>
/// <param name="pos"></param>
public void AddKey(Vector2 pos)
{
EnsureUpdating("AddKey");
// Create new key.
EditCurveKey key = new EditCurveKey(EditCurveKey.GenerateUniqueId(),
new CurveKey(pos.X, pos.Y));
key.Selection = EditCurveSelections.Key;
// Generate add key command and execute it.
EditCurveKeyAddRemoveCommand command =
new EditCurveKeyAddRemoveCommand(this, key, selection);
command.Execute();
if (commandHistory != null) commandHistory.Add(command);
}
/// <summary>
/// Remove selected keys.
/// </summary>
public void RemoveKeys()
{
if (!Editable) return;
if (selectedKeys.Count != 0)
{
// Generate Remove keys command and execute it.
EditCurveKeyAddRemoveCommand command =
new EditCurveKeyAddRemoveCommand(this, selectedKeys.Values);
command.Execute();
if (commandHistory != null) commandHistory.Add(command);
// Clear selection
selection.Clear();
selectedKeys.Clear();
dirty = true;
}
}
/// <summary>
/// Apply new EditCurveState.
/// </summary>
/// <param name="newState"></param>
public void ApplyState(EditCurveState newState)
{
if (newState == null) throw new ArgumentNullException("newState");
inUpdating = true;
Name = newState.Name;
PreLoop = newState.PreLoop;
PostLoop = newState.PostLoop;
inUpdating = false;
FireStateChangeEvent();
}
/// <summary>
/// Apply given key values.
/// </summary>
/// <param name="newKeyValues"></param>
public void ApplyKeyValues(ICollection<EditCurveKey> newKeyValues)
{
foreach (EditCurveKey newKeyValue in newKeyValues)
{
EditCurveKey key = newKeyValue.Clone();
// Update key value.
keys.Remove(keys.GetValue(key.Id));
keys.Add(key);
// Also, update key values if that key is selected.
if (selectedKeys.ContainsKey(key.Id))
{
selectedKeys.Remove(key.Id);
selectedKeys.Add(key.Id, key);
}
dirty = true;
}
}
/// <summary>
/// Set specfied tangent type to selected tangents.
/// </summary>
/// <param name="targetTangent">target tangent (In/Out)</param>
/// <param name="tangentType"></param>
public void SetTangents(EditCurveSelections targetTangent,
EditCurveTangent tangentType)
{
if (!Editable) return;
EnsureUpdating("SetTangents");
// Change tangent type of selcted nodes.
foreach (EditCurveKey key in selectedKeys.Values)
{
MarkModify(key);
if (tangentType == EditCurveTangent.Stepped)
{
SetKeyContinuity(key, CurveContinuity.Step);
}
else
{
SetKeyContinuity(key, CurveContinuity.Smooth);
if ((targetTangent & EditCurveSelections.TangentIn) != 0)
key.TangentInType = tangentType;
if ((targetTangent & EditCurveSelections.TangentOut) != 0)
key.TangentOutType = tangentType;
}
}
// Then, compute tangents.
foreach (EditCurveKey key in selectedKeys.Values)
ComputeTangents(keys.IndexOf(key));
}
/// <summary>
/// Compute specfied index key tangents.
/// </summary>
/// <param name="idx"></param>
public void ComputeTangents(int keyIndex)
{
if (keyIndex < 0 || keyIndex >keys.Count ||keyIndex > Int32.MaxValue - 2)
throw new ArgumentOutOfRangeException("keyIndex");
// Compute neighbors tangents too.
for (int i = keyIndex - 1; i < keyIndex + 2; ++i)
{
if (i >= 0 && i < keys.Count)
{
EditCurveKey key = keys[i];
MarkModify(key);
float tangentInValue = key.TangentIn;
float tangentOutValue = key.TangentOut;
CurveTangent tangentIn = Convert(key.TangentInType);
CurveTangent tangentOut = Convert(key.TangentOutType);
OriginalCurve.ComputeTangent(i, tangentIn, tangentOut);
if (Single.IsNaN(key.TangentIn)) key.TangentIn = 0.0f;
if (Single.IsNaN(key.TangentOut)) key.TangentOut = 0.0f;
// Restore original value if EditCurveTanget is fixed.
if (key.TangentInType == EditCurveTangent.Fixed)
key.TangentIn = tangentInValue;
if (key.TangentOutType == EditCurveTangent.Fixed)
key.TangentOut = tangentOutValue;
}
}
}
/// <summary>
/// Get distance between given index key position and previous/next key.
/// </summary>
/// <param name="index"></param>
/// <param name="direction">0:previeous key, 1:next key</param>
/// <returns></returns>
public float GetDistanceOfKeys(int index, int direction)
{
float result = 1.0f;
if (direction == 0)
{
// From previous key.
if (index > 0)
{
result = keys[index].Position - keys[index - 1].Position;
}
else if (OriginalCurve.PreLoop == CurveLoopType.Oscillate &&
keys.Count > 1)
{
result = keys[1].Position - keys[0].Position;
}
}
else
{
// From next key.
if (index < keys.Count - 1)
{
result = keys[index + 1].Position - keys[index].Position;
}
else if (OriginalCurve.PostLoop == CurveLoopType.Oscillate &&
keys.Count > 1)
{
result = keys[index].Position - keys[index - 1].Position;
}
}
return result;
}
/// <summary>
/// Returns selected key list.
/// </summary>
/// <returns></returns>
public EditCurveKey[] GetSelectedKeys()
{
EditCurveKey[] keys = new EditCurveKey[selectedKeys.Count];
int idx = 0;
foreach (EditCurveKey key in selectedKeys.Values)
keys[idx++] = key;
return keys;
}
/// <summary>
/// Load a Curve from given filename.
/// </summary>
/// <param name="filename"></param>
/// <param name="name"></param>
/// <param name="color"></param>
/// <param name="commandHistory"></param>
/// <returns></returns>
public static EditCurve LoadFromFile(string filename, string name,
System.Drawing.Color color, CommandHistory commandHistory)
{
EditCurve editCurve = null;
using (XmlReader xr = XmlReader.Create(filename))
{
Curve curve = IntermediateSerializer.Deserialize<Curve>(xr,
Path.GetDirectoryName(filename));
editCurve = new EditCurve(name, color, curve, commandHistory);
}
return editCurve;
}
/// <summary>
/// Save this curve to given filename.
/// </summary>
/// <param name="filename"></param>
public void Save(string filename)
{
using (XmlWriter xw = XmlWriter.Create(filename))
{
IntermediateSerializer.Serialize(xw, originalCurve,
Path.GetDirectoryName(filename));
dirty = false;
}
}
#endregion
#region Private methods
/// <summary>
/// Mark modified key.
/// </summary>
private void MarkModify(EditCurveKey key)
{
// Clone and save current EditCurveKey to modified keys.
if (modifiedKeys != null && !modifiedKeys.ContainsKey(key.Id))
{
modifiedKeys.Add(key.Id, key.Clone());
dirty = true;
}
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="continuity"></param>
private void SetKeyContinuity(EditCurveKey key, CurveContinuity continuity)
{
if (key.Continuity != continuity)
{
MarkModify(key);
key.Continuity = continuity;
if (continuity == CurveContinuity.Step)
{
key.TangentIn = key.TangentOut = 0;
key.TangentInType = key.TangentInType = EditCurveTangent.Flat;
}
}
}
/// <summary>
/// Convert EditCurveTanget to CurveTangent.
/// </summary>
/// <param name="tangent"></param>
/// <returns></returns>
private static CurveTangent Convert(EditCurveTangent tangent)
{
return (tangent == EditCurveTangent.Fixed) ?
CurveTangent.Flat : (CurveTangent)tangent;
}
private void FireStateChangeEvent()
{
dirty = true;
if (inUpdating) return;
if (StateChanged != null) StateChanged(this, EventArgs.Empty);
if (Owner != null)
Owner.Invalidate();
}
private void EnsureUpdating(string operationName)
{
if (!inUpdating)
throw new InvalidOperationException(String.Format(
"You have to call BeginUpdate before call {0}", operationName));
}
#endregion
#region Private Constants
const float MinTangentAngle = -89.99999f;
const float MaxTangentAngle = +89.99999f;
#endregion
#region Properties wrap members
private Control owner;
private long id;
private System.Drawing.Color color = System.Drawing.Color.Red;
private Curve originalCurve;
private EditCurveKeyCollection keys;
private bool editable = true;
private bool visible = true;
private bool dirty = false;
#endregion
#region Private members
private CommandHistory commandHistory;
private Dictionary<long, EditCurveKey> selectedKeys =
new Dictionary<long, EditCurveKey>();
private EditCurveKeySelection selection = new EditCurveKeySelection();
private Dictionary<long, EditCurveKey> modifiedKeys;
private EditCurveState state = new EditCurveState();
private EditCurveState savedState;
private bool inUpdating;
#endregion
}
}
| |
/*
Copyright 2014 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
namespace DriveProxy.Utils
{
internal class Math
{
public static decimal Round(decimal value)
{
try
{
return System.Math.Round(value);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static decimal Round(decimal value, int decimalPlaces)
{
try
{
return System.Math.Round(value, decimalPlaces);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static double Absolute(double value)
{
try
{
return System.Math.Abs(value);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static decimal Absolute(decimal value)
{
try
{
return System.Math.Abs(value);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static int Absolute(int value)
{
try
{
return System.Math.Abs(value);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static long Absolute(long value)
{
try
{
return System.Math.Abs(value);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static short Absolute(short value)
{
try
{
return System.Math.Abs(value);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static float Absolute(float value)
{
try
{
return System.Math.Abs(value);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static double Ceiling(double value)
{
try
{
return System.Math.Ceiling(value);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static int Divide(int value, int divideBy)
{
try
{
float tempValue = Convert.ToSingle(value);
float tempDivideBy = Convert.ToSingle(divideBy);
float tempResult = tempValue / tempDivideBy;
int result = Convert.ToInt32(tempResult);
return result;
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static int Divide(int value, int divideBy, out int remainder)
{
remainder = 0;
try
{
return System.Math.DivRem(value, divideBy, out remainder);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static long Divide(long value, long divideBy)
{
try
{
long remainder = 0;
return Divide(value, divideBy, out remainder);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static long Divide(long value, long divideBy, out long remainder)
{
remainder = 0;
try
{
return System.Math.DivRem(value, divideBy, out remainder);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static decimal Divide(decimal value, decimal divideBy)
{
try
{
if (value <= 0 || divideBy <= 0)
{
return 0;
}
decimal result = value / divideBy;
return result;
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static decimal Divide(decimal value, decimal divideBy, int decimalPlaces)
{
try
{
decimal result = Divide(value, divideBy);
return Round(result, decimalPlaces);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static double IsPercentOfWhat(double part, double whole)
{
try
{
double percentage = (whole / part);
return percentage;
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static double IsWhatPercentOf(double part, double whole)
{
try
{
return IsWhatPercentOf(part, whole, -1);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static double IsWhatPercentOf(double part, double whole, int roundToDigits)
{
try
{
double percentage = 0;
if (part != 0 && whole != 0)
{
percentage = (part / whole) * 100;
}
if (roundToDigits > -1)
{
percentage = System.Math.Round(percentage, roundToDigits);
}
return percentage;
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static int Max(int value1, int value2)
{
try
{
return System.Math.Max(value1, value2);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static int Min(int value1, int value2)
{
try
{
return System.Math.Min(value1, value2);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static int ProgressPercent(double part, double whole)
{
try
{
double result = IsWhatPercentOf(part, whole);
return Convert.ToInt32(result);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static double WhatIsPercent(double part, double whole)
{
try
{
return WhatIsPercent(part, whole, -1);
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
public static double WhatIsPercent(double part, double whole, int roundToDigits)
{
try
{
double percentage = (whole * part) / 100;
if (roundToDigits > -1)
{
percentage = System.Math.Round(percentage, roundToDigits);
}
return percentage;
}
catch (Exception exception)
{
Log.Error(exception);
return 0;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.IO
{
/// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
internal sealed partial class UnixFileSystem : FileSystem
{
public override int MaxPath { get { return Interop.Sys.MaxPath; } }
public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } }
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);
}
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
// The destination path may just be a directory into which the file should be copied.
// If it is, append the filename from the source onto the destination directory
if (DirectoryExists(destFullPath))
{
destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
}
// Copy the contents of the file from the source to the destination, creating the destination in the process
using (var src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None))
using (var dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, FileStream.DefaultBufferSize, FileOptions.None))
{
Interop.CheckIo(Interop.Sys.CopyFile(src.SafeFileHandle, dst.SafeFileHandle));
}
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
// The desired behavior for Move(source, dest) is to not overwrite the destination file
// if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,
// link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move
// as a Creation and Deletion instead of a Rename and thus differ from Windows.
if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EXDEV) // rename fails across devices / mount points
{
CopyFile(sourceFullPath, destFullPath, overwrite: false);
}
else if (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(destFullPath))) // The parent directory of destFile can't be found
{
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
throw Interop.GetExceptionForIoErrno(errorInfo, destFullPath, isDirectory: true);
}
else
{
throw Interop.GetExceptionForIoErrno(errorInfo);
}
}
DeleteFile(sourceFullPath);
}
public override void DeleteFile(string fullPath)
{
if (Interop.Sys.Unlink(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// ENOENT means it already doesn't exist; nop
if (errorInfo.Error != Interop.Error.ENOENT)
{
if (errorInfo.Error == Interop.Error.EISDIR)
errorInfo = Interop.Error.EACCES.Info();
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);
}
}
}
public override void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
{
length--;
}
// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
}
// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
{
return;
}
// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
Stack<string> stackDir = new Stack<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
string dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
{
stackDir.Push(dir);
}
else
{
somepathexists = true;
}
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
{
i--;
}
i--;
}
}
int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
string root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
return;
}
// Create all the directories
int result = 0;
Interop.ErrorInfo firstError = default(Interop.ErrorInfo);
string errorString = fullPath;
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
if (name.Length >= MaxDirectoryPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
// The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally).
// We do the same.
result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask);
if (result < 0 && firstError.Error == 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errorInfo.Error != Interop.Error.EEXIST)
{
firstError = errorInfo;
}
else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errorInfo;
errorString = name;
}
}
}
// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError.Error != 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
}
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES: // match Win32 exception
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno);
default:
throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true);
}
}
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
var di = new DirectoryInfo(fullPath);
if (!di.Exists)
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
RemoveDirectoryInternal(di, recursive, throwOnTopLevelDirectoryNotFound: true);
}
private void RemoveDirectoryInternal(DirectoryInfo directory, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
Exception firstException = null;
if ((directory.Attributes & FileAttributes.ReparsePoint) != 0)
{
DeleteFile(directory.FullName);
return;
}
if (recursive)
{
try
{
foreach (string item in EnumeratePaths(directory.FullName, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
{
if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
{
try
{
var childDirectory = new DirectoryInfo(item);
if (childDirectory.Exists)
{
RemoveDirectoryInternal(childDirectory, recursive, throwOnTopLevelDirectoryNotFound: false);
}
else
{
DeleteFile(item);
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
}
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
if (firstException != null)
{
throw firstException;
}
}
if (Interop.Sys.RmDir(directory.FullName) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES:
case Interop.Error.EPERM:
case Interop.Error.EROFS:
case Interop.Error.EISDIR:
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, directory.FullName)); // match Win32 exception
case Interop.Error.ENOENT:
if (!throwOnTopLevelDirectoryNotFound)
{
return;
}
goto default;
default:
throw Interop.GetExceptionForIoErrno(errorInfo, directory.FullName, isDirectory: true);
}
}
}
public override bool DirectoryExists(string fullPath)
{
Interop.ErrorInfo ignored;
return DirectoryExists(fullPath, out ignored);
}
private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo)
{
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo);
}
public override bool FileExists(string fullPath)
{
Interop.ErrorInfo ignored;
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFREG, out ignored);
}
private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo)
{
Debug.Assert(fileType == Interop.Sys.FileTypes.S_IFREG || fileType == Interop.Sys.FileTypes.S_IFDIR);
Interop.Sys.FileStatus fileinfo;
errorInfo = default(Interop.ErrorInfo);
// First use stat, as we want to follow symlinks. If that fails, it could be because the symlink
// is broken, we don't have permissions, etc., in which case fall back to using LStat to evaluate
// based on the symlink itself.
if (Interop.Sys.Stat(fullPath, out fileinfo) < 0 &&
Interop.Sys.LStat(fullPath, out fileinfo) < 0)
{
errorInfo = Interop.Sys.GetLastErrorInfo();
return false;
}
// Something exists at this path. If the caller is asking for a directory, return true if it's
// a directory and false for everything else. If the caller is asking for a file, return false for
// a directory and true for everything else.
return
(fileType == Interop.Sys.FileTypes.S_IFDIR) ==
((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR);
}
public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Files:
return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new FileInfo(path, null));
case SearchTarget.Directories:
return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new DirectoryInfo(path, null));
default:
return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?
(FileSystemInfo)new DirectoryInfo(path, null) :
(FileSystemInfo)new FileInfo(path, null));
}
}
private sealed class FileSystemEnumerable<T> : IEnumerable<T>
{
private readonly PathPair _initialDirectory;
private readonly string _searchPattern;
private readonly SearchOption _searchOption;
private readonly bool _includeFiles;
private readonly bool _includeDirectories;
private readonly Func<string, bool, T> _translateResult;
private IEnumerator<T> _firstEnumerator;
internal FileSystemEnumerable(
string userPath, string searchPattern,
SearchOption searchOption, SearchTarget searchTarget,
Func<string, bool, T> translateResult)
{
// Basic validation of the input path
if (userPath == null)
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrWhiteSpace(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
// Validate and normalize the search pattern. If after doing so it's empty,
// matching Win32 behavior we can skip all additional validation and effectively
// return an empty enumerable.
searchPattern = NormalizeSearchPattern(searchPattern);
if (searchPattern.Length > 0)
{
PathHelpers.CheckSearchPattern(searchPattern);
PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);
// If the search pattern contains any paths, make sure we factor those into
// the user path, and then trim them off.
int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (lastSlash >= 0)
{
if (lastSlash >= 1)
{
userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));
}
searchPattern = searchPattern.Substring(lastSlash + 1);
}
string fullPath = Path.GetFullPath(userPath);
// Store everything for the enumerator
_initialDirectory = new PathPair(userPath, fullPath);
_searchPattern = searchPattern;
_searchOption = searchOption;
_includeFiles = (searchTarget & SearchTarget.Files) != 0;
_includeDirectories = (searchTarget & SearchTarget.Directories) != 0;
_translateResult = translateResult;
}
// Open the first enumerator so that any errors are propagated synchronously.
_firstEnumerator = Enumerate();
}
public IEnumerator<T> GetEnumerator()
{
return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private IEnumerator<T> Enumerate()
{
return Enumerate(
_initialDirectory.FullPath != null ?
OpenDirectory(_initialDirectory.FullPath) :
null);
}
private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle)
{
if (dirHandle == null)
{
// Empty search
yield break;
}
Debug.Assert(!dirHandle.IsInvalid);
Debug.Assert(!dirHandle.IsClosed);
// Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories
// Lazily-initialized only if we find subdirectories that will be explored.
Stack<PathPair> toExplore = null;
PathPair dirPath = _initialDirectory;
while (dirHandle != null)
{
try
{
// Read each entry from the enumerator
Interop.Sys.DirectoryEntry dirent;
while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0)
{
// Get from the dir entry whether the entry is a file or directory.
// We classify everything as a file unless we know it to be a directory.
bool isDir;
if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR)
{
// We know it's a directory.
isDir = true;
}
else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN)
{
// It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
// If we can't (e.g. symlink to a file, broken symlink, etc.), we'll just treat it as a file.
Interop.ErrorInfo errnoIgnored;
isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored);
}
else
{
// Otherwise, treat it as a file. This includes regular files, FIFOs, etc.
isDir = false;
}
// Yield the result if the user has asked for it. In the case of directories,
// always explore it by pushing it onto the stack, regardless of whether
// we're returning directories.
if (isDir)
{
if (!ShouldIgnoreDirectory(dirent.InodeName))
{
string userPath = null;
if (_searchOption == SearchOption.AllDirectories)
{
if (toExplore == null)
{
toExplore = new Stack<PathPair>();
}
userPath = Path.Combine(dirPath.UserPath, dirent.InodeName);
toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName)));
}
if (_includeDirectories &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true);
}
}
}
else if (_includeFiles &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false);
}
}
}
finally
{
// Close the directory enumerator
dirHandle.Dispose();
dirHandle = null;
}
if (toExplore != null && toExplore.Count > 0)
{
// Open the next directory.
dirPath = toExplore.Pop();
dirHandle = OpenDirectory(dirPath.FullPath);
}
}
}
private static string NormalizeSearchPattern(string searchPattern)
{
if (searchPattern == "." || searchPattern == "*.*")
{
searchPattern = "*";
}
else if (PathHelpers.EndsInDirectorySeparator(searchPattern))
{
searchPattern += "*";
}
return searchPattern;
}
private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath)
{
Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath);
if (handle.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true);
}
return handle;
}
}
/// <summary>Determines whether the specified directory name should be ignored.</summary>
/// <param name="name">The name to evaluate.</param>
/// <returns>true if the name is "." or ".."; otherwise, false.</returns>
private static bool ShouldIgnoreDirectory(string name)
{
return name == "." || name == "..";
}
public override string GetCurrentDirectory()
{
return Interop.Sys.GetCwd();
}
public override void SetCurrentDirectory(string fullPath)
{
Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath);
}
public override FileAttributes GetAttributes(string fullPath)
{
return new FileInfo(fullPath, null).Attributes;
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
new FileInfo(fullPath, null).Attributes = attributes;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return new FileInfo(fullPath, null).CreationTime;
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.CreationTime = time;
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return new FileInfo(fullPath, null).LastAccessTime;
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastAccessTime = time;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return new FileInfo(fullPath, null).LastWriteTime;
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastWriteTime = time;
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.Icon.cs
//
// Authors:
// Gary Barnett (gary.barnett.mono@gmail.com)
// Dennis Hayes (dennish@Raytek.com)
// Andreas Nahr (ClassDevelopment@A-SoftTech.com)
// Sanjay Gupta (gsanjay@novell.com)
// Peter Dennis Bartok (pbartok@novell.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2002 Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004-2008 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.Collections;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
namespace System.Drawing
{
#if !NETCORE
#if !MONOTOUCH
[Editor ("System.Drawing.Design.IconEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))]
#endif
[TypeConverter(typeof(IconConverter))]
#endif
public sealed partial class Icon : MarshalByRefObject, ISerializable, ICloneable, IDisposable
{
[StructLayout(LayoutKind.Sequential)]
internal struct IconDirEntry
{
internal byte width; // Width of icon
internal byte height; // Height of icon
internal byte colorCount; // colors in icon
internal byte reserved; // Reserved
internal ushort planes; // Color Planes
internal ushort bitCount; // Bits per pixel
internal uint bytesInRes; // bytes in resource
internal uint imageOffset; // position in file
internal bool ignore; // for unsupported images (vista 256 png)
};
[StructLayout(LayoutKind.Sequential)]
internal struct IconDir
{
internal ushort idReserved; // Reserved
internal ushort idType; // resource type (1 for icons)
internal ushort idCount; // how many images?
internal IconDirEntry[] idEntries; // the entries for each image
};
[StructLayout(LayoutKind.Sequential)]
internal struct BitmapInfoHeader
{
internal uint biSize;
internal int biWidth;
internal int biHeight;
internal ushort biPlanes;
internal ushort biBitCount;
internal uint biCompression;
internal uint biSizeImage;
internal int biXPelsPerMeter;
internal int biYPelsPerMeter;
internal uint biClrUsed;
internal uint biClrImportant;
};
[StructLayout(LayoutKind.Sequential)] // added baseclass for non bmp image format support
internal abstract class ImageData
{
};
[StructLayout(LayoutKind.Sequential)]
internal class IconImage : ImageData
{
internal BitmapInfoHeader iconHeader; //image header
internal uint[] iconColors; //colors table
internal byte[] iconXOR; // bits for XOR mask
internal byte[] iconAND; //bits for AND mask
};
[StructLayout(LayoutKind.Sequential)]
internal class IconDump : ImageData
{
internal byte[] data;
};
private Size iconSize;
private IntPtr handle = IntPtr.Zero;
private IconDir iconDir;
private ushort id;
private ImageData[] imageData;
private bool undisposable;
private bool disposed;
private Bitmap bitmap;
private Icon()
{
}
#if !MONOTOUCH
private Icon(IntPtr handle)
{
this.handle = handle;
bitmap = Bitmap.FromHicon(handle);
iconSize = new Size(bitmap.Width, bitmap.Height);
bitmap = Bitmap.FromHicon(handle);
iconSize = new Size(bitmap.Width, bitmap.Height);
// FIXME: we need to convert the bitmap into an icon
undisposable = true;
}
#endif
public Icon(Icon original, int width, int height)
: this(original, new Size(width, height))
{
}
public Icon(Icon original, Size size)
{
if (original == null)
throw new ArgumentNullException(nameof(original));
iconSize = size;
iconDir = original.iconDir;
int count = iconDir.idCount;
if (count > 0)
{
imageData = original.imageData;
id = UInt16.MaxValue;
for (ushort i = 0; i < count; i++)
{
IconDirEntry ide = iconDir.idEntries[i];
if (((ide.height == size.Height) || (ide.width == size.Width)) && !ide.ignore)
{
id = i;
break;
}
}
// if a perfect match isn't found we look for the biggest icon *smaller* than specified
if (id == UInt16.MaxValue)
{
int requested = Math.Min(size.Height, size.Width);
// previously best set to 1st image, as this might not be smallest changed loop to check all
IconDirEntry? best = null;
for (ushort i = 0; i < count; i++)
{
IconDirEntry ide = iconDir.idEntries[i];
if (((ide.height < requested) || (ide.width < requested)) && !ide.ignore)
{
if (best == null)
{
best = ide;
id = i;
}
else if ((ide.height > best.Value.height) || (ide.width > best.Value.width))
{
best = ide;
id = i;
}
}
}
}
// last one, if nothing better can be found
if (id == UInt16.MaxValue)
{
int i = count;
while (id == UInt16.MaxValue && i > 0)
{
i--;
if (!iconDir.idEntries[i].ignore)
id = (ushort)i;
}
}
if (id == UInt16.MaxValue)
throw new ArgumentException("Icon", "No valid icon image found");
iconSize.Height = iconDir.idEntries[id].height;
iconSize.Width = iconDir.idEntries[id].width;
}
else
{
iconSize.Height = size.Height;
iconSize.Width = size.Width;
}
if (original.bitmap != null)
bitmap = (Bitmap)original.bitmap.Clone();
}
public Icon(Stream stream) : this(stream, 32, 32)
{
}
public Icon(Stream stream, int width, int height)
{
InitFromStreamWithSize(stream, width, height);
}
public Icon(string fileName)
{
using (FileStream fs = File.OpenRead(fileName))
{
InitFromStreamWithSize(fs, 32, 32);
}
}
public Icon(Type type, string resource)
{
if (resource == null)
throw new ArgumentException("resource");
// For compatibility with the .NET Framework
if (type == null)
throw new NullReferenceException();
using (Stream s = type.GetTypeInfo().Assembly.GetManifestResourceStream(type, resource))
{
if (s == null)
{
throw new ArgumentException(null);
}
InitFromStreamWithSize(s, 32, 32); // 32x32 is default
}
}
internal Icon(string resourceName, bool undisposable)
{
using (Stream s = typeof(Icon).GetTypeInfo().Assembly.GetManifestResourceStream(resourceName))
{
if (s == null)
{
string msg = string.Format("Resource '{0}' was not found.", resourceName);
throw new FileNotFoundException(msg);
}
InitFromStreamWithSize(s, 32, 32); // 32x32 is default
}
this.undisposable = true;
}
public Icon(Stream stream, Size size) :
this(stream, size.Width, size.Height)
{
}
public Icon(string fileName, int width, int height)
{
using (FileStream fs = File.OpenRead(fileName))
{
InitFromStreamWithSize(fs, width, height);
}
}
public Icon(string fileName, Size size)
{
using (FileStream fs = File.OpenRead(fileName))
{
InitFromStreamWithSize(fs, size.Width, size.Height);
}
}
[MonoLimitation("The same icon, SystemIcons.WinLogo, is returned for all file types.")]
public static Icon ExtractAssociatedIcon(string filePath)
{
if (filePath == null)
throw new ArgumentNullException(nameof(filePath));
if (String.IsNullOrEmpty(filePath))
throw new ArgumentException("Null or empty path.", "path");
if (!File.Exists(filePath))
throw new FileNotFoundException("Couldn't find specified file.", filePath);
return SystemIcons.WinLogo;
}
public void Dispose()
{
// SystemIcons requires this
if (undisposable)
return;
if (!disposed)
{
if (bitmap != null)
{
bitmap.Dispose();
bitmap = null;
}
GC.SuppressFinalize(this);
}
disposed = true;
}
public object Clone()
{
return new Icon(this, Size);
}
#if !MONOTOUCH
public static Icon FromHandle(IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentException("handle");
return new Icon(handle);
}
#endif
private void SaveIconImage(BinaryWriter writer, IconImage ii)
{
BitmapInfoHeader bih = ii.iconHeader;
writer.Write(bih.biSize);
writer.Write(bih.biWidth);
writer.Write(bih.biHeight);
writer.Write(bih.biPlanes);
writer.Write(bih.biBitCount);
writer.Write(bih.biCompression);
writer.Write(bih.biSizeImage);
writer.Write(bih.biXPelsPerMeter);
writer.Write(bih.biYPelsPerMeter);
writer.Write(bih.biClrUsed);
writer.Write(bih.biClrImportant);
//now write color table
int colCount = ii.iconColors.Length;
for (int j = 0; j < colCount; j++)
writer.Write(ii.iconColors[j]);
//now write XOR Mask
writer.Write(ii.iconXOR);
//now write AND Mask
writer.Write(ii.iconAND);
}
private void SaveIconDump(BinaryWriter writer, IconDump id)
{
writer.Write(id.data);
}
private void SaveIconDirEntry(BinaryWriter writer, IconDirEntry ide, uint offset)
{
writer.Write(ide.width);
writer.Write(ide.height);
writer.Write(ide.colorCount);
writer.Write(ide.reserved);
writer.Write(ide.planes);
writer.Write(ide.bitCount);
writer.Write(ide.bytesInRes);
writer.Write((offset == UInt32.MaxValue) ? ide.imageOffset : offset);
}
private void SaveAll(BinaryWriter writer)
{
writer.Write(iconDir.idReserved);
writer.Write(iconDir.idType);
ushort count = iconDir.idCount;
writer.Write(count);
for (int i = 0; i < (int)count; i++)
{
SaveIconDirEntry(writer, iconDir.idEntries[i], UInt32.MaxValue);
}
for (int i = 0; i < (int)count; i++)
{
//FIXME: HACK: 1 (out of the 8) vista type icons had additional bytes (value:0)
//between images. This fixes the issue, but perhaps shouldnt include in production?
while (writer.BaseStream.Length < iconDir.idEntries[i].imageOffset)
writer.Write((byte)0);
if (imageData[i] is IconDump)
SaveIconDump(writer, (IconDump)imageData[i]);
else
SaveIconImage(writer, (IconImage)imageData[i]);
}
}
// TODO: check image not ignored (presently this method doesnt seem to be called unless width/height
// refer to image)
private void SaveBestSingleIcon(BinaryWriter writer, int width, int height)
{
writer.Write(iconDir.idReserved);
writer.Write(iconDir.idType);
writer.Write((ushort)1);
// find best entry and save it
int best = 0;
int bitCount = 0;
for (int i = 0; i < iconDir.idCount; i++)
{
IconDirEntry ide = iconDir.idEntries[i];
if ((width == ide.width) && (height == ide.height))
{
if (ide.bitCount >= bitCount)
{
bitCount = ide.bitCount;
best = i;
}
}
}
SaveIconDirEntry(writer, iconDir.idEntries[best], 22);
SaveIconImage(writer, (IconImage)imageData[best]);
}
private void SaveBitmapAsIcon(BinaryWriter writer)
{
writer.Write((ushort)0); // idReserved must be 0
writer.Write((ushort)1); // idType must be 1
writer.Write((ushort)1); // only one icon
// when transformed into a bitmap only a single image exists
IconDirEntry ide = new IconDirEntry();
ide.width = (byte)bitmap.Width;
ide.height = (byte)bitmap.Height;
ide.colorCount = 0; // 32 bbp == 0, for palette size
ide.reserved = 0; // always 0
ide.planes = 0;
ide.bitCount = 32;
ide.imageOffset = 22; // 22 is the first icon position (for single icon files)
BitmapInfoHeader bih = new BitmapInfoHeader();
bih.biSize = (uint)Marshal.SizeOf(typeof(BitmapInfoHeader));
bih.biWidth = bitmap.Width;
bih.biHeight = 2 * bitmap.Height; // include both XOR and AND images
bih.biPlanes = 1;
bih.biBitCount = 32;
bih.biCompression = 0;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
IconImage ii = new IconImage();
ii.iconHeader = bih;
ii.iconColors = Array.Empty<uint>(); // no palette
int xor_size = (((bih.biBitCount * bitmap.Width + 31) & ~31) >> 3) * bitmap.Height;
ii.iconXOR = new byte[xor_size];
int p = 0;
for (int y = bitmap.Height - 1; y >= 0; y--)
{
for (int x = 0; x < bitmap.Width; x++)
{
Color c = bitmap.GetPixel(x, y);
ii.iconXOR[p++] = c.B;
ii.iconXOR[p++] = c.G;
ii.iconXOR[p++] = c.R;
ii.iconXOR[p++] = c.A;
}
}
int and_line_size = (((Width + 31) & ~31) >> 3); // must be a multiple of 4 bytes
int and_size = and_line_size * bitmap.Height;
ii.iconAND = new byte[and_size];
ide.bytesInRes = (uint)(bih.biSize + xor_size + and_size);
SaveIconDirEntry(writer, ide, UInt32.MaxValue);
SaveIconImage(writer, ii);
}
private void Save(Stream outputStream, int width, int height)
{
BinaryWriter writer = new BinaryWriter(outputStream);
// if we have the icon information then save from this
if (iconDir.idEntries != null)
{
if ((width == -1) && (height == -1))
SaveAll(writer);
else
SaveBestSingleIcon(writer, width, height);
}
else if (bitmap != null)
{
// if the icon was created from a bitmap then convert it
SaveBitmapAsIcon(writer);
}
writer.Flush();
}
public void Save(Stream outputStream)
{
if (outputStream == null)
throw new NullReferenceException("outputStream");
// save every icons available
Save(outputStream, -1, -1);
}
#if !MONOTOUCH
internal Bitmap BuildBitmapOnWin32()
{
Bitmap bmp;
if (imageData == null)
return new Bitmap(32, 32);
IconImage ii = (IconImage)imageData[id];
BitmapInfoHeader bih = ii.iconHeader;
int biHeight = bih.biHeight / 2;
int ncolors = (int)bih.biClrUsed;
if ((ncolors == 0) && (bih.biBitCount < 24))
ncolors = (int)(1 << bih.biBitCount);
switch (bih.biBitCount)
{
case 1:
bmp = new Bitmap(bih.biWidth, biHeight, PixelFormat.Format1bppIndexed);
break;
case 4:
bmp = new Bitmap(bih.biWidth, biHeight, PixelFormat.Format4bppIndexed);
break;
case 8:
bmp = new Bitmap(bih.biWidth, biHeight, PixelFormat.Format8bppIndexed);
break;
case 24:
bmp = new Bitmap(bih.biWidth, biHeight, PixelFormat.Format24bppRgb);
break;
case 32:
bmp = new Bitmap(bih.biWidth, biHeight, PixelFormat.Format32bppArgb);
break;
default:
string msg = string.Format("Unexpected number of bits: {0}", bih.biBitCount);
throw new Exception(msg);
}
if (bih.biBitCount < 24)
{
ColorPalette pal = bmp.Palette; // Managed palette
for (int i = 0; i < ii.iconColors.Length; i++)
{
pal.Entries[i] = Color.FromArgb((int)ii.iconColors[i] | unchecked((int)0xff000000));
}
bmp.Palette = pal;
}
int bytesPerLine = (int)((((bih.biWidth * bih.biBitCount) + 31) & ~31) >> 3);
BitmapData bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
for (int y = 0; y < biHeight; y++)
{
Marshal.Copy(ii.iconXOR, bytesPerLine * y,
(IntPtr)(bits.Scan0.ToInt64() + bits.Stride * (biHeight - 1 - y)), bytesPerLine);
}
bmp.UnlockBits(bits);
bmp = new Bitmap(bmp); // This makes a 32bpp image out of an indexed one
// Apply the mask to make properly transparent
bytesPerLine = (int)((((bih.biWidth) + 31) & ~31) >> 3);
for (int y = 0; y < biHeight; y++)
{
for (int x = 0; x < bih.biWidth / 8; x++)
{
for (int bit = 7; bit >= 0; bit--)
{
if (((ii.iconAND[y * bytesPerLine + x] >> bit) & 1) != 0)
{
bmp.SetPixel(x * 8 + 7 - bit, biHeight - y - 1, Color.Transparent);
}
}
}
}
return bmp;
}
internal Bitmap GetInternalBitmap()
{
if (bitmap == null)
{
// Mono's libgdiplus doesn't require to keep the stream alive when loading images
using (MemoryStream ms = new MemoryStream())
{
// save the current icon
Save(ms, Width, Height);
ms.Position = 0;
// libgdiplus can now decode icons
bitmap = (Bitmap)Image.LoadFromStream(ms, false);
}
}
return bitmap;
}
// note: all bitmaps are 32bits ARGB - no matter what the icon format (bitcount) was
public Bitmap ToBitmap()
{
if (disposed)
throw new ObjectDisposedException("Icon instance was disposed.");
// note: we can't return the original image because
// (a) we have no control over the bitmap instance we return (i.e. it could be disposed)
// (b) the palette, flags won't match MS results. See MonoTests.System.Drawing.Imaging.IconCodecTest.
// Image16 for the differences
return new Bitmap(GetInternalBitmap());
}
#endif
public override string ToString()
{
//is this correct, this is what returned by .Net
return "<Icon>";
}
#if !MONOTOUCH
[Browsable(false)]
public IntPtr Handle
{
get
{
if (disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
// note: this handle doesn't survive the lifespan of the icon instance
if (handle == IntPtr.Zero)
{
handle = GetInternalBitmap().nativeImage;
}
return handle;
}
}
#endif
[Browsable(false)]
public int Height
{
get
{
if (disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return iconSize.Height;
}
}
public Size Size
{
get
{
if (disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return iconSize;
}
}
[Browsable(false)]
public int Width
{
get
{
if (disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return iconSize.Width;
}
}
~Icon()
{
Dispose();
}
private void InitFromStreamWithSize(Stream stream, int width, int height)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (stream.Length == 0)
throw new System.ArgumentException("The argument 'stream' must be a picture that can be used as a Icon", "stream");
//read the icon header
BinaryReader reader = new BinaryReader(stream);
//iconDir = new IconDir ();
iconDir.idReserved = reader.ReadUInt16();
if (iconDir.idReserved != 0) //must be 0
throw new System.ArgumentException("Invalid Argument", "stream");
iconDir.idType = reader.ReadUInt16();
if (iconDir.idType != 1) //must be 1
throw new System.ArgumentException("Invalid Argument", "stream");
ushort dirEntryCount = reader.ReadUInt16();
imageData = new ImageData[dirEntryCount];
iconDir.idCount = dirEntryCount;
iconDir.idEntries = new IconDirEntry[dirEntryCount];
bool sizeObtained = false;
// now read in the IconDirEntry structures
for (int i = 0; i < dirEntryCount; i++)
{
IconDirEntry ide;
ide.width = reader.ReadByte();
ide.height = reader.ReadByte();
ide.colorCount = reader.ReadByte();
ide.reserved = reader.ReadByte();
ide.planes = reader.ReadUInt16();
ide.bitCount = reader.ReadUInt16();
ide.bytesInRes = reader.ReadUInt32();
ide.imageOffset = reader.ReadUInt32();
// Vista 256x256 icons points directly to a PNG bitmap
// 256x256 icons are decoded as 0x0 (width and height are encoded as BYTE)
// and we ignore them just like MS does (at least up to fx 2.0)
// Added: storing data so it can be saved back
if ((ide.width == 0) && (ide.height == 0))
ide.ignore = true;
else
ide.ignore = false;
iconDir.idEntries[i] = ide;
//is this is the best fit??
if (!sizeObtained)
{
if (((ide.height == height) || (ide.width == width)) && !ide.ignore)
{
this.id = (ushort)i;
sizeObtained = true;
this.iconSize.Height = ide.height;
this.iconSize.Width = ide.width;
}
}
}
// throw error if no valid entries found
int valid = 0;
for (int i = 0; i < dirEntryCount; i++)
{
if (!(iconDir.idEntries[i].ignore))
valid++;
}
if (valid == 0)
throw new Win32Exception(0, "No valid icon entry were found.");
// if we havent found the best match, return the one with the
// largest size. Is this approach correct??
if (!sizeObtained)
{
uint largestSize = 0;
for (int j = 0; j < dirEntryCount; j++)
{
if (iconDir.idEntries[j].bytesInRes >= largestSize && !iconDir.idEntries[j].ignore)
{
largestSize = iconDir.idEntries[j].bytesInRes;
this.id = (ushort)j;
this.iconSize.Height = iconDir.idEntries[j].height;
this.iconSize.Width = iconDir.idEntries[j].width;
}
}
}
//now read in the icon data
for (int j = 0; j < dirEntryCount; j++)
{
// process ignored into IconDump
if (iconDir.idEntries[j].ignore)
{
IconDump id = new IconDump();
stream.Seek(iconDir.idEntries[j].imageOffset, SeekOrigin.Begin);
id.data = new byte[iconDir.idEntries[j].bytesInRes];
stream.Read(id.data, 0, id.data.Length);
imageData[j] = id;
continue;
}
// standard image
IconImage iidata = new IconImage();
BitmapInfoHeader bih = new BitmapInfoHeader();
stream.Seek(iconDir.idEntries[j].imageOffset, SeekOrigin.Begin);
byte[] buffer = new byte[iconDir.idEntries[j].bytesInRes];
stream.Read(buffer, 0, buffer.Length);
BinaryReader bihReader = new BinaryReader(new MemoryStream(buffer));
bih.biSize = bihReader.ReadUInt32();
bih.biWidth = bihReader.ReadInt32();
bih.biHeight = bihReader.ReadInt32();
bih.biPlanes = bihReader.ReadUInt16();
bih.biBitCount = bihReader.ReadUInt16();
bih.biCompression = bihReader.ReadUInt32();
bih.biSizeImage = bihReader.ReadUInt32();
bih.biXPelsPerMeter = bihReader.ReadInt32();
bih.biYPelsPerMeter = bihReader.ReadInt32();
bih.biClrUsed = bihReader.ReadUInt32();
bih.biClrImportant = bihReader.ReadUInt32();
iidata.iconHeader = bih;
//Read the number of colors used and corresponding memory occupied by
//color table. Fill this memory chunk into rgbquad[]
int numColors;
switch (bih.biBitCount)
{
case 1:
numColors = 2;
break;
case 4:
numColors = 16;
break;
case 8:
numColors = 256;
break;
default:
numColors = 0;
break;
}
iidata.iconColors = new uint[numColors];
for (int i = 0; i < numColors; i++)
iidata.iconColors[i] = bihReader.ReadUInt32();
//XOR mask is immediately after ColorTable and its size is
//icon height* no. of bytes per line
//icon height is half of BITMAPINFOHEADER.biHeight, since it contains
//both XOR as well as AND mask bytes
int iconHeight = bih.biHeight / 2;
//bytes per line should should be uint aligned
int numBytesPerLine = ((((bih.biWidth * bih.biPlanes * bih.biBitCount) + 31) >> 5) << 2);
//Determine the XOR array Size
int xorSize = numBytesPerLine * iconHeight;
iidata.iconXOR = new byte[xorSize];
int nread = bihReader.Read(iidata.iconXOR, 0, xorSize);
if (nread != xorSize)
{
string msg = string.Format("{0} data length expected {1}, read {2}", "XOR", xorSize, nread);
throw new ArgumentException(msg, "stream");
}
//Determine the AND array size
numBytesPerLine = (int)((((bih.biWidth) + 31) & ~31) >> 3);
int andSize = numBytesPerLine * iconHeight;
iidata.iconAND = new byte[andSize];
nread = bihReader.Read(iidata.iconAND, 0, andSize);
if (nread != andSize)
{
string msg = string.Format("{0} data length expected {1}, read {2}", "AND", andSize, nread);
throw new ArgumentException(msg, "stream");
}
imageData[j] = iidata;
bihReader.Dispose();
}
reader.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.
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using Microsoft.Xml;
using Microsoft.Xml.Schema;
using DataContractDictionary = System.Collections.Generic.Dictionary<Microsoft.Xml.XmlQualifiedName, DataContract>;
using SchemaObjectDictionary = System.Collections.Generic.Dictionary<Microsoft.Xml.XmlQualifiedName, SchemaObjectInfo>;
internal class SchemaImporter
{
private DataContractSet _dataContractSet;
private XmlSchemaSet _schemaSet;
private ICollection<XmlQualifiedName> _typeNames;
private ICollection<XmlSchemaElement> _elements;
private XmlQualifiedName[] _elementTypeNames;
private bool _importXmlDataType;
private SchemaObjectDictionary _schemaObjects;
private List<XmlSchemaRedefine> _redefineList;
private bool _needToImportKnownTypesForObject;
// TODO: [Fx.Tag.SecurityNote(Critical = "Static field used to store serialization schema elements from future versions."
// + " Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
private static Hashtable s_serializationSchemaElements;
internal SchemaImporter(XmlSchemaSet schemas, ICollection<XmlQualifiedName> typeNames, ICollection<XmlSchemaElement> elements, XmlQualifiedName[] elementTypeNames, DataContractSet dataContractSet, bool importXmlDataType)
{
_dataContractSet = dataContractSet;
_schemaSet = schemas;
_typeNames = typeNames;
_elements = elements;
_elementTypeNames = elementTypeNames;
_importXmlDataType = importXmlDataType;
}
internal void Import()
{
if (!_schemaSet.Contains(Globals.SerializationNamespace))
{
StringReader reader = new StringReader(Globals.SerializationSchema);
XmlSchema schema = XmlSchema.Read(reader, null);
if (schema == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRSerialization.CouldNotReadSerializationSchema, Globals.SerializationNamespace)));
_schemaSet.Add(schema);
}
try
{
CompileSchemaSet(_schemaSet);
}
#pragma warning disable 56500 // covered by FxCOP
catch (Exception ex)
{
if (DiagnosticUtility.IsFatal(ex))
{
throw;
}
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRSerialization.CannotImportInvalidSchemas), ex));
}
if (_typeNames == null)
{
ICollection schemaList = _schemaSet.Schemas();
foreach (object schemaObj in schemaList)
{
if (schemaObj == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRSerialization.CannotImportNullSchema)));
XmlSchema schema = (XmlSchema)schemaObj;
if (schema.TargetNamespace != Globals.SerializationNamespace
&& schema.TargetNamespace != Globals.SchemaNamespace)
{
foreach (XmlSchemaObject typeObj in schema.SchemaTypes.Values)
{
ImportType((XmlSchemaType)typeObj);
}
foreach (XmlSchemaElement element in schema.Elements.Values)
{
if (element.SchemaType != null)
ImportAnonymousGlobalElement(element, element.QualifiedName, schema.TargetNamespace);
}
}
}
}
else
{
foreach (XmlQualifiedName typeName in _typeNames)
{
if (typeName == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRSerialization.CannotImportNullDataContractName)));
ImportType(typeName);
}
if (_elements != null)
{
int i = 0;
foreach (XmlSchemaElement element in _elements)
{
XmlQualifiedName typeName = element.SchemaTypeName;
if (typeName != null && typeName.Name.Length > 0)
{
_elementTypeNames[i++] = ImportType(typeName).StableName;
}
else
{
XmlSchema schema = SchemaHelper.GetSchemaWithGlobalElementDeclaration(element, _schemaSet);
if (schema == null)
{
_elementTypeNames[i++] = ImportAnonymousElement(element, element.QualifiedName).StableName;
}
else
{
_elementTypeNames[i++] = ImportAnonymousGlobalElement(element, element.QualifiedName, schema.TargetNamespace).StableName;
}
}
}
}
}
ImportKnownTypesForObject();
}
internal static void CompileSchemaSet(XmlSchemaSet schemaSet)
{
if (schemaSet.Contains(XmlSchema.Namespace))
schemaSet.Compile();
else
{
// Add base XSD schema with top level element named "schema"
XmlSchema xsdSchema = new XmlSchema();
xsdSchema.TargetNamespace = XmlSchema.Namespace;
XmlSchemaElement element = new XmlSchemaElement();
element.Name = Globals.SchemaLocalName;
element.SchemaType = new XmlSchemaComplexType();
xsdSchema.Items.Add(element);
schemaSet.Add(xsdSchema);
schemaSet.Compile();
}
}
private SchemaObjectDictionary SchemaObjects
{
get
{
if (_schemaObjects == null)
_schemaObjects = CreateSchemaObjects();
return _schemaObjects;
}
}
private List<XmlSchemaRedefine> RedefineList
{
get
{
if (_redefineList == null)
_redefineList = CreateRedefineList();
return _redefineList;
}
}
private void ImportKnownTypes(XmlQualifiedName typeName)
{
SchemaObjectInfo schemaObjectInfo;
if (SchemaObjects.TryGetValue(typeName, out schemaObjectInfo))
{
List<XmlSchemaType> knownTypes = schemaObjectInfo.knownTypes;
if (knownTypes != null)
{
foreach (XmlSchemaType knownType in knownTypes)
ImportType(knownType);
}
}
}
internal static bool IsObjectContract(DataContract dataContract)
{
Dictionary<Type, object> previousCollectionTypes = new Dictionary<Type, object>();
while (dataContract is CollectionDataContract)
{
if (dataContract.OriginalUnderlyingType == null)
{
dataContract = ((CollectionDataContract)dataContract).ItemContract;
continue;
}
if (!previousCollectionTypes.ContainsKey(dataContract.OriginalUnderlyingType))
{
previousCollectionTypes.Add(dataContract.OriginalUnderlyingType, dataContract.OriginalUnderlyingType);
dataContract = ((CollectionDataContract)dataContract).ItemContract;
}
else
{
break;
}
}
return dataContract is PrimitiveDataContract && ((PrimitiveDataContract)dataContract).UnderlyingType == Globals.TypeOfObject;
}
private void ImportKnownTypesForObject()
{
if (!_needToImportKnownTypesForObject)
return;
_needToImportKnownTypesForObject = false;
if (_dataContractSet.KnownTypesForObject == null)
{
SchemaObjectInfo schemaObjectInfo;
if (SchemaObjects.TryGetValue(SchemaExporter.AnytypeQualifiedName, out schemaObjectInfo))
{
List<XmlSchemaType> knownTypes = schemaObjectInfo.knownTypes;
if (knownTypes != null)
{
DataContractDictionary knownDataContracts = new DataContractDictionary();
foreach (XmlSchemaType knownType in knownTypes)
{
// Expected: will throw exception if schema set contains types that are not supported
DataContract dataContract = ImportType(knownType);
DataContract existingContract;
if (!knownDataContracts.TryGetValue(dataContract.StableName, out existingContract))
{
knownDataContracts.Add(dataContract.StableName, dataContract);
}
}
_dataContractSet.KnownTypesForObject = knownDataContracts;
}
}
}
}
internal SchemaObjectDictionary CreateSchemaObjects()
{
SchemaObjectDictionary schemaObjects = new SchemaObjectDictionary();
ICollection schemaList = _schemaSet.Schemas();
List<XmlSchemaType> knownTypesForObject = new List<XmlSchemaType>();
schemaObjects.Add(SchemaExporter.AnytypeQualifiedName, new SchemaObjectInfo(null, null, null, knownTypesForObject));
foreach (XmlSchema schema in schemaList)
{
if (schema.TargetNamespace != Globals.SerializationNamespace)
{
foreach (XmlSchemaObject schemaObj in schema.SchemaTypes.Values)
{
XmlSchemaType schemaType = schemaObj as XmlSchemaType;
if (schemaType != null)
{
knownTypesForObject.Add(schemaType);
XmlQualifiedName currentTypeName = new XmlQualifiedName(schemaType.Name, schema.TargetNamespace);
SchemaObjectInfo schemaObjectInfo;
if (schemaObjects.TryGetValue(currentTypeName, out schemaObjectInfo))
{
schemaObjectInfo.type = schemaType;
schemaObjectInfo.schema = schema;
}
else
{
schemaObjects.Add(currentTypeName, new SchemaObjectInfo(schemaType, null, schema, null));
}
XmlQualifiedName baseTypeName = GetBaseTypeName(schemaType);
if (baseTypeName != null)
{
SchemaObjectInfo baseTypeInfo;
if (schemaObjects.TryGetValue(baseTypeName, out baseTypeInfo))
{
if (baseTypeInfo.knownTypes == null)
{
baseTypeInfo.knownTypes = new List<XmlSchemaType>();
}
}
else
{
baseTypeInfo = new SchemaObjectInfo(null, null, null, new List<XmlSchemaType>());
schemaObjects.Add(baseTypeName, baseTypeInfo);
}
baseTypeInfo.knownTypes.Add(schemaType);
}
}
}
foreach (XmlSchemaObject schemaObj in schema.Elements.Values)
{
XmlSchemaElement schemaElement = schemaObj as XmlSchemaElement;
if (schemaElement != null)
{
XmlQualifiedName currentElementName = new XmlQualifiedName(schemaElement.Name, schema.TargetNamespace);
SchemaObjectInfo schemaObjectInfo;
if (schemaObjects.TryGetValue(currentElementName, out schemaObjectInfo))
{
schemaObjectInfo.element = schemaElement;
schemaObjectInfo.schema = schema;
}
else
{
schemaObjects.Add(currentElementName, new SchemaObjectInfo(null, schemaElement, schema, null));
}
}
}
}
}
return schemaObjects;
}
private XmlQualifiedName GetBaseTypeName(XmlSchemaType type)
{
XmlQualifiedName baseTypeName = null;
XmlSchemaComplexType complexType = type as XmlSchemaComplexType;
if (complexType != null)
{
if (complexType.ContentModel != null)
{
XmlSchemaComplexContent complexContent = complexType.ContentModel as XmlSchemaComplexContent;
if (complexContent != null)
{
XmlSchemaComplexContentExtension extension = complexContent.Content as XmlSchemaComplexContentExtension;
if (extension != null)
baseTypeName = extension.BaseTypeName;
}
}
}
return baseTypeName;
}
private List<XmlSchemaRedefine> CreateRedefineList()
{
List<XmlSchemaRedefine> list = new List<XmlSchemaRedefine>();
ICollection schemaList = _schemaSet.Schemas();
foreach (object schemaObj in schemaList)
{
XmlSchema schema = schemaObj as XmlSchema;
if (schema == null)
continue;
foreach (XmlSchemaExternal ext in schema.Includes)
{
XmlSchemaRedefine redefine = ext as XmlSchemaRedefine;
if (redefine != null)
list.Add(redefine);
}
}
return list;
}
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets critical properties on XmlDataContract.",
// Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
private DataContract ImportAnonymousGlobalElement(XmlSchemaElement element, XmlQualifiedName typeQName, string ns)
{
DataContract contract = ImportAnonymousElement(element, typeQName);
XmlDataContract xmlDataContract = contract as XmlDataContract;
if (xmlDataContract != null)
{
xmlDataContract.SetTopLevelElementName(new XmlQualifiedName(element.Name, ns));
xmlDataContract.IsTopLevelElementNullable = element.IsNillable;
}
return contract;
}
private DataContract ImportAnonymousElement(XmlSchemaElement element, XmlQualifiedName typeQName)
{
if (SchemaHelper.GetSchemaType(SchemaObjects, typeQName) != null)
{
for (int i = 1; ; i++)
{
typeQName = new XmlQualifiedName(typeQName.Name + i.ToString(NumberFormatInfo.InvariantInfo), typeQName.Namespace);
if (SchemaHelper.GetSchemaType(SchemaObjects, typeQName) == null)
break;
if (i == Int32.MaxValue)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.CannotComputeUniqueName, element.Name)));
}
}
if (element.SchemaType == null)
return ImportType(SchemaExporter.AnytypeQualifiedName);
else
return ImportType(element.SchemaType, typeQName, true/*isAnonymous*/);
}
private DataContract ImportType(XmlQualifiedName typeName)
{
DataContract dataContract = DataContract.GetBuiltInDataContract(typeName.Name, typeName.Namespace);
if (dataContract == null)
{
XmlSchemaType type = SchemaHelper.GetSchemaType(SchemaObjects, typeName);
if (type == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.SpecifiedTypeNotFoundInSchema, typeName.Name, typeName.Namespace)));
dataContract = ImportType(type);
}
if (IsObjectContract(dataContract))
_needToImportKnownTypesForObject = true;
return dataContract;
}
private DataContract ImportType(XmlSchemaType type)
{
return ImportType(type, type.QualifiedName, false/*isAnonymous*/);
}
private DataContract ImportType(XmlSchemaType type, XmlQualifiedName typeName, bool isAnonymous)
{
DataContract dataContract = _dataContractSet[typeName];
if (dataContract != null)
return dataContract;
InvalidDataContractException invalidContractException;
try
{
foreach (XmlSchemaRedefine redefine in RedefineList)
{
if (redefine.SchemaTypes[typeName] != null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.RedefineNotSupported));
}
if (type is XmlSchemaSimpleType)
{
XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)type;
XmlSchemaSimpleTypeContent content = simpleType.Content;
if (content is XmlSchemaSimpleTypeUnion)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.SimpleTypeUnionNotSupported));
else if (content is XmlSchemaSimpleTypeList)
dataContract = ImportFlagsEnum(typeName, (XmlSchemaSimpleTypeList)content, simpleType.Annotation);
else if (content is XmlSchemaSimpleTypeRestriction)
{
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)content;
if (CheckIfEnum(restriction))
{
dataContract = ImportEnum(typeName, restriction, false /*isFlags*/, simpleType.Annotation);
}
else
{
dataContract = ImportSimpleTypeRestriction(typeName, restriction);
if (dataContract.IsBuiltInDataContract && !isAnonymous)
{
_dataContractSet.InternalAdd(typeName, dataContract);
}
}
}
}
else if (type is XmlSchemaComplexType)
{
XmlSchemaComplexType complexType = (XmlSchemaComplexType)type;
if (complexType.ContentModel == null)
{
CheckComplexType(typeName, complexType);
dataContract = ImportType(typeName, complexType.Particle, complexType.Attributes, complexType.AnyAttribute, null /* baseTypeName */, complexType.Annotation);
}
else
{
XmlSchemaContentModel contentModel = complexType.ContentModel;
if (contentModel is XmlSchemaSimpleContent)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.SimpleContentNotSupported));
else if (contentModel is XmlSchemaComplexContent)
{
XmlSchemaComplexContent complexContent = (XmlSchemaComplexContent)contentModel;
if (complexContent.IsMixed)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.MixedContentNotSupported));
if (complexContent.Content is XmlSchemaComplexContentExtension)
{
XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)complexContent.Content;
dataContract = ImportType(typeName, extension.Particle, extension.Attributes, extension.AnyAttribute, extension.BaseTypeName, complexType.Annotation);
}
else if (complexContent.Content is XmlSchemaComplexContentRestriction)
{
XmlSchemaComplexContentRestriction restriction = (XmlSchemaComplexContentRestriction)complexContent.Content;
XmlQualifiedName baseTypeName = restriction.BaseTypeName;
if (baseTypeName == SchemaExporter.AnytypeQualifiedName)
dataContract = ImportType(typeName, restriction.Particle, restriction.Attributes, restriction.AnyAttribute, null /* baseTypeName */, complexType.Annotation);
else
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ComplexTypeRestrictionNotSupported));
}
}
}
}
if (dataContract == null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, String.Empty);
if (type.QualifiedName != XmlQualifiedName.Empty)
ImportTopLevelElement(typeName);
ImportDataContractExtension(type, dataContract);
ImportGenericInfo(type, dataContract);
ImportKnownTypes(typeName);
return dataContract;
}
catch (InvalidDataContractException e)
{
invalidContractException = e;
}
// Execution gets to this point if InvalidDataContractException was thrown
if (_importXmlDataType)
{
RemoveFailedContract(typeName);
return ImportXmlDataType(typeName, type, isAnonymous);
}
Type referencedType;
if (_dataContractSet.TryGetReferencedType(typeName, dataContract, out referencedType)
|| (string.IsNullOrEmpty(type.Name) && _dataContractSet.TryGetReferencedType(ImportActualType(type.Annotation, typeName, typeName), dataContract, out referencedType)))
{
if (Globals.TypeOfIXmlSerializable.GetTypeInfo().IsAssignableFrom(referencedType.GetTypeInfo()))
{
RemoveFailedContract(typeName);
return ImportXmlDataType(typeName, type, isAnonymous);
}
}
XmlDataContract specialContract = ImportSpecialXmlDataType(type, isAnonymous);
if (specialContract != null)
{
_dataContractSet.Remove(typeName);
return specialContract;
}
throw invalidContractException;
}
private void RemoveFailedContract(XmlQualifiedName typeName)
{
ClassDataContract oldContract = _dataContractSet[typeName] as ClassDataContract;
_dataContractSet.Remove(typeName);
if (oldContract != null)
{
ClassDataContract ancestorDataContract = oldContract.BaseContract;
while (ancestorDataContract != null)
{
ancestorDataContract.KnownDataContracts.Remove(typeName);
ancestorDataContract = ancestorDataContract.BaseContract;
}
if (_dataContractSet.KnownTypesForObject != null)
_dataContractSet.KnownTypesForObject.Remove(typeName);
}
}
private bool CheckIfEnum(XmlSchemaSimpleTypeRestriction restriction)
{
foreach (XmlSchemaFacet facet in restriction.Facets)
{
if (!(facet is XmlSchemaEnumerationFacet))
return false;
}
XmlQualifiedName expectedBase = SchemaExporter.StringQualifiedName;
if (restriction.BaseTypeName != XmlQualifiedName.Empty)
{
return ((restriction.BaseTypeName == expectedBase && restriction.Facets.Count > 0) || ImportType(restriction.BaseTypeName) is EnumDataContract);
}
else if (restriction.BaseType != null)
{
DataContract baseContract = ImportType(restriction.BaseType);
return (baseContract.StableName == expectedBase || baseContract is EnumDataContract);
}
return false;
}
private bool CheckIfCollection(XmlSchemaSequence rootSequence)
{
if (rootSequence.Items == null || rootSequence.Items.Count == 0)
return false;
RemoveOptionalUnknownSerializationElements(rootSequence.Items);
if (rootSequence.Items.Count != 1)
return false;
XmlSchemaObject o = rootSequence.Items[0];
if (!(o is XmlSchemaElement))
return false;
XmlSchemaElement localElement = (XmlSchemaElement)o;
return (localElement.MaxOccursString == Globals.OccursUnbounded || localElement.MaxOccurs > 1);
}
private bool CheckIfISerializable(XmlSchemaSequence rootSequence, XmlSchemaObjectCollection attributes)
{
if (rootSequence.Items == null || rootSequence.Items.Count == 0)
return false;
RemoveOptionalUnknownSerializationElements(rootSequence.Items);
if (attributes == null || attributes.Count == 0)
return false;
return (rootSequence.Items.Count == 1 && rootSequence.Items[0] is XmlSchemaAny);
}
// TODO: [Fx.Tag.SecurityNote(Critical = "Initializes critical static fields.",
// Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
private void RemoveOptionalUnknownSerializationElements(XmlSchemaObjectCollection items)
{
for (int i = 0; i < items.Count; i++)
{
XmlSchemaElement element = items[i] as XmlSchemaElement;
if (element != null && element.RefName != null &&
element.RefName.Namespace == Globals.SerializationNamespace &&
element.MinOccurs == 0)
{
if (s_serializationSchemaElements == null)
{
XmlSchema serializationSchema = XmlSchema.Read(XmlReader.Create(new StringReader(Globals.SerializationSchema)), null);
s_serializationSchemaElements = new Hashtable();
foreach (XmlSchemaObject schemaObject in serializationSchema.Items)
{
XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement;
if (schemaElement != null)
s_serializationSchemaElements.Add(schemaElement.Name, schemaElement);
}
}
if (!s_serializationSchemaElements.ContainsKey(element.RefName.Name))
{
items.RemoveAt(i);
i--;
}
}
}
}
private DataContract ImportType(XmlQualifiedName typeName, XmlSchemaParticle rootParticle, XmlSchemaObjectCollection attributes, XmlSchemaAnyAttribute anyAttribute, XmlQualifiedName baseTypeName, XmlSchemaAnnotation annotation)
{
DataContract dataContract = null;
bool isDerived = (baseTypeName != null);
bool isReference;
ImportAttributes(typeName, attributes, anyAttribute, out isReference);
if (rootParticle == null)
dataContract = ImportClass(typeName, new XmlSchemaSequence(), baseTypeName, annotation, isReference);
else if (!(rootParticle is XmlSchemaSequence))
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.RootParticleMustBeSequence));
else
{
XmlSchemaSequence rootSequence = (XmlSchemaSequence)rootParticle;
if (rootSequence.MinOccurs != 1)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.RootSequenceMustBeRequired));
if (rootSequence.MaxOccurs != 1)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.RootSequenceMaxOccursMustBe));
if (!isDerived && CheckIfCollection(rootSequence))
dataContract = ImportCollection(typeName, rootSequence, attributes, annotation, isReference);
else if (CheckIfISerializable(rootSequence, attributes))
dataContract = ImportISerializable(typeName, rootSequence, baseTypeName, attributes, annotation);
else
dataContract = ImportClass(typeName, rootSequence, baseTypeName, annotation, isReference);
}
return dataContract;
}
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets critical properties on ClassDataContract.",
// Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
private ClassDataContract ImportClass(XmlQualifiedName typeName, XmlSchemaSequence rootSequence, XmlQualifiedName baseTypeName, XmlSchemaAnnotation annotation, bool isReference)
{
ClassDataContract dataContract = new ClassDataContract();
dataContract.StableName = typeName;
AddDataContract(dataContract);
dataContract.IsValueType = IsValueType(typeName, annotation);
dataContract.IsReference = isReference;
if (baseTypeName != null)
{
ImportBaseContract(baseTypeName, dataContract);
if (dataContract.BaseContract.IsISerializable)
{
if (IsISerializableDerived(typeName, rootSequence))
dataContract.IsISerializable = true;
else
ThrowTypeCannotBeImportedException(dataContract.StableName.Name, dataContract.StableName.Namespace, string.Format(SRSerialization.DerivedTypeNotISerializable, baseTypeName.Name, baseTypeName.Namespace));
}
if (dataContract.BaseContract.IsReference)
{
dataContract.IsReference = true;
}
}
if (!dataContract.IsISerializable)
{
dataContract.Members = new List<DataMember>();
RemoveOptionalUnknownSerializationElements(rootSequence.Items);
for (int memberIndex = 0; memberIndex < rootSequence.Items.Count; memberIndex++)
{
XmlSchemaElement element = rootSequence.Items[memberIndex] as XmlSchemaElement;
if (element == null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.MustContainOnlyLocalElements));
ImportClassMember(element, dataContract);
}
}
return dataContract;
}
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets critical properties on XmlDataContract.",
// Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
private DataContract ImportXmlDataType(XmlQualifiedName typeName, XmlSchemaType xsdType, bool isAnonymous)
{
DataContract dataContract = _dataContractSet[typeName];
if (dataContract != null)
return dataContract;
XmlDataContract xmlDataContract = ImportSpecialXmlDataType(xsdType, isAnonymous);
if (xmlDataContract != null)
return xmlDataContract;
xmlDataContract = new XmlDataContract();
xmlDataContract.StableName = typeName;
xmlDataContract.IsValueType = false;
AddDataContract(xmlDataContract);
if (xsdType != null)
{
ImportDataContractExtension(xsdType, xmlDataContract);
xmlDataContract.IsValueType = IsValueType(typeName, xsdType.Annotation);
xmlDataContract.IsTypeDefinedOnImport = true;
xmlDataContract.XsdType = isAnonymous ? xsdType : null;
xmlDataContract.HasRoot = !IsXmlAnyElementType(xsdType as XmlSchemaComplexType);
}
else
{
//Value type can be used by both nillable and non-nillable elements but reference type cannot be used by non nillable elements
xmlDataContract.IsValueType = true;
xmlDataContract.IsTypeDefinedOnImport = false;
xmlDataContract.HasRoot = true;
}
if (!isAnonymous)
{
bool isNullable;
xmlDataContract.SetTopLevelElementName(SchemaHelper.GetGlobalElementDeclaration(_schemaSet, typeName, out isNullable));
xmlDataContract.IsTopLevelElementNullable = isNullable;
}
return xmlDataContract;
}
private XmlDataContract ImportSpecialXmlDataType(XmlSchemaType xsdType, bool isAnonymous)
{
if (!isAnonymous)
return null;
XmlSchemaComplexType complexType = xsdType as XmlSchemaComplexType;
if (complexType == null)
return null;
if (IsXmlAnyElementType(complexType))
{
//check if the type is XElement
XmlQualifiedName xlinqTypeName = new XmlQualifiedName("XElement", "http://schemas.datacontract.org/2004/07/System.Xml.Linq");
Type referencedType;
if (_dataContractSet.TryGetReferencedType(xlinqTypeName, null, out referencedType)
&& Globals.TypeOfIXmlSerializable.IsAssignableFrom(referencedType))
{
XmlDataContract xmlDataContract = new XmlDataContract(referencedType);
AddDataContract(xmlDataContract);
return xmlDataContract;
}
//otherwise, assume XmlElement
return (XmlDataContract)DataContract.GetBuiltInDataContract(Globals.TypeOfXmlElement);
}
if (IsXmlAnyType(complexType))
return (XmlDataContract)DataContract.GetBuiltInDataContract(Globals.TypeOfXmlNodeArray);
return null;
}
private bool IsXmlAnyElementType(XmlSchemaComplexType xsdType)
{
if (xsdType == null)
return false;
XmlSchemaSequence sequence = xsdType.Particle as XmlSchemaSequence;
if (sequence == null)
return false;
if (sequence.Items == null || sequence.Items.Count != 1)
return false;
XmlSchemaAny any = sequence.Items[0] as XmlSchemaAny;
if (any == null || any.Namespace != null)
return false;
if (xsdType.AnyAttribute != null || (xsdType.Attributes != null && xsdType.Attributes.Count > 0))
return false;
return true;
}
private bool IsXmlAnyType(XmlSchemaComplexType xsdType)
{
if (xsdType == null)
return false;
XmlSchemaSequence sequence = xsdType.Particle as XmlSchemaSequence;
if (sequence == null)
return false;
if (sequence.Items == null || sequence.Items.Count != 1)
return false;
XmlSchemaAny any = sequence.Items[0] as XmlSchemaAny;
if (any == null || any.Namespace != null)
return false;
if (any.MaxOccurs != Decimal.MaxValue)
return false;
if (xsdType.AnyAttribute == null || xsdType.Attributes.Count > 0)
return false;
return true;
}
private bool IsValueType(XmlQualifiedName typeName, XmlSchemaAnnotation annotation)
{
string isValueTypeInnerText = GetInnerText(typeName, ImportAnnotation(annotation, SchemaExporter.IsValueTypeName));
if (isValueTypeInnerText != null)
{
try
{
return XmlConvert.ToBoolean(isValueTypeInnerText);
}
catch (FormatException fe)
{
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.IsValueTypeFormattedIncorrectly, isValueTypeInnerText, fe.Message));
}
}
return false;
}
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets critical properties on ClassDataContract.",
// Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
private ClassDataContract ImportISerializable(XmlQualifiedName typeName, XmlSchemaSequence rootSequence, XmlQualifiedName baseTypeName, XmlSchemaObjectCollection attributes, XmlSchemaAnnotation annotation)
{
ClassDataContract dataContract = new ClassDataContract();
dataContract.StableName = typeName;
dataContract.IsISerializable = true;
AddDataContract(dataContract);
dataContract.IsValueType = IsValueType(typeName, annotation);
if (baseTypeName == null)
CheckISerializableBase(typeName, rootSequence, attributes);
else
{
ImportBaseContract(baseTypeName, dataContract);
if (!dataContract.BaseContract.IsISerializable)
ThrowISerializableTypeCannotBeImportedException(dataContract.StableName.Name, dataContract.StableName.Namespace, string.Format(SRSerialization.BaseTypeNotISerializable, baseTypeName.Name, baseTypeName.Namespace));
if (!IsISerializableDerived(typeName, rootSequence))
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ISerializableDerivedContainsOneOrMoreItems));
}
return dataContract;
}
private void CheckISerializableBase(XmlQualifiedName typeName, XmlSchemaSequence rootSequence, XmlSchemaObjectCollection attributes)
{
if (rootSequence == null)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ISerializableDoesNotContainAny));
if (rootSequence.Items == null || rootSequence.Items.Count < 1)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ISerializableDoesNotContainAny));
else if (rootSequence.Items.Count > 1)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ISerializableContainsMoreThanOneItems));
XmlSchemaObject o = rootSequence.Items[0];
if (!(o is XmlSchemaAny))
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ISerializableDoesNotContainAny));
XmlSchemaAny wildcard = (XmlSchemaAny)o;
XmlSchemaAny iSerializableWildcardElement = SchemaExporter.ISerializableWildcardElement;
if (wildcard.MinOccurs != iSerializableWildcardElement.MinOccurs)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ISerializableWildcardMinOccursMustBe, iSerializableWildcardElement.MinOccurs));
if (wildcard.MaxOccursString != iSerializableWildcardElement.MaxOccursString)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ISerializableWildcardMaxOccursMustBe, iSerializableWildcardElement.MaxOccursString));
if (wildcard.Namespace != iSerializableWildcardElement.Namespace)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ISerializableWildcardNamespaceInvalid, iSerializableWildcardElement.Namespace));
if (wildcard.ProcessContents != iSerializableWildcardElement.ProcessContents)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ISerializableWildcardProcessContentsInvalid, iSerializableWildcardElement.ProcessContents));
XmlQualifiedName factoryTypeAttributeRefName = SchemaExporter.ISerializableFactoryTypeAttribute.RefName;
bool containsFactoryTypeAttribute = false;
if (attributes != null)
{
for (int i = 0; i < attributes.Count; i++)
{
o = attributes[i];
if (o is XmlSchemaAttribute)
{
if (((XmlSchemaAttribute)o).RefName == factoryTypeAttributeRefName)
{
containsFactoryTypeAttribute = true;
break;
}
}
}
}
if (!containsFactoryTypeAttribute)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ISerializableMustRefFactoryTypeAttribute, factoryTypeAttributeRefName.Name, factoryTypeAttributeRefName.Namespace));
}
private bool IsISerializableDerived(XmlQualifiedName typeName, XmlSchemaSequence rootSequence)
{
return (rootSequence == null || rootSequence.Items == null || rootSequence.Items.Count == 0);
}
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets critical BaseContract property on ClassDataContract.",
// Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
private void ImportBaseContract(XmlQualifiedName baseTypeName, ClassDataContract dataContract)
{
ClassDataContract baseContract = ImportType(baseTypeName) as ClassDataContract;
if (baseContract == null)
ThrowTypeCannotBeImportedException(dataContract.StableName.Name, dataContract.StableName.Namespace, string.Format(dataContract.IsISerializable ? SRSerialization.InvalidISerializableDerivation : SRSerialization.InvalidClassDerivation, baseTypeName.Name, baseTypeName.Namespace));
// Note: code ignores IsValueType annotation if derived type exists
if (baseContract.IsValueType)
baseContract.IsValueType = false;
ClassDataContract ancestorDataContract = baseContract;
while (ancestorDataContract != null)
{
DataContractDictionary knownDataContracts = ancestorDataContract.KnownDataContracts;
if (knownDataContracts == null)
{
knownDataContracts = new DataContractDictionary();
ancestorDataContract.KnownDataContracts = knownDataContracts;
}
knownDataContracts.Add(dataContract.StableName, dataContract);
ancestorDataContract = ancestorDataContract.BaseContract;
}
dataContract.BaseContract = baseContract;
}
private void ImportTopLevelElement(XmlQualifiedName typeName)
{
XmlSchemaElement topLevelElement = SchemaHelper.GetSchemaElement(SchemaObjects, typeName);
// Top level element of same name is not required, but is validated if it is present
if (topLevelElement == null)
return;
else
{
XmlQualifiedName elementTypeName = topLevelElement.SchemaTypeName;
if (elementTypeName.IsEmpty)
{
if (topLevelElement.SchemaType != null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.AnonymousTypeNotSupported, typeName.Name, typeName.Namespace));
else
elementTypeName = SchemaExporter.AnytypeQualifiedName;
}
if (elementTypeName != typeName)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.TopLevelElementRepresentsDifferentType, topLevelElement.SchemaTypeName.Name, topLevelElement.SchemaTypeName.Namespace));
CheckIfElementUsesUnsupportedConstructs(typeName, topLevelElement);
}
}
private void ImportClassMember(XmlSchemaElement element, ClassDataContract dataContract)
{
XmlQualifiedName typeName = dataContract.StableName;
if (element.MinOccurs > 1)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ElementMinOccursMustBe, element.Name));
if (element.MaxOccurs != 1)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ElementMaxOccursMustBe, element.Name));
DataContract memberTypeContract = null;
string memberName = element.Name;
bool memberIsRequired = (element.MinOccurs > 0);
bool memberIsNullable = element.IsNillable;
bool memberEmitDefaultValue;
int memberOrder = 0;
XmlSchemaForm? elementForm = (element.Form == XmlSchemaForm.None) ? SchemaHelper.GetSchemaWithType(SchemaObjects, _schemaSet, typeName)?.ElementFormDefault : element.Form;
if (elementForm != XmlSchemaForm.Qualified)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.FormMustBeQualified, element.Name));
CheckIfElementUsesUnsupportedConstructs(typeName, element);
if (element.SchemaTypeName.IsEmpty)
{
if (element.SchemaType != null)
memberTypeContract = ImportAnonymousElement(element, new XmlQualifiedName(String.Format(CultureInfo.InvariantCulture, "{0}.{1}Type", typeName.Name, element.Name), typeName.Namespace));
else if (!element.RefName.IsEmpty)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ElementRefOnLocalElementNotSupported, element.RefName.Name, element.RefName.Namespace));
else
memberTypeContract = ImportType(SchemaExporter.AnytypeQualifiedName);
}
else
{
XmlQualifiedName memberTypeName = ImportActualType(element.Annotation, element.SchemaTypeName, typeName);
memberTypeContract = ImportType(memberTypeName);
if (IsObjectContract(memberTypeContract))
_needToImportKnownTypesForObject = true;
}
bool? emitDefaultValueFromAnnotation = ImportEmitDefaultValue(element.Annotation, typeName);
if (!memberTypeContract.IsValueType && !memberIsNullable)
{
if (emitDefaultValueFromAnnotation != null && emitDefaultValueFromAnnotation.Value)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.InvalidEmitDefaultAnnotation, memberName, typeName.Name, typeName.Namespace)));
memberEmitDefaultValue = false;
}
else
memberEmitDefaultValue = emitDefaultValueFromAnnotation != null ? emitDefaultValueFromAnnotation.Value : Globals.DefaultEmitDefaultValue;
int prevMemberIndex = dataContract.Members.Count - 1;
if (prevMemberIndex >= 0)
{
DataMember prevMember = dataContract.Members[prevMemberIndex];
if (prevMember.Order > Globals.DefaultOrder)
memberOrder = dataContract.Members.Count;
DataMember currentMember = new DataMember(memberTypeContract, memberName, memberIsNullable, memberIsRequired, memberEmitDefaultValue, memberOrder);
int compare = ClassDataContract.DataMemberComparer.Singleton.Compare(prevMember, currentMember);
if (compare == 0)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.CannotHaveDuplicateElementNames, memberName));
else if (compare > 0)
memberOrder = dataContract.Members.Count;
}
DataMember dataMember = new DataMember(memberTypeContract, memberName, memberIsNullable, memberIsRequired, memberEmitDefaultValue, memberOrder);
XmlQualifiedName surrogateDataAnnotationName = SchemaExporter.SurrogateDataAnnotationName;
_dataContractSet.SetSurrogateData(dataMember, ImportSurrogateData(ImportAnnotation(element.Annotation, surrogateDataAnnotationName), surrogateDataAnnotationName.Name, surrogateDataAnnotationName.Namespace));
dataContract.Members.Add(dataMember);
}
private bool? ImportEmitDefaultValue(XmlSchemaAnnotation annotation, XmlQualifiedName typeName)
{
XmlElement defaultValueElement = ImportAnnotation(annotation, SchemaExporter.DefaultValueAnnotation);
if (defaultValueElement == null)
return null;
XmlNode emitDefaultValueAttribute = defaultValueElement.Attributes.GetNamedItem(Globals.EmitDefaultValueAttribute);
string emitDefaultValueString = (emitDefaultValueAttribute == null) ? null : emitDefaultValueAttribute.Value;
if (emitDefaultValueString == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.AnnotationAttributeNotFound, SchemaExporter.DefaultValueAnnotation.Name, typeName.Name, typeName.Namespace, Globals.EmitDefaultValueAttribute)));
return XmlConvert.ToBoolean(emitDefaultValueString);
}
internal static XmlQualifiedName ImportActualType(XmlSchemaAnnotation annotation, XmlQualifiedName defaultTypeName, XmlQualifiedName typeName)
{
XmlElement actualTypeElement = ImportAnnotation(annotation, SchemaExporter.ActualTypeAnnotationName);
if (actualTypeElement == null)
return defaultTypeName;
XmlNode nameAttribute = actualTypeElement.Attributes.GetNamedItem(Globals.ActualTypeNameAttribute);
string name = (nameAttribute == null) ? null : nameAttribute.Value;
if (name == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.AnnotationAttributeNotFound, SchemaExporter.ActualTypeAnnotationName.Name, typeName.Name, typeName.Namespace, Globals.ActualTypeNameAttribute)));
XmlNode nsAttribute = actualTypeElement.Attributes.GetNamedItem(Globals.ActualTypeNamespaceAttribute);
string ns = (nsAttribute == null) ? null : nsAttribute.Value;
if (ns == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.AnnotationAttributeNotFound, SchemaExporter.ActualTypeAnnotationName.Name, typeName.Name, typeName.Namespace, Globals.ActualTypeNamespaceAttribute)));
return new XmlQualifiedName(name, ns);
}
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets critical properties on CollectionDataContract.",
// Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
private CollectionDataContract ImportCollection(XmlQualifiedName typeName, XmlSchemaSequence rootSequence, XmlSchemaObjectCollection attributes, XmlSchemaAnnotation annotation, bool isReference)
{
CollectionDataContract dataContract = new CollectionDataContract(CollectionKind.Array);
dataContract.StableName = typeName;
AddDataContract(dataContract);
dataContract.IsReference = isReference;
// CheckIfCollection has already checked if sequence contains exactly one item with maxOccurs="unbounded" or maxOccurs > 1
XmlSchemaElement element = (XmlSchemaElement)rootSequence.Items[0];
dataContract.IsItemTypeNullable = element.IsNillable;
dataContract.ItemName = element.Name;
XmlSchemaForm? elementForm = (element.Form == XmlSchemaForm.None) ? SchemaHelper.GetSchemaWithType(SchemaObjects, _schemaSet, typeName)?.ElementFormDefault : element.Form;
if (elementForm != XmlSchemaForm.Qualified)
ThrowArrayTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ArrayItemFormMustBe, element.Name));
CheckIfElementUsesUnsupportedConstructs(typeName, element);
if (element.SchemaTypeName.IsEmpty)
{
if (element.SchemaType != null)
{
XmlQualifiedName shortName = new XmlQualifiedName(element.Name, typeName.Namespace);
DataContract contract = _dataContractSet[shortName];
if (contract == null)
{
dataContract.ItemContract = ImportAnonymousElement(element, shortName);
}
else
{
XmlQualifiedName fullName = new XmlQualifiedName(String.Format(CultureInfo.InvariantCulture, "{0}.{1}Type", typeName.Name, element.Name), typeName.Namespace);
dataContract.ItemContract = ImportAnonymousElement(element, fullName);
}
}
else if (!element.RefName.IsEmpty)
ThrowArrayTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.ElementRefOnLocalElementNotSupported, element.RefName.Name, element.RefName.Namespace));
else
dataContract.ItemContract = ImportType(SchemaExporter.AnytypeQualifiedName);
}
else
{
dataContract.ItemContract = ImportType(element.SchemaTypeName);
}
if (IsDictionary(typeName, annotation))
{
ClassDataContract keyValueContract = dataContract.ItemContract as ClassDataContract;
DataMember key = null, value = null;
if (keyValueContract == null || keyValueContract.Members == null || keyValueContract.Members.Count != 2
|| !(key = keyValueContract.Members[0]).IsRequired || !(value = keyValueContract.Members[1]).IsRequired)
{
ThrowArrayTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.InvalidKeyValueType, element.Name));
}
if (keyValueContract.Namespace != dataContract.Namespace)
{
ThrowArrayTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.InvalidKeyValueTypeNamespace, element.Name, keyValueContract.Namespace));
}
keyValueContract.IsValueType = true;
dataContract.KeyName = key.Name;
dataContract.ValueName = value.Name;
if (element.SchemaType != null)
{
_dataContractSet.Remove(keyValueContract.StableName);
GenericInfo genericInfo = new GenericInfo(DataContract.GetStableName(Globals.TypeOfKeyValue), Globals.TypeOfKeyValue.FullName);
genericInfo.Add(GetGenericInfoForDataMember(key));
genericInfo.Add(GetGenericInfoForDataMember(value));
genericInfo.AddToLevel(0, 2);
dataContract.ItemContract.StableName = new XmlQualifiedName(genericInfo.GetExpandedStableName().Name, typeName.Namespace);
}
}
return dataContract;
}
private GenericInfo GetGenericInfoForDataMember(DataMember dataMember)
{
GenericInfo genericInfo = null;
if (dataMember.MemberTypeContract.IsValueType && dataMember.IsNullable)
{
genericInfo = new GenericInfo(DataContract.GetStableName(Globals.TypeOfNullable), Globals.TypeOfNullable.FullName);
genericInfo.Add(new GenericInfo(dataMember.MemberTypeContract.StableName, null));
}
else
{
genericInfo = new GenericInfo(dataMember.MemberTypeContract.StableName, null);
}
return genericInfo;
}
private bool IsDictionary(XmlQualifiedName typeName, XmlSchemaAnnotation annotation)
{
string isDictionaryInnerText = GetInnerText(typeName, ImportAnnotation(annotation, SchemaExporter.IsDictionaryAnnotationName));
if (isDictionaryInnerText != null)
{
try
{
return XmlConvert.ToBoolean(isDictionaryInnerText);
}
catch (FormatException fe)
{
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.IsDictionaryFormattedIncorrectly, isDictionaryInnerText, fe.Message));
}
}
return false;
}
private EnumDataContract ImportFlagsEnum(XmlQualifiedName typeName, XmlSchemaSimpleTypeList list, XmlSchemaAnnotation annotation)
{
XmlSchemaSimpleType anonymousType = list.ItemType;
if (anonymousType == null)
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.EnumListMustContainAnonymousType));
XmlSchemaSimpleTypeContent content = anonymousType.Content;
if (content is XmlSchemaSimpleTypeUnion)
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.EnumUnionInAnonymousTypeNotSupported));
else if (content is XmlSchemaSimpleTypeList)
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.EnumListInAnonymousTypeNotSupported));
else if (content is XmlSchemaSimpleTypeRestriction)
{
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)content;
if (CheckIfEnum(restriction))
return ImportEnum(typeName, restriction, true /*isFlags*/, annotation);
else
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.EnumRestrictionInvalid));
}
return null;
}
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets critical properties on EnumDataContract.",
// Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
private EnumDataContract ImportEnum(XmlQualifiedName typeName, XmlSchemaSimpleTypeRestriction restriction, bool isFlags, XmlSchemaAnnotation annotation)
{
EnumDataContract dataContract = new EnumDataContract();
dataContract.StableName = typeName;
dataContract.BaseContractName = ImportActualType(annotation, SchemaExporter.DefaultEnumBaseTypeName, typeName);
dataContract.IsFlags = isFlags;
AddDataContract(dataContract);
// CheckIfEnum has already checked if baseType of restriction is string
dataContract.Values = new List<long>();
dataContract.Members = new List<DataMember>();
foreach (XmlSchemaFacet facet in restriction.Facets)
{
XmlSchemaEnumerationFacet enumFacet = facet as XmlSchemaEnumerationFacet;
if (enumFacet == null)
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.EnumOnlyEnumerationFacetsSupported));
if (enumFacet.Value == null)
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.EnumEnumerationFacetsMustHaveValue));
string valueInnerText = GetInnerText(typeName, ImportAnnotation(enumFacet.Annotation, SchemaExporter.EnumerationValueAnnotationName));
if (valueInnerText == null)
dataContract.Values.Add(SchemaExporter.GetDefaultEnumValue(isFlags, dataContract.Members.Count));
else
dataContract.Values.Add(dataContract.GetEnumValueFromString(valueInnerText));
DataMember dataMember = new DataMember(enumFacet.Value);
dataContract.Members.Add(dataMember);
}
return dataContract;
}
private DataContract ImportSimpleTypeRestriction(XmlQualifiedName typeName, XmlSchemaSimpleTypeRestriction restriction)
{
DataContract dataContract = null;
if (!restriction.BaseTypeName.IsEmpty)
dataContract = ImportType(restriction.BaseTypeName);
else if (restriction.BaseType != null)
dataContract = ImportType(restriction.BaseType);
else
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.SimpleTypeRestrictionDoesNotSpecifyBase));
return dataContract;
}
private void ImportDataContractExtension(XmlSchemaType type, DataContract dataContract)
{
if (type.Annotation == null || type.Annotation.Items == null)
return;
foreach (XmlSchemaObject schemaObject in type.Annotation.Items)
{
XmlSchemaAppInfo appInfo = schemaObject as XmlSchemaAppInfo;
if (appInfo == null)
continue;
if (appInfo.Markup != null)
{
foreach (XmlNode xmlNode in appInfo.Markup)
{
XmlElement typeElement = xmlNode as XmlElement;
XmlQualifiedName surrogateDataAnnotationName = SchemaExporter.SurrogateDataAnnotationName;
if (typeElement != null && typeElement.NamespaceURI == surrogateDataAnnotationName.Namespace && typeElement.LocalName == surrogateDataAnnotationName.Name)
{
object surrogateData = ImportSurrogateData(typeElement, surrogateDataAnnotationName.Name, surrogateDataAnnotationName.Namespace);
_dataContractSet.SetSurrogateData(dataContract, surrogateData);
}
}
}
}
}
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets critical properties on DataContract.",
// Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
private void ImportGenericInfo(XmlSchemaType type, DataContract dataContract)
{
if (type.Annotation == null || type.Annotation.Items == null)
return;
foreach (XmlSchemaObject schemaObject in type.Annotation.Items)
{
XmlSchemaAppInfo appInfo = schemaObject as XmlSchemaAppInfo;
if (appInfo == null)
continue;
if (appInfo.Markup != null)
{
foreach (XmlNode xmlNode in appInfo.Markup)
{
XmlElement typeElement = xmlNode as XmlElement;
if (typeElement != null && typeElement.NamespaceURI == Globals.SerializationNamespace)
{
if (typeElement.LocalName == Globals.GenericTypeLocalName)
dataContract.GenericInfo = ImportGenericInfo(typeElement, type);
}
}
}
}
}
private GenericInfo ImportGenericInfo(XmlElement typeElement, XmlSchemaType type)
{
XmlNode nameAttribute = typeElement.Attributes.GetNamedItem(Globals.GenericNameAttribute);
string name = (nameAttribute == null) ? null : nameAttribute.Value;
if (name == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.GenericAnnotationAttributeNotFound, type.Name, Globals.GenericNameAttribute)));
XmlNode nsAttribute = typeElement.Attributes.GetNamedItem(Globals.GenericNamespaceAttribute);
string ns = (nsAttribute == null) ? null : nsAttribute.Value;
if (ns == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.GenericAnnotationAttributeNotFound, type.Name, Globals.GenericNamespaceAttribute)));
if (typeElement.ChildNodes.Count > 0) //Generic Type
name = DataContract.EncodeLocalName(name);
int currentLevel = 0;
GenericInfo genInfo = new GenericInfo(new XmlQualifiedName(name, ns), type.Name);
foreach (XmlNode childNode in typeElement.ChildNodes)
{
XmlElement argumentElement = childNode as XmlElement;
if (argumentElement == null)
continue;
if (argumentElement.LocalName != Globals.GenericParameterLocalName ||
argumentElement.NamespaceURI != Globals.SerializationNamespace)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.GenericAnnotationHasInvalidElement, argumentElement.LocalName, argumentElement.NamespaceURI, type.Name)));
XmlNode nestedLevelAttribute = argumentElement.Attributes.GetNamedItem(Globals.GenericParameterNestedLevelAttribute);
int argumentLevel = 0;
if (nestedLevelAttribute != null)
{
if (!Int32.TryParse(nestedLevelAttribute.Value, out argumentLevel))
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.GenericAnnotationHasInvalidAttributeValue, argumentElement.LocalName, argumentElement.NamespaceURI, type.Name, nestedLevelAttribute.Value, nestedLevelAttribute.LocalName, Globals.TypeOfInt.Name)));
}
if (argumentLevel < currentLevel)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.GenericAnnotationForNestedLevelMustBeIncreasing, argumentElement.LocalName, argumentElement.NamespaceURI, type.Name)));
genInfo.Add(ImportGenericInfo(argumentElement, type));
genInfo.AddToLevel(argumentLevel, 1);
currentLevel = argumentLevel;
}
XmlNode typeNestedLevelsAttribute = typeElement.Attributes.GetNamedItem(Globals.GenericParameterNestedLevelAttribute);
if (typeNestedLevelsAttribute != null)
{
int nestedLevels = 0;
if (!Int32.TryParse(typeNestedLevelsAttribute.Value, out nestedLevels))
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.GenericAnnotationHasInvalidAttributeValue, typeElement.LocalName, typeElement.NamespaceURI, type.Name, typeNestedLevelsAttribute.Value, typeNestedLevelsAttribute.LocalName, Globals.TypeOfInt.Name)));
if ((nestedLevels - 1) > currentLevel)
genInfo.AddToLevel(nestedLevels - 1, 0);
}
return genInfo;
}
private object ImportSurrogateData(XmlElement typeElement, string name, string ns)
{
if (_dataContractSet.DataContractSurrogate != null && typeElement != null)
{
Collection<Type> knownTypes = new Collection<Type>();
DataContractSurrogateCaller.GetKnownCustomDataTypes(_dataContractSet.DataContractSurrogate, knownTypes);
XmlDictionary dictionary = new XmlDictionary(2);
DataContractSerializer serializer = new DataContractSerializer(Globals.TypeOfObject, dictionary.Add(name), dictionary.Add(DataContract.GetNamespace(ns)), knownTypes,
Int32.MaxValue, false /*ignoreExtensionDataObject*/, true /*preserveObjectReferences*/, null /*dataContractResolver*/);
return serializer.ReadObject(new XmlNodeReader(typeElement));
}
return null;
}
private void CheckComplexType(XmlQualifiedName typeName, XmlSchemaComplexType type)
{
if (type.IsAbstract)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.AbstractTypeNotSupported));
if (type.IsMixed)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.MixedContentNotSupported));
}
private void CheckIfElementUsesUnsupportedConstructs(XmlQualifiedName typeName, XmlSchemaElement element)
{
if (element.IsAbstract)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.AbstractElementNotSupported, element.Name));
if (element.DefaultValue != null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.DefaultOnElementNotSupported, element.Name));
if (element.FixedValue != null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.FixedOnElementNotSupported, element.Name));
if (!element.SubstitutionGroup.IsEmpty)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.SubstitutionGroupOnElementNotSupported, element.Name));
}
private void ImportAttributes(XmlQualifiedName typeName, XmlSchemaObjectCollection attributes, XmlSchemaAnyAttribute anyAttribute, out bool isReference)
{
if (anyAttribute != null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.AnyAttributeNotSupported));
isReference = false;
if (attributes != null)
{
bool foundId = false, foundRef = false;
for (int i = 0; i < attributes.Count; i++)
{
XmlSchemaObject o = attributes[i];
if (o is XmlSchemaAttribute)
{
XmlSchemaAttribute attribute = (XmlSchemaAttribute)o;
if (attribute.Use == XmlSchemaUse.Prohibited)
continue;
if (TryCheckIfAttribute(typeName, attribute, Globals.IdQualifiedName, ref foundId))
continue;
if (TryCheckIfAttribute(typeName, attribute, Globals.RefQualifiedName, ref foundRef))
continue;
if (attribute.RefName.IsEmpty || attribute.RefName.Namespace != Globals.SerializationNamespace || attribute.Use == XmlSchemaUse.Required)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.TypeShouldNotContainAttributes, Globals.SerializationNamespace));
}
}
isReference = (foundId && foundRef);
}
}
private bool TryCheckIfAttribute(XmlQualifiedName typeName, XmlSchemaAttribute attribute, XmlQualifiedName refName, ref bool foundAttribute)
{
if (attribute.RefName != refName)
return false;
if (foundAttribute)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.CannotHaveDuplicateAttributeNames, refName.Name));
foundAttribute = true;
return true;
}
private void AddDataContract(DataContract dataContract)
{
_dataContractSet.Add(dataContract.StableName, dataContract);
}
private string GetInnerText(XmlQualifiedName typeName, XmlElement xmlElement)
{
if (xmlElement != null)
{
XmlNode child = xmlElement.FirstChild;
while (child != null)
{
if (child.NodeType == XmlNodeType.Element)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, string.Format(SRSerialization.InvalidAnnotationExpectingText, xmlElement.LocalName, xmlElement.NamespaceURI, child.LocalName, child.NamespaceURI));
child = child.NextSibling;
}
return xmlElement.InnerText;
}
return null;
}
private static XmlElement ImportAnnotation(XmlSchemaAnnotation annotation, XmlQualifiedName annotationQualifiedName)
{
if (annotation != null && annotation.Items != null && annotation.Items.Count > 0 && annotation.Items[0] is XmlSchemaAppInfo)
{
XmlSchemaAppInfo appInfo = (XmlSchemaAppInfo)annotation.Items[0];
XmlNode[] markup = appInfo.Markup;
if (markup != null)
{
for (int i = 0; i < markup.Length; i++)
{
XmlElement annotationElement = markup[i] as XmlElement;
if (annotationElement != null && annotationElement.LocalName == annotationQualifiedName.Name && annotationElement.NamespaceURI == annotationQualifiedName.Namespace)
return annotationElement;
}
}
}
return null;
}
private static void ThrowTypeCannotBeImportedException(string name, string ns, string message)
{
ThrowTypeCannotBeImportedException(string.Format(SRSerialization.TypeCannotBeImported, name, ns, message));
}
private static void ThrowArrayTypeCannotBeImportedException(string name, string ns, string message)
{
ThrowTypeCannotBeImportedException(string.Format(SRSerialization.ArrayTypeCannotBeImported, name, ns, message));
}
private static void ThrowEnumTypeCannotBeImportedException(string name, string ns, string message)
{
ThrowTypeCannotBeImportedException(string.Format(SRSerialization.EnumTypeCannotBeImported, name, ns, message));
}
private static void ThrowISerializableTypeCannotBeImportedException(string name, string ns, string message)
{
ThrowTypeCannotBeImportedException(string.Format(SRSerialization.ISerializableTypeCannotBeImported, name, ns, message));
}
private static void ThrowTypeCannotBeImportedException(string message)
{
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.TypeCannotBeImportedHowToFix, message)));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps=OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps
{
public class ObjectAdd : IRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
#region IRegionModule Members
public void Initialise(Scene pScene, IConfigSource pSource)
{
m_scene = pScene;
m_scene.EventManager.OnRegisterCaps += RegisterCaps;
}
public void PostInitialise()
{
}
public void RegisterCaps(UUID agentID, Caps caps)
{
UUID capuuid = UUID.Random();
m_log.InfoFormat("[OBJECTADD]: {0}", "/CAPS/OA/" + capuuid + "/");
caps.RegisterHandler("ObjectAdd",
new RestHTTPHandler("POST", "/CAPS/OA/" + capuuid + "/",
delegate(Hashtable m_dhttpMethod)
{
return ProcessAdd(m_dhttpMethod, agentID, caps);
}));
}
public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap)
{
Hashtable responsedata = new Hashtable();
responsedata["int_response_code"] = 400; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Request wasn't what was expected";
ScenePresence avatar;
if (!m_scene.TryGetScenePresence(AgentId, out avatar))
return responsedata;
OSD r = OSDParser.DeserializeLLSDXml((string)request["requestbody"]);
//UUID session_id = UUID.Zero;
bool bypass_raycast = false;
uint everyone_mask = 0;
uint group_mask = 0;
uint next_owner_mask = 0;
uint flags = 0;
UUID group_id = UUID.Zero;
int hollow = 0;
int material = 0;
int p_code = 0;
int path_begin = 0;
int path_curve = 0;
int path_end = 0;
int path_radius_offset = 0;
int path_revolutions = 0;
int path_scale_x = 0;
int path_scale_y = 0;
int path_shear_x = 0;
int path_shear_y = 0;
int path_skew = 0;
int path_taper_x = 0;
int path_taper_y = 0;
int path_twist = 0;
int path_twist_begin = 0;
int profile_begin = 0;
int profile_curve = 0;
int profile_end = 0;
Vector3 ray_end = Vector3.Zero;
bool ray_end_is_intersection = false;
Vector3 ray_start = Vector3.Zero;
UUID ray_target_id = UUID.Zero;
Quaternion rotation = Quaternion.Identity;
Vector3 scale = Vector3.Zero;
int state = 0;
if (r.Type != OSDType.Map) // not a proper req
return responsedata;
OSDMap rm = (OSDMap)r;
if (rm.ContainsKey("ObjectData")) //v2
{
if (rm["ObjectData"].Type != OSDType.Map)
{
responsedata["str_response_string"] = "Has ObjectData key, but data not in expected format";
return responsedata;
}
OSDMap ObjMap = (OSDMap) rm["ObjectData"];
bypass_raycast = ObjMap["BypassRaycast"].AsBoolean();
everyone_mask = readuintval(ObjMap["EveryoneMask"]);
flags = readuintval(ObjMap["Flags"]);
group_mask = readuintval(ObjMap["GroupMask"]);
material = ObjMap["Material"].AsInteger();
next_owner_mask = readuintval(ObjMap["NextOwnerMask"]);
p_code = ObjMap["PCode"].AsInteger();
if (ObjMap.ContainsKey("Path"))
{
if (ObjMap["Path"].Type != OSDType.Map)
{
responsedata["str_response_string"] = "Has Path key, but data not in expected format";
return responsedata;
}
OSDMap PathMap = (OSDMap)ObjMap["Path"];
path_begin = PathMap["Begin"].AsInteger();
path_curve = PathMap["Curve"].AsInteger();
path_end = PathMap["End"].AsInteger();
path_radius_offset = PathMap["RadiusOffset"].AsInteger();
path_revolutions = PathMap["Revolutions"].AsInteger();
path_scale_x = PathMap["ScaleX"].AsInteger();
path_scale_y = PathMap["ScaleY"].AsInteger();
path_shear_x = PathMap["ShearX"].AsInteger();
path_shear_y = PathMap["ShearY"].AsInteger();
path_skew = PathMap["Skew"].AsInteger();
path_taper_x = PathMap["TaperX"].AsInteger();
path_taper_y = PathMap["TaperY"].AsInteger();
path_twist = PathMap["Twist"].AsInteger();
path_twist_begin = PathMap["TwistBegin"].AsInteger();
}
if (ObjMap.ContainsKey("Profile"))
{
if (ObjMap["Profile"].Type != OSDType.Map)
{
responsedata["str_response_string"] = "Has Profile key, but data not in expected format";
return responsedata;
}
OSDMap ProfileMap = (OSDMap)ObjMap["Profile"];
profile_begin = ProfileMap["Begin"].AsInteger();
profile_curve = ProfileMap["Curve"].AsInteger();
profile_end = ProfileMap["End"].AsInteger();
hollow = ProfileMap["Hollow"].AsInteger();
}
ray_end_is_intersection = ObjMap["RayEndIsIntersection"].AsBoolean();
ray_target_id = ObjMap["RayTargetId"].AsUUID();
state = ObjMap["State"].AsInteger();
try
{
ray_end = ((OSDArray) ObjMap["RayEnd"]).AsVector3();
ray_start = ((OSDArray) ObjMap["RayStart"]).AsVector3();
scale = ((OSDArray) ObjMap["Scale"]).AsVector3();
rotation = ((OSDArray)ObjMap["Rotation"]).AsQuaternion();
}
catch (Exception)
{
responsedata["str_response_string"] = "RayEnd, RayStart, Scale or Rotation wasn't in the expected format";
return responsedata;
}
if (rm.ContainsKey("AgentData"))
{
if (rm["AgentData"].Type != OSDType.Map)
{
responsedata["str_response_string"] = "Has AgentData key, but data not in expected format";
return responsedata;
}
OSDMap AgentDataMap = (OSDMap) rm["AgentData"];
//session_id = AgentDataMap["SessionId"].AsUUID();
group_id = AgentDataMap["GroupId"].AsUUID();
}
}
else
{ //v1
bypass_raycast = rm["bypass_raycast"].AsBoolean();
everyone_mask = readuintval(rm["everyone_mask"]);
flags = readuintval(rm["flags"]);
group_id = rm["group_id"].AsUUID();
group_mask = readuintval(rm["group_mask"]);
hollow = rm["hollow"].AsInteger();
material = rm["material"].AsInteger();
next_owner_mask = readuintval(rm["next_owner_mask"]);
hollow = rm["hollow"].AsInteger();
p_code = rm["p_code"].AsInteger();
path_begin = rm["path_begin"].AsInteger();
path_curve = rm["path_curve"].AsInteger();
path_end = rm["path_end"].AsInteger();
path_radius_offset = rm["path_radius_offset"].AsInteger();
path_revolutions = rm["path_revolutions"].AsInteger();
path_scale_x = rm["path_scale_x"].AsInteger();
path_scale_y = rm["path_scale_y"].AsInteger();
path_shear_x = rm["path_shear_x"].AsInteger();
path_shear_y = rm["path_shear_y"].AsInteger();
path_skew = rm["path_skew"].AsInteger();
path_taper_x = rm["path_taper_x"].AsInteger();
path_taper_y = rm["path_taper_y"].AsInteger();
path_twist = rm["path_twist"].AsInteger();
path_twist_begin = rm["path_twist_begin"].AsInteger();
profile_begin = rm["profile_begin"].AsInteger();
profile_curve = rm["profile_curve"].AsInteger();
profile_end = rm["profile_end"].AsInteger();
ray_end_is_intersection = rm["ray_end_is_intersection"].AsBoolean();
ray_target_id = rm["ray_target_id"].AsUUID();
//session_id = rm["session_id"].AsUUID();
state = rm["state"].AsInteger();
try
{
ray_end = ((OSDArray)rm["ray_end"]).AsVector3();
ray_start = ((OSDArray)rm["ray_start"]).AsVector3();
rotation = ((OSDArray)rm["rotation"]).AsQuaternion();
scale = ((OSDArray)rm["scale"]).AsVector3();
}
catch (Exception)
{
responsedata["str_response_string"] = "RayEnd, RayStart, Scale or Rotation wasn't in the expected format";
return responsedata;
}
}
Vector3 pos = m_scene.GetNewRezLocation(ray_start, ray_end, ray_target_id, rotation, (bypass_raycast) ? (byte)1 : (byte)0, (ray_end_is_intersection) ? (byte)1 : (byte)0, true, scale, false);
PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
pbs.PathBegin = (ushort)path_begin;
pbs.PathCurve = (byte)path_curve;
pbs.PathEnd = (ushort)path_end;
pbs.PathRadiusOffset = (sbyte)path_radius_offset;
pbs.PathRevolutions = (byte)path_revolutions;
pbs.PathScaleX = (byte)path_scale_x;
pbs.PathScaleY = (byte)path_scale_y;
pbs.PathShearX = (byte) path_shear_x;
pbs.PathShearY = (byte)path_shear_y;
pbs.PathSkew = (sbyte)path_skew;
pbs.PathTaperX = (sbyte)path_taper_x;
pbs.PathTaperY = (sbyte)path_taper_y;
pbs.PathTwist = (sbyte)path_twist;
pbs.PathTwistBegin = (sbyte)path_twist_begin;
pbs.HollowShape = (HollowShape) hollow;
pbs.PCode = (byte)p_code;
pbs.ProfileBegin = (ushort) profile_begin;
pbs.ProfileCurve = (byte) profile_curve;
pbs.ProfileEnd = (ushort)profile_end;
pbs.Scale = scale;
pbs.State = (byte)state;
SceneObjectGroup obj = null; ;
if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos))
{
// rez ON the ground, not IN the ground
// pos.Z += 0.25F;
obj = m_scene.AddNewPrim(avatar.UUID, group_id, pos, rotation, pbs);
}
if (obj == null)
return responsedata;
SceneObjectPart rootpart = obj.RootPart;
rootpart.Shape = pbs;
rootpart.Flags |= (PrimFlags)flags;
rootpart.EveryoneMask = everyone_mask;
rootpart.GroupID = group_id;
rootpart.GroupMask = group_mask;
rootpart.NextOwnerMask = next_owner_mask;
rootpart.Material = (byte)material;
m_scene.PhysicsScene.AddPhysicsActorTaint(rootpart.PhysActor);
responsedata["int_response_code"] = 200; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>",ConvertUintToBytes(obj.LocalId));
return responsedata;
}
private uint readuintval(OSD obj)
{
byte[] tmp = obj.AsBinary();
if (BitConverter.IsLittleEndian)
Array.Reverse(tmp);
return Utils.BytesToUInt(tmp);
}
private string ConvertUintToBytes(uint val)
{
byte[] resultbytes = Utils.UIntToBytes(val);
if (BitConverter.IsLittleEndian)
Array.Reverse(resultbytes);
return String.Format("<binary encoding=\"base64\">{0}</binary>",Convert.ToBase64String(resultbytes));
}
public void Close()
{
}
public string Name
{
get { return "ObjectAddModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.