context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class ctor_str_int_parity_int_stopbits : PortsTest
{
private enum ThrowAt { Set, Open };
[Fact]
public void COM1_9600_Odd_5_1()
{
string portName = "COM1";
int baudRate = 9600;
int parity = (int)Parity.Odd;
int dataBits = 5;
int stopBits = (int)StopBits.One;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM2_14400_None_5_1()
{
string portName = "COM2";
int baudRate = 14400;
int parity = (int)Parity.None;
int dataBits = 5;
int stopBits = (int)StopBits.One;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM3_28800_None_5_15()
{
string portName = "COM3";
int baudRate = 28800;
int parity = (int)Parity.None;
int dataBits = 5;
int stopBits = (int)StopBits.OnePointFive;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM4_57600_Even_5_15()
{
string portName = "COM2";
int baudRate = 57600;
int parity = (int)Parity.Even;
int dataBits = 5;
int stopBits = (int)StopBits.OnePointFive;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM256_115200_Mark_5_2()
{
string portName = "COM256";
int baudRate = 115200;
int parity = (int)Parity.Mark;
int dataBits = 5;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM1_9600_None_5_2()
{
string portName = "COM1";
int baudRate = 9600;
int parity = (int)Parity.None;
int dataBits = 5;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM2_14400_Even_6_1()
{
string portName = "COM2";
int baudRate = 14400;
int parity = (int)Parity.Even;
int dataBits = 6;
int stopBits = (int)StopBits.One;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM3_28800_Odd_7_2()
{
string portName = "COM3";
int baudRate = 28800;
int parity = (int)Parity.Odd;
int dataBits = 7;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM1_9600_Odd_8_1()
{
string portName = "COM1";
int baudRate = 9600;
int parity = (int)Parity.Odd;
int dataBits = 8;
int stopBits = (int)StopBits.One;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM2_14400_None_8_1()
{
string portName = "COM2";
int baudRate = 14400;
int parity = (int)Parity.None;
int dataBits = 8;
int stopBits = (int)StopBits.One;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM256_115200_Mark_8_2()
{
string portName = "COM256";
int baudRate = 115200;
int parity = (int)Parity.Mark;
int dataBits = 8;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void COM1_9600_None_8_2()
{
string portName = "COM1";
int baudRate = 9600;
int parity = (int)Parity.None;
int dataBits = 8;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
//[] Error checking for PortName
[Fact]
public void Empty_9600_None_5_15()
{
string portName = string.Empty;
int baudRate = 9600;
int parity = (int)Parity.None;
int dataBits = 5;
int stopBits = (int)StopBits.OnePointFive;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Set);
}
[Fact]
public void Null_14400_Even_6_1()
{
string portName = null;
int baudRate = 14400;
int parity = (int)Parity.Even;
int dataBits = 6;
int stopBits = (int)StopBits.One;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentNullException), ThrowAt.Set);
}
[Fact]
public void COM257_57600_Mark_8_2()
{
string portName = "COM257";
int baudRate = 57600;
int parity = (int)Parity.Mark;
int dataBits = 8;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits);
}
[Fact]
public void Filename_9600_Space_8_1()
{
string portName;
int baudRate = 9600;
int parity = (int)Parity.Space;
int dataBits = 8;
int stopBits = (int)StopBits.One;
string fileName = portName = "PortNameEqualToFileName.txt";
FileStream testFile = File.Open(fileName, FileMode.Create);
ASCIIEncoding asciiEncd = new ASCIIEncoding();
string testStr = "Hello World";
testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr));
testFile.Close();
try
{
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Open);
}
catch (Exception)
{
throw;
}
finally
{
File.Delete(fileName);
}
}
[Fact]
public void PHYSICALDRIVE0_14400_Even_5_15()
{
string portName = "PHYSICALDRIVE0";
int baudRate = 14400;
int parity = (int)Parity.Even;
int dataBits = 5;
int stopBits = (int)StopBits.OnePointFive;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Open);
}
//[] Error checking for BaudRate
[Fact]
public void COM1_Int32MinValue_None_5_15()
{
string portName = "Com1";
int baudRate = int.MinValue;
int parity = (int)Parity.None;
int dataBits = 5;
int stopBits = (int)StopBits.OnePointFive;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM2_Neg1_Even_6_1()
{
string portName = "Com2";
int baudRate = -1;
int parity = (int)Parity.Even;
int dataBits = 6;
int stopBits = (int)StopBits.One;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM3_0_Odd_7_2()
{
string portName = "Com3";
int baudRate = 0;
int parity = (int)Parity.Odd;
int dataBits = 7;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM4_Int32MaxValue_Mark_8_2()
{
string portName = "Com4";
int baudRate = int.MaxValue;
int parity = (int)Parity.Mark;
int dataBits = 8;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Open);
}
//[] Error checking for Parity
[Fact]
public void COM1_9600_Int32MinValue_5_15()
{
string portName = "Com1";
int baudRate = 9600;
int parity = int.MinValue;
int dataBits = 5;
int stopBits = (int)StopBits.OnePointFive;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM2_14400_Neg1_6_1()
{
string portName = "Com2";
int baudRate = 14400;
int parity = -1;
int dataBits = 6;
int stopBits = (int)StopBits.One;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM3_28800_5_7_2()
{
string portName = "Com3";
int baudRate = 28800;
int parity = 5;
int dataBits = 7;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM4_57600_Int32MaxValue_8_2()
{
string portName = "Com4";
int baudRate = 57600;
int parity = int.MaxValue;
int dataBits = 8;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
//[] Error checking for DataBits
[Fact]
public void COM1_9600_None_Int32MinValue_1()
{
string portName = "Com1";
int baudRate = 9600;
int parity = (int)Parity.None;
int dataBits = int.MinValue;
int stopBits = (int)StopBits.OnePointFive;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM2_14400_Even_Neg1_15()
{
string portName = "Com2";
int baudRate = 14400;
int parity = (int)Parity.Even;
int dataBits = -1;
int stopBits = (int)StopBits.One;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM3_28800_Odd_4_2()
{
string portName = "Com3";
int baudRate = 28800;
int parity = (int)Parity.Odd;
int dataBits = 4;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM4_57600_Mark_9_1()
{
string portName = "Com4";
int baudRate = 57600;
int parity = (int)Parity.Mark;
int dataBits = 9;
int stopBits = (int)StopBits.Two;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM255_115200_Space_Int32MaxValue_15()
{
string portName = "Com255";
int baudRate = 115200;
int parity = (int)Parity.Space;
int dataBits = int.MaxValue;
int stopBits = (int)StopBits.One;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
//[] Error checking for StopBits
[Fact]
public void COM1_9600_None_5_Int32MinValue()
{
string portName = "Com1";
int baudRate = 9600;
int parity = (int)Parity.None;
int dataBits = 5;
int stopBits = int.MinValue;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM2_14400_Even_6_Neg1()
{
string portName = "Com2";
int baudRate = 14400;
int parity = (int)Parity.Even;
int dataBits = 6;
int stopBits = -1;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM3_28800_Odd_7_0()
{
string portName = "Com3";
int baudRate = 28800;
int parity = (int)Parity.Odd;
int dataBits = 7;
int stopBits = 0;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM4_57600_Mark_8_4()
{
string portName = "Com4";
int baudRate = 57600;
int parity = (int)Parity.Mark;
int dataBits = 8;
int stopBits = 4;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
[Fact]
public void COM255_115200_Space_8_Int32MaxValue()
{
string portName = "Com255";
int baudRate = 115200;
int parity = (int)Parity.Space;
int dataBits = 8;
int stopBits = int.MaxValue;
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set);
}
private void VerifyCtor(string portName, int baudRate, int parity, int dataBits, int stopBits)
{
VerifyCtor(portName, baudRate, parity, dataBits, stopBits, null, ThrowAt.Set);
}
private void VerifyCtor(string portName, int baudRate, int parity, int dataBits, int stopBits, Type expectedException, ThrowAt throwAt)
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying properties where PortName={0},BaudRate={1},Parity={2},DatBits={3},StopBits={4}", portName, baudRate, parity, dataBits, stopBits);
try
{
using (SerialPort com = new SerialPort(portName, baudRate, (Parity)parity, dataBits, (StopBits)stopBits))
{
if (null != expectedException && throwAt == ThrowAt.Set)
{
Fail("Err_7212ahsdj Expected Ctor to throw {0}", expectedException);
}
serPortProp.SetAllPropertiesToDefaults();
serPortProp.SetProperty("PortName", portName);
serPortProp.SetProperty("BaudRate", baudRate);
serPortProp.SetProperty("Parity", (Parity)parity);
serPortProp.SetProperty("DataBits", dataBits);
serPortProp.SetProperty("StopBits", (StopBits)stopBits);
serPortProp.VerifyPropertiesAndPrint(com);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("Err_07081hadnh Did not expect exception to be thrown and the following was thrown: \n{0}", e);
}
else if (throwAt == ThrowAt.Open)
{
Fail("Err_88916adfa Expected {0} to be thrown at Open and the following was thrown at Set: \n{1}", expectedException, e);
}
else if (e.GetType() != expectedException)
{
Fail("Err_90282ahwhp Expected {0} to be thrown and the following was thrown: \n{1}", expectedException, e);
}
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SpacewarGame.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion
namespace Spacewar
{
/// <summary>
/// This is the main type for your game
/// </summary>
partial class SpacewarGame : Microsoft.Xna.Framework.Game
{
// these are the size of the offscreen drawing surface
// in general, no one wants to change these as there
// are all kinds of UI calculations and positions based
// on these dimensions.
const int FixedDrawingWidth = 1280;
const int FixedDrawingHeight = 720;
// these are the size of the output window, ignored
// on Xbox 360
private int preferredWindowWidth = 1280;
private int preferredWindowHeight = 720;
private static ContentManager contentManager;
/// <summary>
/// The game settings from settings.xml
/// </summary>
private static Settings settings = new Settings();
private static Camera camera;
/// <summary>
/// Information about the players such as score, health etc
/// </summary>
private static Player[] players;
/// <summary>
/// The current game state
/// </summary>
private static GameState gameState = GameState.Started;
/// <summary>
/// Which game board are we playing on
/// </summary>
private static int gameLevel;
/// <summary>
/// Stores game paused state
/// </summary>
private bool paused;
private GraphicsDeviceManager graphics;
private bool enableDrawScaling;
private RenderTarget2D drawBuffer;
private SpriteBatch spriteBatch;
private static Screen currentScreen;
private static PlatformID currentPlatform;
private static KeyboardState keyState;
private bool justWentFullScreen;
#region Properties
public static GameState GameState
{
get
{
return gameState;
}
}
public static int GameLevel
{
get
{
return gameLevel;
}
set
{
gameLevel = value;
}
}
public static Camera Camera
{
get
{
return camera;
}
}
public static Settings Settings
{
get
{
return settings;
}
}
public static Player[] Players
{
get
{
return players;
}
}
public static ContentManager ContentManager
{
get
{
return contentManager;
}
}
public static PlatformID CurrentPlatform
{
get
{
return currentPlatform;
}
}
public static KeyboardState KeyState
{
get
{
return keyState;
}
}
#endregion
public SpacewarGame()
{
#if XBOX360
// we might as well use the xbox in all its glory
preferredWindowWidth = FixedDrawingWidth;
preferredWindowHeight = FixedDrawingHeight;
enableDrawScaling = false;
#else
enableDrawScaling = true;
#endif
this.graphics = new Microsoft.Xna.Framework.GraphicsDeviceManager(this);
this.graphics.PreferredBackBufferWidth = preferredWindowWidth;
this.graphics.PreferredBackBufferHeight = preferredWindowHeight;
// Game should run as fast as possible.
IsFixedTimeStep = false;
}
protected override void Initialize()
{
// game initialization code here
//Uncomment this line to force a save of the default settings file. Useful when you had added things to settings.cs
//NOTE in VS this will go in DEBUG or RELEASE - need to copy up to main project
//Settings.Save("settings.xml");
settings = Settings.Load("settings.xml");
currentPlatform = System.Environment.OSVersion.Platform;
//Initialise the sound
Sound.Initialize();
Window.Title = Settings.WindowTitle;
base.Initialize();
}
protected override void BeginRun()
{
Sound.PlayCue(Sounds.TitleMusic);
//Kick off the game by loading the logo splash screen
ChangeState(GameState.LogoSplash);
float fieldOfView = (float)Math.PI / 4;
float aspectRatio = (float)FixedDrawingWidth / (float)FixedDrawingHeight;
float nearPlane = 10f;
float farPlane = 700f;
camera = new Camera(fieldOfView, aspectRatio, nearPlane, farPlane);
camera.ViewPosition = new Vector3(0, 0, 500);
base.BeginRun();
}
protected override void Update(GameTime gameTime)
{
TimeSpan elapsedTime = gameTime.ElapsedGameTime;
TimeSpan time = gameTime.TotalGameTime;
// The time since Update was called last
float elapsed = (float)elapsedTime.TotalSeconds;
GameState changeState = GameState.None;
keyState = Keyboard.GetState();
XInputHelper.Update(this, keyState);
if ((keyState.IsKeyDown(Keys.RightAlt) || keyState.IsKeyDown(Keys.LeftAlt)) && keyState.IsKeyDown(Keys.Enter) && !justWentFullScreen)
{
ToggleFullScreen();
justWentFullScreen = true;
}
if (keyState.IsKeyUp(Keys.Enter))
{
justWentFullScreen = false;
}
if (XInputHelper.GamePads[PlayerIndex.One].BackPressed ||
XInputHelper.GamePads[PlayerIndex.Two].BackPressed)
{
if (gameState == GameState.PlayEvolved || gameState == GameState.PlayRetro)
{
paused = !paused;
}
if (gameState == GameState.LogoSplash)
{
this.Exit();
}
}
//Reload settings file?
if (XInputHelper.GamePads[PlayerIndex.One].YPressed)
{
//settings = Settings.Load("settings.xml");
//GC.Collect();
}
if (!paused)
{
//Update everything
changeState = currentScreen.Update(time, elapsedTime);
// Update the AudioEngine - MUST call this every frame!!
Sound.Update();
//If either player presses start then reset the game
if (XInputHelper.GamePads[PlayerIndex.One].StartPressed ||
XInputHelper.GamePads[PlayerIndex.Two].StartPressed)
{
changeState = GameState.LogoSplash;
}
if (changeState != GameState.None)
{
ChangeState(changeState);
}
}
base.Update(gameTime);
}
protected override bool BeginDraw()
{
if (!base.BeginDraw())
return false;
BeginDrawScaling();
return true;
}
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(ClearOptions.DepthBuffer,
Color.CornflowerBlue, 1.0f, 0);
base.Draw(gameTime);
currentScreen.Render();
}
protected override void EndDraw()
{
EndDrawScaling();
base.EndDraw();
}
internal void ChangeState(GameState NextState)
{
//Logo spash can come from ANY state since its the place you go when you restart
if (NextState == GameState.LogoSplash)
{
if (currentScreen != null)
currentScreen.Shutdown();
currentScreen = new TitleScreen(this);
gameState = GameState.LogoSplash;
}
else if (gameState == GameState.LogoSplash && NextState == GameState.ShipSelection)
{
Sound.PlayCue(Sounds.MenuAdvance);
//This is really where the game starts so setup the player information
players = new Player[2] { new Player(), new Player() };
//Start at level 1
gameLevel = 1;
currentScreen.Shutdown();
currentScreen = new SelectionScreen(this);
gameState = GameState.ShipSelection;
}
else if (gameState == GameState.PlayEvolved && NextState == GameState.ShipUpgrade)
{
currentScreen.Shutdown();
currentScreen = new ShipUpgradeScreen(this);
gameState = GameState.ShipUpgrade;
}
else if ((gameState == GameState.ShipSelection || GameState == GameState.ShipUpgrade) && NextState == GameState.PlayEvolved)
{
Sound.PlayCue(Sounds.MenuAdvance);
currentScreen.Shutdown();
currentScreen = new EvolvedScreen(this);
gameState = GameState.PlayEvolved;
}
else if (gameState == GameState.LogoSplash && NextState == GameState.PlayRetro)
{
//Game starts here for retro
players = new Player[2] { new Player(), new Player() };
currentScreen.Shutdown();
currentScreen = new RetroScreen(this);
gameState = GameState.PlayRetro;
}
else if (gameState == GameState.PlayEvolved && NextState == GameState.Victory)
{
currentScreen.Shutdown();
currentScreen = new VictoryScreen(this);
gameState = GameState.Victory;
}
else
{
//This is a BAD thing and should never happen
// What does this map to on XBox 360?
//Debug.Assert(false, String.Format("Invalid State transition {0} to {1}", gameState.ToString(), NextState.ToString()));
}
}
protected override void LoadContent()
{
base.LoadContent();
contentManager = new ContentManager(Services);
if (currentScreen != null)
currentScreen.OnCreateDevice();
Font.Init(this);
if (enableDrawScaling)
{
PresentationParameters pp = graphics.GraphicsDevice.PresentationParameters;
drawBuffer = new RenderTarget2D(graphics.GraphicsDevice,
FixedDrawingWidth, FixedDrawingHeight,
true, SurfaceFormat.Color,
DepthFormat.Depth24Stencil8, pp.MultiSampleCount,
RenderTargetUsage.DiscardContents);
spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
}
}
protected override void UnloadContent()
{
base.UnloadContent();
if (drawBuffer != null)
{
drawBuffer.Dispose();
drawBuffer = null;
}
if (spriteBatch != null)
{
spriteBatch.Dispose();
spriteBatch = null;
}
Font.Dispose();
if (contentManager != null)
{
contentManager.Dispose();
contentManager = null;
}
}
private void ToggleFullScreen()
{
PresentationParameters presentation = graphics.GraphicsDevice.PresentationParameters;
if (presentation.IsFullScreen)
{ // going windowed
graphics.PreferredBackBufferWidth = preferredWindowWidth;
graphics.PreferredBackBufferHeight = preferredWindowHeight;
}
else
{
// going fullscreen, use desktop resolution to minimize display mode changes
// this also has the nice effect of working around some displays that lie about
// supporting 1280x720
GraphicsAdapter adapter = graphics.GraphicsDevice.Adapter;
graphics.PreferredBackBufferWidth = adapter.CurrentDisplayMode.Width;
graphics.PreferredBackBufferHeight = adapter.CurrentDisplayMode.Height;
}
graphics.ToggleFullScreen();
}
private void BeginDrawScaling()
{
if (enableDrawScaling && drawBuffer != null)
{
graphics.GraphicsDevice.SetRenderTarget(drawBuffer);
}
}
private void EndDrawScaling()
{
// copy our offscreen surface to the backbuffer with appropriate
// letterbox bars
if (!enableDrawScaling || drawBuffer == null)
return;
graphics.GraphicsDevice.SetRenderTarget(null);
PresentationParameters presentation = graphics.GraphicsDevice.PresentationParameters;
float outputAspect = (float)presentation.BackBufferWidth / (float)presentation.BackBufferHeight;
float preferredAspect = (float)FixedDrawingWidth / (float)FixedDrawingHeight;
Rectangle dst;
if (outputAspect <= preferredAspect)
{
// output is taller than it is wider, bars on top/bottom
int presentHeight = (int)((presentation.BackBufferWidth / preferredAspect) + 0.5f);
int barHeight = (presentation.BackBufferHeight - presentHeight) / 2;
dst = new Rectangle(0, barHeight, presentation.BackBufferWidth, presentHeight);
}
else
{
// output is wider than it is tall, bars left/right
int presentWidth = (int)((presentation.BackBufferHeight * preferredAspect) + 0.5f);
int barWidth = (presentation.BackBufferWidth - presentWidth) / 2;
dst = new Rectangle(barWidth, 0, presentWidth, presentation.BackBufferHeight);
}
// clear to get black bars
graphics.GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 1.0f, 0);
// draw a quad to get the draw buffer to the back buffer
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
spriteBatch.Draw(drawBuffer, dst, Color.White);
spriteBatch.End();
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// 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.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk
{
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public partial struct PhysicalDeviceDescriptorIndexingFeatures
{
/// <summary>
///
/// </summary>
public bool ShaderInputAttachmentArrayDynamicIndexing
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool ShaderUniformTexelBufferArrayDynamicIndexing
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool ShaderStorageTexelBufferArrayDynamicIndexing
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool ShaderUniformBufferArrayNonUniformIndexing
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool ShaderSampledImageArrayNonUniformIndexing
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool ShaderStorageBufferArrayNonUniformIndexing
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool ShaderStorageImageArrayNonUniformIndexing
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool ShaderInputAttachmentArrayNonUniformIndexing
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool ShaderUniformTexelBufferArrayNonUniformIndexing
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool ShaderStorageTexelBufferArrayNonUniformIndexing
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool DescriptorBindingUniformBufferUpdateAfterBind
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool DescriptorBindingSampledImageUpdateAfterBind
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool DescriptorBindingStorageImageUpdateAfterBind
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool DescriptorBindingStorageBufferUpdateAfterBind
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool DescriptorBindingUniformTexelBufferUpdateAfterBind
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool DescriptorBindingStorageTexelBufferUpdateAfterBind
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool DescriptorBindingUpdateUnusedWhilePending
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool DescriptorBindingPartiallyBound
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool DescriptorBindingVariableDescriptorCount
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool RuntimeDescriptorArray
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <param name="pointer">
/// </param>
internal unsafe void MarshalTo(SharpVk.Interop.PhysicalDeviceDescriptorIndexingFeatures* pointer)
{
pointer->SType = StructureType.PhysicalDeviceDescriptorIndexingFeaturesVersion;
pointer->Next = null;
pointer->ShaderInputAttachmentArrayDynamicIndexing = this.ShaderInputAttachmentArrayDynamicIndexing;
pointer->ShaderUniformTexelBufferArrayDynamicIndexing = this.ShaderUniformTexelBufferArrayDynamicIndexing;
pointer->ShaderStorageTexelBufferArrayDynamicIndexing = this.ShaderStorageTexelBufferArrayDynamicIndexing;
pointer->ShaderUniformBufferArrayNonUniformIndexing = this.ShaderUniformBufferArrayNonUniformIndexing;
pointer->ShaderSampledImageArrayNonUniformIndexing = this.ShaderSampledImageArrayNonUniformIndexing;
pointer->ShaderStorageBufferArrayNonUniformIndexing = this.ShaderStorageBufferArrayNonUniformIndexing;
pointer->ShaderStorageImageArrayNonUniformIndexing = this.ShaderStorageImageArrayNonUniformIndexing;
pointer->ShaderInputAttachmentArrayNonUniformIndexing = this.ShaderInputAttachmentArrayNonUniformIndexing;
pointer->ShaderUniformTexelBufferArrayNonUniformIndexing = this.ShaderUniformTexelBufferArrayNonUniformIndexing;
pointer->ShaderStorageTexelBufferArrayNonUniformIndexing = this.ShaderStorageTexelBufferArrayNonUniformIndexing;
pointer->DescriptorBindingUniformBufferUpdateAfterBind = this.DescriptorBindingUniformBufferUpdateAfterBind;
pointer->DescriptorBindingSampledImageUpdateAfterBind = this.DescriptorBindingSampledImageUpdateAfterBind;
pointer->DescriptorBindingStorageImageUpdateAfterBind = this.DescriptorBindingStorageImageUpdateAfterBind;
pointer->DescriptorBindingStorageBufferUpdateAfterBind = this.DescriptorBindingStorageBufferUpdateAfterBind;
pointer->DescriptorBindingUniformTexelBufferUpdateAfterBind = this.DescriptorBindingUniformTexelBufferUpdateAfterBind;
pointer->DescriptorBindingStorageTexelBufferUpdateAfterBind = this.DescriptorBindingStorageTexelBufferUpdateAfterBind;
pointer->DescriptorBindingUpdateUnusedWhilePending = this.DescriptorBindingUpdateUnusedWhilePending;
pointer->DescriptorBindingPartiallyBound = this.DescriptorBindingPartiallyBound;
pointer->DescriptorBindingVariableDescriptorCount = this.DescriptorBindingVariableDescriptorCount;
pointer->RuntimeDescriptorArray = this.RuntimeDescriptorArray;
}
/// <summary>
///
/// </summary>
/// <param name="pointer">
/// </param>
internal static unsafe PhysicalDeviceDescriptorIndexingFeatures MarshalFrom(SharpVk.Interop.PhysicalDeviceDescriptorIndexingFeatures* pointer)
{
PhysicalDeviceDescriptorIndexingFeatures result = default(PhysicalDeviceDescriptorIndexingFeatures);
result.ShaderInputAttachmentArrayDynamicIndexing = pointer->ShaderInputAttachmentArrayDynamicIndexing;
result.ShaderUniformTexelBufferArrayDynamicIndexing = pointer->ShaderUniformTexelBufferArrayDynamicIndexing;
result.ShaderStorageTexelBufferArrayDynamicIndexing = pointer->ShaderStorageTexelBufferArrayDynamicIndexing;
result.ShaderUniformBufferArrayNonUniformIndexing = pointer->ShaderUniformBufferArrayNonUniformIndexing;
result.ShaderSampledImageArrayNonUniformIndexing = pointer->ShaderSampledImageArrayNonUniformIndexing;
result.ShaderStorageBufferArrayNonUniformIndexing = pointer->ShaderStorageBufferArrayNonUniformIndexing;
result.ShaderStorageImageArrayNonUniformIndexing = pointer->ShaderStorageImageArrayNonUniformIndexing;
result.ShaderInputAttachmentArrayNonUniformIndexing = pointer->ShaderInputAttachmentArrayNonUniformIndexing;
result.ShaderUniformTexelBufferArrayNonUniformIndexing = pointer->ShaderUniformTexelBufferArrayNonUniformIndexing;
result.ShaderStorageTexelBufferArrayNonUniformIndexing = pointer->ShaderStorageTexelBufferArrayNonUniformIndexing;
result.DescriptorBindingUniformBufferUpdateAfterBind = pointer->DescriptorBindingUniformBufferUpdateAfterBind;
result.DescriptorBindingSampledImageUpdateAfterBind = pointer->DescriptorBindingSampledImageUpdateAfterBind;
result.DescriptorBindingStorageImageUpdateAfterBind = pointer->DescriptorBindingStorageImageUpdateAfterBind;
result.DescriptorBindingStorageBufferUpdateAfterBind = pointer->DescriptorBindingStorageBufferUpdateAfterBind;
result.DescriptorBindingUniformTexelBufferUpdateAfterBind = pointer->DescriptorBindingUniformTexelBufferUpdateAfterBind;
result.DescriptorBindingStorageTexelBufferUpdateAfterBind = pointer->DescriptorBindingStorageTexelBufferUpdateAfterBind;
result.DescriptorBindingUpdateUnusedWhilePending = pointer->DescriptorBindingUpdateUnusedWhilePending;
result.DescriptorBindingPartiallyBound = pointer->DescriptorBindingPartiallyBound;
result.DescriptorBindingVariableDescriptorCount = pointer->DescriptorBindingVariableDescriptorCount;
result.RuntimeDescriptorArray = pointer->RuntimeDescriptorArray;
return result;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation.Language;
using System.Globalization;
using Microsoft.PowerShell.Commands;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Internal;
namespace System.Management.Automation
{
/// <summary>
/// Monad help is an architecture made up of three layers:
/// 1. At the top is get-help commandlet from where help functionality is accessed.
/// 2. At the middel is the help system which collects help objects based on user's request.
/// 3. At the bottom are different help providers which provide help contents for different kinds of information requested.
///
/// Class HelpSystem implements the middle layer of Monad Help.
///
/// HelpSystem will provide functionalitys in following areas,
/// 1. Initialization and management of help providers
/// 2. Help engine: this will invoke different providers based on user's request.
/// 3. Help API: this is the API HelpSystem provide to get-help commandlet.
///
/// Initialization:
/// Initialization of different help providers needs some context information like "ExecutionContext"
///
/// Help engine:
/// By default, HelpInfo will be retrieved in two phase: exact-match phase and search phase.
///
/// Exact-match phase: help providers will be called in appropriate order to retrieve HelpInfo.
/// If a match is found, help engine will stop and return the one and only HelpInfo retrieved.
///
/// Search phase: all relevant help providers will be called to retrieve HelpInfo. (Order doesn't
/// matter in this case) Help engine will not stop until all help providers are called.
///
/// Behaviour of help engine can be modified based on Help API parameters in following ways,
/// 1. limit the number of HelpInfo to be returned.
/// 2. specify which providers will be used.
/// 3. general help info returned in case the search target is empty.
/// 4. default help info (or hint) returned in case no match is found.
///
/// Help Api:
/// Help Api is the function to be called by get-help commandlet.
///
/// Following information needs to be provided in Help Api paramters,
/// 1. search target: (which can be one or multiple strings)
/// 2. help type: limit the type of help to be searched.
/// 3. included fields: the fields to be included in the help info
/// 4. excluded fields: the fields to be excluded in the help info
/// 5. max number of results to be returned:
/// 6. scoring algorithm for help results?
/// 7. help reason: help can be directly invoked by end user or as a result of
/// some command syntax error.
///
/// [gxie, 7-25-04]: included fields, excluded fields and help reason will be handled in
/// get-help commandlet.
///
/// Help API's are internal. The only way to access help is by
/// invoking the get-help command.
///
/// To support the scenario where multiple monad engine running in one process. It
/// is required that each monad engine has its one help system instance.
///
/// Currently each ExecutionContext has a help system instance as its member.
///
/// Help Providers:
/// The basic contract for help providers is to provide help based on the
/// search target.
///
/// The result of help provider invocation can be three things:
/// a. Full help info. (in the case of exact-match and single search result)
/// b. Short help info. (in the case of multiple search result)
/// c. Partial help info. (in the case of some commandlet help info, which
/// should be supplemented by provider help info)
/// d. Help forwarding info. (in the case of alias, which will change the target
/// for alias)
///
/// Help providers may need to provide functionality in following two area,
/// a. caching and indexing to boost performance
/// b. localization
///
/// </summary>
internal class HelpSystem
{
/// <summary>
/// Constructor for HelpSystem.
/// </summary>
/// <param name="context">Execution context for this help system</param>
internal HelpSystem(ExecutionContext context)
{
if (context == null)
{
throw PSTraceSource.NewArgumentNullException("ExecutionContext");
}
_executionContext = context;
Initialize();
}
private ExecutionContext _executionContext;
/// <summary>
/// ExecutionContext for the help system. Different help providers
/// will depend on this to retrieve session related information like
/// session state and command discovery objects.
/// </summary>
/// <value></value>
internal ExecutionContext ExecutionContext
{
get
{
return _executionContext;
}
}
#region Progress Callback
internal delegate void HelpProgressHandler(object sender, HelpProgressInfo arg);
internal event HelpProgressHandler OnProgress;
#endregion
#region Initialization
/// <summary>
/// Initialize help system with an execution context. If the execution context
/// matches the execution context of current singleton HelpSystem object, nothing
/// needs to be done. Otherwise, a new singleton HelpSystem object will be created
/// with the new execution context.
/// </summary>
internal void Initialize()
{
_verboseHelpErrors = LanguagePrimitives.IsTrue(
_executionContext.GetVariableValue(SpecialVariables.VerboseHelpErrorsVarPath, false));
_helpErrorTracer = new HelpErrorTracer(this);
InitializeHelpProviders();
}
#endregion Initalization
#region Help API
/// <summary>
/// Get Help api function. This is the basic form of the Help API using help
/// request.
///
/// Variants of this function are defined below, which will create help request
/// object on fly.
/// </summary>
/// <param name="helpRequest">helpRequest object</param>
/// <returns>An array of HelpInfo object</returns>
internal IEnumerable<HelpInfo> GetHelp(HelpRequest helpRequest)
{
if (helpRequest == null)
return null;
helpRequest.Validate();
ValidateHelpCulture();
return this.DoGetHelp(helpRequest);
}
#endregion Help API
#region Error Handling
private Collection<ErrorRecord> _lastErrors = new Collection<ErrorRecord>();
/// <summary>
/// This is for tracking the last set of errors happened during the help
/// search.
/// </summary>
/// <value></value>
internal Collection<ErrorRecord> LastErrors
{
get
{
return _lastErrors;
}
}
private HelpCategory _lastHelpCategory = HelpCategory.None;
/// <summary>
/// This is the help category to search for help for the last command.
/// </summary>
/// <value>help category to search for help</value>
internal HelpCategory LastHelpCategory
{
get
{
return _lastHelpCategory;
}
}
#endregion
#region Configuration
private bool _verboseHelpErrors = false;
/// <summary>
/// VerboseHelpErrors is used in the case when end user is interested
/// to know all errors happened during a help search. This property
/// is false by default.
///
/// If this property is turned on (by setting session variable "VerboseHelpError"),
/// following two behaviours will be different,
/// a. Help errors will be written to error pipeline regardless the situation.
/// (Normally, help errors will be written to error pipeline if there is no
/// help found and there is no wildcard in help search target).
/// b. Some additional warnings, including maml processing warnings, will be
/// written to error pipeline.
/// </summary>
/// <value></value>
internal bool VerboseHelpErrors
{
get
{
return _verboseHelpErrors;
}
}
#endregion
#region Help Engine
// Cache of search paths that are currently active.
// This will save a lot time when help providers do their searching
private Collection<String> _searchPaths = null;
/// <summary>
/// Gets the search paths for external snapins/modules that are currently loaded.
/// If the current shell is single-shell based, then the returned
/// search path contains all the directories of currently active PSSnapIns/modules.
/// </summary>
/// <returns>a collection of strings representing locations</returns>
internal Collection<string> GetSearchPaths()
{
// return the cache if already present.
if (null != _searchPaths)
{
return _searchPaths;
}
_searchPaths = new Collection<String>();
RunspaceConfigForSingleShell runspace = this.ExecutionContext.RunspaceConfiguration as RunspaceConfigForSingleShell;
if (null != runspace)
{
// SingleShell case. Check active snapins...
MshConsoleInfo currentConsole = runspace.ConsoleInfo;
if ((null == currentConsole) || (null == currentConsole.ExternalPSSnapIns))
{
return _searchPaths;
}
foreach (PSSnapInInfo snapin in currentConsole.ExternalPSSnapIns)
{
_searchPaths.Add(snapin.ApplicationBase);
}
}
// add loaded modules paths to the search path
if (null != ExecutionContext.Modules)
{
foreach (PSModuleInfo loadedModule in ExecutionContext.Modules.ModuleTable.Values)
{
if (!_searchPaths.Contains(loadedModule.ModuleBase))
{
_searchPaths.Add(loadedModule.ModuleBase);
}
}
}
return _searchPaths;
}
/// <summary>
/// Get help based on the target, help type, etc
///
/// Help eninge retrieve help based on following schemes,
///
/// 1. if help target is empty, get default help
/// 2. if help target is not a search pattern, try to retrieve exact help
/// 3. if help target is a search pattern or step 2 returns no helpInfo, try to search for help
/// (Search for pattern in command name followed by pattern match in help content)
/// 4. if step 3 returns exact one helpInfo object, try to retrieve exact help.
///
/// </summary>
/// <param name="helpRequest">Help request object</param>
/// <returns>An array of HelpInfo object</returns>
private IEnumerable<HelpInfo> DoGetHelp(HelpRequest helpRequest)
{
_lastErrors.Clear();
// Reset SearchPaths
_searchPaths = null;
_lastHelpCategory = helpRequest.HelpCategory;
if (String.IsNullOrEmpty(helpRequest.Target))
{
HelpInfo helpInfo = GetDefaultHelp();
if (helpInfo != null)
{
yield return helpInfo;
}
yield return null;
}
else
{
bool isMatchFound = false;
if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target))
{
foreach (HelpInfo helpInfo in ExactMatchHelp(helpRequest))
{
isMatchFound = true;
yield return helpInfo;
}
}
if (!isMatchFound)
{
foreach (HelpInfo helpInfo in SearchHelp(helpRequest))
{
isMatchFound = true;
yield return helpInfo;
}
if (!isMatchFound)
{
// Throwing exception here may not be the
// best thing to do. Instead we can choose to
// a. give a hint
// b. just silently return an empty search result.
// Solution:
// If it is an exact help target, throw exception.
// Otherwise, return empty result set.
if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target) && this.LastErrors.Count == 0)
{
Exception e = new HelpNotFoundException(helpRequest.Target);
ErrorRecord errorRecord = new ErrorRecord(e, "HelpNotFound", ErrorCategory.ResourceUnavailable, null);
this.LastErrors.Add(errorRecord);
yield break;
}
}
}
}
}
/// <summary>
/// Get help that exactly match the target.
///
/// If the helpInfo returned is not complete, we will forward the
/// helpInfo object to appropriate help provider for further processing.
/// (this is implemented by ForwardHelp)
///
/// </summary>
/// <param name="helpRequest">Help request object</param>
/// <returns>HelpInfo object retrieved. Can be Null.</returns>
internal IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest)
{
bool isHelpInfoFound = false;
for (int i = 0; i < this.HelpProviders.Count; i++)
{
HelpProvider helpProvider = (HelpProvider)this.HelpProviders[i];
if ((helpProvider.HelpCategory & helpRequest.HelpCategory) > 0)
{
foreach (HelpInfo helpInfo in helpProvider.ExactMatchHelp(helpRequest))
{
isHelpInfoFound = true;
foreach (HelpInfo fwdHelpInfo in ForwardHelp(helpInfo, helpRequest))
{
yield return fwdHelpInfo;
}
}
}
// Bug Win7 737383: Win7 RTM shows both function and cmdlet help when there is
// function and cmdlet with the same name. So, ignoring the ScriptCommandHelpProvider's
// results and going to the CommandHelpProvider for further evaluation.
if (isHelpInfoFound && (!(helpProvider is ScriptCommandHelpProvider)))
{
// once helpInfo found from a provider..no need to traverse other providers.
yield break;
}
}
}
/// <summary>
/// Forward help to the help provider with type forwardHelpCategory.
///
/// This is used in the following known scenarios so far
/// 1. Alias: helpInfo returned by Alias is not what end user needed.
/// The real help can be retrieved from Command help provider.
///
/// </summary>
/// <param name="helpInfo"></param>
/// <param name="helpRequest">Help request object</param>
/// <returns>Never returns null.</returns>
/// <remarks>helpInfos is not null or emtpy.</remarks>
private IEnumerable<HelpInfo> ForwardHelp(HelpInfo helpInfo, HelpRequest helpRequest)
{
Collection<HelpInfo> result = new Collection<HelpInfo>();
// findout if this helpInfo needs to be processed further..
if (helpInfo.ForwardHelpCategory == HelpCategory.None && string.IsNullOrEmpty(helpInfo.ForwardTarget))
{
// this helpInfo is final...so store this in result
// and move on..
yield return helpInfo;
}
else
{
// Find out a capable provider to process this request...
HelpCategory forwardHelpCategory = helpInfo.ForwardHelpCategory;
bool isHelpInfoProcessed = false;
for (int i = 0; i < this.HelpProviders.Count; i++)
{
HelpProvider helpProvider = (HelpProvider)this.HelpProviders[i];
if ((helpProvider.HelpCategory & forwardHelpCategory) != HelpCategory.None)
{
isHelpInfoProcessed = true;
// If this help info is processed by this provider already, break
// out of the provider loop...
foreach (HelpInfo fwdResult in helpProvider.ProcessForwardedHelp(helpInfo, helpRequest))
{
// Add each helpinfo to our repository
foreach (HelpInfo fHelpInfo in ForwardHelp(fwdResult, helpRequest))
{
yield return fHelpInfo;
}
// get out of the provider loop..
yield break;
}
}
}
if (!isHelpInfoProcessed)
{
// we are here because no help provider processed the helpinfo..
// so add this to our repository..
yield return helpInfo;
}
}
}
/// <summary>
/// Get the default help info (normally when help target is empty).
/// </summary>
/// <returns></returns>
private HelpInfo GetDefaultHelp()
{
HelpRequest helpRequest = new HelpRequest("default", HelpCategory.DefaultHelp);
foreach (HelpInfo helpInfo in ExactMatchHelp(helpRequest))
{
// return just the first helpInfo object
return helpInfo;
}
return null;
}
/// <summary>
/// Get help that exactly match the target
/// </summary>
/// <param name="helpRequest">help request object</param>
/// <returns>An IEnumerable of HelpInfo object</returns>
private IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest)
{
int countOfHelpInfosFound = 0;
bool searchInHelpContent = false;
bool shouldBreak = false;
HelpProgressInfo progress = new HelpProgressInfo();
progress.Activity = StringUtil.Format(HelpDisplayStrings.SearchingForHelpContent, helpRequest.Target);
progress.Completed = false;
progress.PercentComplete = 0;
try
{
OnProgress(this, progress);
// algorithm:
// 1. Search for pattern (helpRequest.Target) in command name
// 2. If Step 1 fails then search for pattern in help content
do
{
// we should not continue the search loop if we are
// searching in the help content (as this is the last step
// in our search algorithm).
if (searchInHelpContent)
{
shouldBreak = true;
}
for (int i = 0; i < this.HelpProviders.Count; i++)
{
HelpProvider helpProvider = (HelpProvider)this.HelpProviders[i];
if ((helpProvider.HelpCategory & helpRequest.HelpCategory) > 0)
{
foreach (HelpInfo helpInfo in helpProvider.SearchHelp(helpRequest, searchInHelpContent))
{
if (_executionContext.CurrentPipelineStopping)
{
yield break;
}
countOfHelpInfosFound++;
yield return helpInfo;
if ((countOfHelpInfosFound >= helpRequest.MaxResults) && (helpRequest.MaxResults > 0))
{
yield break;
}
}
}
}
// no need to do help content search once we have some help topics
// with command name search.
if (countOfHelpInfosFound > 0)
{
yield break;
}
// appears that we did not find any help matching command names..look for
// pattern in help content.
searchInHelpContent = true;
if (this.HelpProviders.Count > 0)
{
progress.PercentComplete += (100 / this.HelpProviders.Count);
OnProgress(this, progress);
}
} while (!shouldBreak);
}
finally
{
progress.Completed = true;
progress.PercentComplete = 100;
OnProgress(this, progress);
}
}
#endregion Help Engine
#region Help Provider Manager
private ArrayList _helpProviders = new ArrayList();
/// <summary>
/// return the list of help providers initialized
/// </summary>
/// <value>a list of help providers</value>
internal ArrayList HelpProviders
{
get
{
return _helpProviders;
}
}
/// <summary>
/// Initialize help providers.
/// </summary>
/// <remarks>
/// Currently we hardcode the sequence of help provider initialization.
/// In the longer run, we probably will load help providers based on some provider catalog. That
/// will allow new providers to be defined by customer.
/// </remarks>
private void InitializeHelpProviders()
{
HelpProvider helpProvider = null;
helpProvider = new AliasHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new ScriptCommandHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new CommandHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new ProviderHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new PSClassHelpProvider(this);
_helpProviders.Add(helpProvider);
/* TH Bug#3141590 - Disable DscResourceHelp for ClientRTM due to perf issue.
#if !CORECLR // TODO:CORECLR Add this back in once we support Get-DscResource
helpProvider = new DscResourceHelpProvider(this);
_helpProviders.Add(helpProvider);
#endif
*/
helpProvider = new HelpFileHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new FaqHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new GlossaryHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new GeneralHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new DefaultHelpProvider(this);
_helpProviders.Add(helpProvider);
}
#if _HelpProviderReflection
// Eventually we will publicize the provider api and initialize
// help providers using reflection. This is not in v1 right now.
//
private static HelpProviderInfo[] _providerInfos = new HelpProviderInfo[]
{ new HelpProviderInfo("", "AliasHelpProvider", HelpCategory.Alias),
new HelpProviderInfo("", "CommandHelpProvider", HelpCategory.Command),
new HelpProviderInfo("", "ProviderHelpProvider", HelpCategory.Provider),
new HelpProviderInfo("", "OverviewHelpProvider", HelpCategory.Overview),
new HelpProviderInfo("", "GeneralHelpProvider", HelpCategory.General),
new HelpProviderInfo("", "FAQHelpProvider", HelpCategory.FAQ),
new HelpProviderInfo("", "GlossaryHelpProvider", HelpCategory.Glossary),
new HelpProviderInfo("", "HelpFileHelpProvider", HelpCategory.HelpFile),
new HelpProviderInfo("", "DefaultHelpHelpProvider", HelpCategory.DefaultHelp)
};
private void InitializeHelpProviders()
{
for (int i = 0; i < _providerInfos.Length; i++)
{
HelpProvider helpProvider = GetHelpProvider(_providerInfos[i]);
if (helpProvider != null)
{
helpProvider.Initialize(this._executionContext);
_helpProviders.Add(helpProvider);
}
}
}
private HelpProvider GetHelpProvider(HelpProviderInfo providerInfo)
{
Assembly providerAssembly = null;
if (String.IsNullOrEmpty(providerInfo.AssemblyName))
{
providerAssembly = Assembly.GetExecutingAssembly();
}
else
{
providerAssembly = Assembly.Load(providerInfo.AssemblyName);
}
try
{
if (providerAssembly != null)
{
HelpProvider helpProvider =
(HelpProvider)providerAssembly.CreateInstance(providerInfo.ClassName,
false, // don't ignore case
BindingFlags.CreateInstance,
null, // use default binder
null,
null, // use current culture
null // no special activation attributes
);
return helpProvider;
}
}
catch (TargetInvocationException e)
{
System.Console.WriteLine(e.Message);
if (e.InnerException != null)
{
System.Console.WriteLine(e.InnerException.Message);
System.Console.WriteLine(e.InnerException.StackTrace);
}
}
return null;
}
#endif
#endregion Help Provider Manager
#region Help Error Tracer
private HelpErrorTracer _helpErrorTracer;
/// <summary>
/// The error tracer for this help system
/// </summary>
/// <value></value>
internal HelpErrorTracer HelpErrorTracer
{
get
{
return _helpErrorTracer;
}
}
/// <summary>
/// Start a trace frame for a help file
/// </summary>
/// <param name="helpFile"></param>
/// <returns></returns>
internal IDisposable Trace(string helpFile)
{
if (_helpErrorTracer == null)
return null;
return _helpErrorTracer.Trace(helpFile);
}
/// <summary>
/// Trace an error within a help frame, which is tracked by help tracer itself.
/// </summary>
/// <param name="errorRecord"></param>
internal void TraceError(ErrorRecord errorRecord)
{
if (_helpErrorTracer == null)
return;
_helpErrorTracer.TraceError(errorRecord);
}
/// <summary>
/// Trace a collection of errors within a help frame, which is tracked by
/// help tracer itself.
/// </summary>
/// <param name="errorRecords"></param>
internal void TraceErrors(Collection<ErrorRecord> errorRecords)
{
if (_helpErrorTracer == null || errorRecords == null)
return;
_helpErrorTracer.TraceErrors(errorRecords);
}
#endregion
#region Help MUI
private CultureInfo _culture;
/// <summary>
/// Before each help request is serviced, current thread culture will validate
/// against the current culture of help system. If there is a miss match, each
/// help provider will be notified of the culture change.
/// </summary>
private void ValidateHelpCulture()
{
CultureInfo culture = CultureInfo.CurrentUICulture;
if (_culture == null)
{
_culture = culture;
return;
}
if (_culture.Equals(culture))
{
return;
}
_culture = culture;
ResetHelpProviders();
}
/// <summary>
/// Reset help providers providers. This normally corresponds to help culture change.
///
/// Normally help providers will remove cached help content to make sure new help
/// requests will be served with content of right culture.
///
/// </summary>
internal void ResetHelpProviders()
{
if (_helpProviders == null)
return;
for (int i = 0; i < _helpProviders.Count; i++)
{
HelpProvider helpProvider = (HelpProvider)_helpProviders[i];
helpProvider.Reset();
}
return;
}
#endregion
#region ScriptBlock Parse Tokens Caching/Clearing Functionality
private readonly Lazy<Dictionary<Ast, Token[]>> _scriptBlockTokenCache = new Lazy<Dictionary<Ast, Token[]>>(isThreadSafe: true);
internal Dictionary<Ast, Token[]> ScriptBlockTokenCache
{
get { return _scriptBlockTokenCache.Value; }
}
internal void ClearScriptBlockTokenCache()
{
if (_scriptBlockTokenCache.IsValueCreated)
{
_scriptBlockTokenCache.Value.Clear();
}
}
#endregion
}
/// <summary>
/// Help progress info
/// </summary>
internal class HelpProgressInfo
{
internal bool Completed;
internal string Activity;
internal int PercentComplete;
}
/// <summary>
/// This is the structure to keep track of HelpProvider Info.
/// </summary>
internal class HelpProviderInfo
{
internal string AssemblyName = "";
internal string ClassName = "";
internal HelpCategory HelpCategory = HelpCategory.None;
/// <summary>
/// Constructor
/// </summary>
/// <param name="assemblyName">assembly that contains this help provider</param>
/// <param name="className">the class that implements this help provider</param>
/// <param name="helpCategory">help category of this help provider</param>
internal HelpProviderInfo(string assemblyName, string className, HelpCategory helpCategory)
{
this.AssemblyName = assemblyName;
this.ClassName = className;
this.HelpCategory = helpCategory;
}
}
/// <summary>
/// Help categories
/// </summary>
[Flags]
internal enum HelpCategory
{
/// <summary>
/// Undefined help category
/// </summary>
None = 0x00,
/// <summary>
/// Alias help
/// </summary>
Alias = 0x01,
/// <summary>
/// Cmdlet help
/// </summary>
Cmdlet = 0x02,
/// <summary>
/// Provider help
/// </summary>
Provider = 0x04,
/// <summary>
/// General keyword help
/// </summary>
General = 0x10,
/// <summary>
/// FAQ's
/// </summary>
FAQ = 0x20,
/// <summary>
/// Glossary and term definitions
/// </summary>
Glossary = 0x40,
/// <summary>
/// Help that is contained in help file
/// </summary>
HelpFile = 0x80,
/// <summary>
/// Help from a script block
/// </summary>
ScriptCommand = 0x100,
/// <summary>
/// Help for a function
/// </summary>
Function = 0x200,
/// <summary>
/// Help for a filter
/// </summary>
Filter = 0x400,
/// <summary>
/// Help for an external script (i.e. for a *.ps1 file)
/// </summary>
ExternalScript = 0x800,
/// <summary>
/// All help categories.
/// </summary>
All = 0xFFFFF,
///<summary>
/// Default Help
/// </summary>
DefaultHelp = 0x1000,
///<summary>
/// Help for a Workflow
/// </summary>
Workflow = 0x2000,
///<summary>
/// Help for a Configuration
/// </summary>
Configuration = 0x4000,
/// <summary>
/// Help for DSC Resource
/// </summary>
DscResource = 0x8000,
/// <summary>
/// Help for PS Classes
/// </summary>
Class = 0x10000
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2017 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
#if !MSTEST
using NUnit.Framework;
#else
using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
using TimeoutAttribute = NUnit.Framework.TimeoutAttribute;
using Assert = NUnit.Framework.Assert;
using Is = NUnit.Framework.Is;
#endif
namespace MsgPack
{
partial class TimestampTest
{
[Test]
public void TestFromDateTime_UtcNow_OK()
{
var source = DateTime.UtcNow;
var target = Timestamp.FromDateTime( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestImplicitDateTime_UtcNow_OK()
{
var source = DateTime.UtcNow;
var target = ( Timestamp )source;
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTime_MinValue_OK()
{
var source = DateTime.MinValue;
var target = Timestamp.FromDateTime( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestImplicitDateTime_MinValue_OK()
{
var source = DateTime.MinValue;
var target = ( Timestamp )source;
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTime_MaxValue_OK()
{
var source = DateTime.MaxValue;
var target = Timestamp.FromDateTime( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestImplicitDateTime_MaxValue_OK()
{
var source = DateTime.MaxValue;
var target = ( Timestamp )source;
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestToDateTime_UtcNow_OK()
{
var source = Timestamp.UtcNow;
var target = source.ToDateTime();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestExplicitDateTime_UtcNow_OK()
{
var source = Timestamp.UtcNow;
var target = ( DateTime )source;
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestFromDateTime_Now_AsUtc()
{
var source = DateTime.Now;
var target = Timestamp.FromDateTime( source );
var expected = source.ToUniversalTime();
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestImplicitDateTime_Now_AsUtc()
{
var source = DateTime.Now;
var target = ( Timestamp )source;
var expected = source.ToUniversalTime();
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestToDateTime_OverflowSeconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MaxValue ) + 1L, checked( ( int )( DateTimeOffset.MaxValue.Ticks % 10000000 * 100 ) ) );
Assert.Throws<InvalidOperationException>( () => source.ToDateTime() );
}
[Test]
public void TestToDateTime_OverflowNanoseconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MaxValue ) + 1, 0 );
Assert.Throws<InvalidOperationException>( () => source.ToDateTime() );
}
[Test]
public void TestExplicitDateTime_OverflowSeconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MaxValue ) + 1L, checked( ( int )( DateTimeOffset.MaxValue.Ticks % 10000000 * 100 ) ) );
Assert.Throws<InvalidOperationException>( () => { var x = ( DateTime )source; } );
}
[Test]
public void TestExplicitDateTime_OverflowNanoseconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MaxValue ) + 1, 0 );
Assert.Throws<InvalidOperationException>( () => { var x = ( DateTime )source; } );
}
[Test]
public void TestToDateTime_UnderflowSeconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MinValue ) - 1L, checked( ( int )( DateTimeOffset.MinValue.Ticks % 10000000 * 100 ) ) );
Assert.Throws<InvalidOperationException>( () => source.ToDateTime() );
}
[Test]
public void TestToDateTime_UnderflowNanoseconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MinValue ) -1L, 999999999 );
Assert.Throws<InvalidOperationException>( () => source.ToDateTime() );
}
[Test]
public void TestExplicitDateTime_UnderflowSeconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MinValue ) - 1L, checked( ( int )( DateTimeOffset.MinValue.Ticks % 10000000 * 100 ) ) );
Assert.Throws<InvalidOperationException>( () => { var x = ( DateTime )source; } );
}
[Test]
public void TestExplicitDateTime_UnderflowNanoseconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MinValue ) - 1, 999999999 );
Assert.Throws<InvalidOperationException>( () => { var x = ( DateTime )source; } );
}
private static void AssertSubseconds( DateTime target, Timestamp expected )
{
var ticks = target.Ticks % 10000;
Assert.That( ticks / 10, Is.EqualTo( expected.Microsecond ), "Microsecond" );
Assert.That( ticks % 10, Is.EqualTo( expected.Nanosecond / 100 ), "Nanosecond" );
}
private static void AssertSubseconds( Timestamp target, DateTime expected )
{
var ticks = expected.Ticks % 10000;
Assert.That( target.Microsecond, Is.EqualTo( ticks / 10 ), "Microsecond" );
Assert.That( target.Nanosecond, Is.EqualTo( ( ticks % 10 ) * 100 ), "Nanosecond" );
}
[Test]
public void TestFromDateTimeOffset_UtcNow_OK()
{
var source = DateTimeOffset.UtcNow;
var target = Timestamp.FromDateTimeOffset( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestImplicitDateTimeOffset_UtcNow_OK()
{
var source = DateTimeOffset.UtcNow;
var target = ( Timestamp )source;
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTimeOffset_MinValue_OK()
{
var source = DateTimeOffset.MinValue;
var target = Timestamp.FromDateTimeOffset( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestImplicitDateTimeOffset_MinValue_OK()
{
var source = DateTimeOffset.MinValue;
var target = ( Timestamp )source;
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTimeOffset_MaxValue_OK()
{
var source = DateTimeOffset.MaxValue;
var target = Timestamp.FromDateTimeOffset( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestImplicitDateTimeOffset_MaxValue_OK()
{
var source = DateTimeOffset.MaxValue;
var target = ( Timestamp )source;
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestToDateTimeOffset_UtcNow_OK()
{
var source = Timestamp.UtcNow;
var target = source.ToDateTimeOffset();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestExplicitDateTimeOffset_UtcNow_OK()
{
var source = Timestamp.UtcNow;
var target = ( DateTimeOffset )source;
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestFromDateTimeOffset_Now_AsUtc()
{
var source = DateTimeOffset.Now;
var target = Timestamp.FromDateTimeOffset( source );
var expected = source.ToUniversalTime();
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestImplicitDateTimeOffset_Now_AsUtc()
{
var source = DateTimeOffset.Now;
var target = ( Timestamp )source;
var expected = source.ToUniversalTime();
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestToDateTimeOffset_OverflowSeconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MaxValue ) + 1L, checked( ( int )( DateTimeOffset.MaxValue.Ticks % 10000000 * 100 ) ) );
Assert.Throws<InvalidOperationException>( () => source.ToDateTimeOffset() );
}
[Test]
public void TestToDateTimeOffset_OverflowNanoseconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MaxValue ) + 1, 0 );
Assert.Throws<InvalidOperationException>( () => source.ToDateTimeOffset() );
}
[Test]
public void TestExplicitDateTimeOffset_OverflowSeconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MaxValue ) + 1L, checked( ( int )( DateTimeOffset.MaxValue.Ticks % 10000000 * 100 ) ) );
Assert.Throws<InvalidOperationException>( () => { var x = ( DateTimeOffset )source; } );
}
[Test]
public void TestExplicitDateTimeOffset_OverflowNanoseconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MaxValue ) + 1, 0 );
Assert.Throws<InvalidOperationException>( () => { var x = ( DateTimeOffset )source; } );
}
[Test]
public void TestToDateTimeOffset_UnderflowSeconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MinValue ) - 1L, checked( ( int )( DateTimeOffset.MinValue.Ticks % 10000000 * 100 ) ) );
Assert.Throws<InvalidOperationException>( () => source.ToDateTimeOffset() );
}
[Test]
public void TestToDateTimeOffset_UnderflowNanoseconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MinValue ) -1L, 999999999 );
Assert.Throws<InvalidOperationException>( () => source.ToDateTimeOffset() );
}
[Test]
public void TestExplicitDateTimeOffset_UnderflowSeconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MinValue ) - 1L, checked( ( int )( DateTimeOffset.MinValue.Ticks % 10000000 * 100 ) ) );
Assert.Throws<InvalidOperationException>( () => { var x = ( DateTimeOffset )source; } );
}
[Test]
public void TestExplicitDateTimeOffset_UnderflowNanoseconds()
{
var source = new Timestamp( MessagePackConvert.FromDateTimeOffset( DateTimeOffset.MinValue ) - 1, 999999999 );
Assert.Throws<InvalidOperationException>( () => { var x = ( DateTimeOffset )source; } );
}
private static void AssertSubseconds( DateTimeOffset target, Timestamp expected )
{
var ticks = target.Ticks % 10000;
Assert.That( ticks / 10, Is.EqualTo( expected.Microsecond ), "Microsecond" );
Assert.That( ticks % 10, Is.EqualTo( expected.Nanosecond / 100 ), "Nanosecond" );
}
private static void AssertSubseconds( Timestamp target, DateTimeOffset expected )
{
var ticks = expected.Ticks % 10000;
Assert.That( target.Microsecond, Is.EqualTo( ticks / 10 ), "Microsecond" );
Assert.That( target.Nanosecond, Is.EqualTo( ( ticks % 10 ) * 100 ), "Nanosecond" );
}
#if !NET35 && !SILVERLIGHT && !NETSTANDARD1_1
[Test]
public void TestFromDateTime_UnixEpoc_OK()
{
var source = DateTimeOffset.FromUnixTimeMilliseconds( 0 ).DateTime;
var target = Timestamp.FromDateTime( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTime_UnixEpocMinus1Millisecond_OK()
{
var source = DateTimeOffset.FromUnixTimeMilliseconds( -1 ).DateTime;
var target = Timestamp.FromDateTime( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTime_UnixEpocPlus1Millisecond_OK()
{
var source = DateTimeOffset.FromUnixTimeMilliseconds( 1 ).DateTime;
var target = Timestamp.FromDateTime( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTime_UnixEpocMinusSecond_OK()
{
var source = DateTimeOffset.FromUnixTimeSeconds( -1 ).DateTime;
var target = Timestamp.FromDateTime( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTime_UnixEpocPlus1Second_OK()
{
var source = DateTimeOffset.FromUnixTimeSeconds( 1 ).DateTime;
var target = Timestamp.FromDateTime( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestToDateTime_UnixEpoc_OK()
{
var source = default( Timestamp );
var target = source.ToDateTime();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestToDateTime_UnixEpocMinus1Millisecond_OK()
{
var source = default( Timestamp ).Add( TimeSpan.FromMilliseconds( -1 ) );
var target = source.ToDateTime();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestToDateTime_UnixEpocPlus1Millisecond_OK()
{
var source = default( Timestamp ).Add( TimeSpan.FromMilliseconds( 1 ) );
var target = source.ToDateTime();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestToDateTime_UnixEpocMinus1Second_OK()
{
var source = default( Timestamp ).Add( TimeSpan.FromSeconds( -1 ) );
var target = source.ToDateTime();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestToDateTime_UnixEpocPlus1Second_OK()
{
var source = default( Timestamp ).Add( TimeSpan.FromSeconds( 1 ) );
var target = source.ToDateTime();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestFromDateTimeOffset_UnixEpoc_OK()
{
var source = DateTimeOffset.FromUnixTimeMilliseconds( 0 );
var target = Timestamp.FromDateTimeOffset( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTimeOffset_UnixEpocMinus1Millisecond_OK()
{
var source = DateTimeOffset.FromUnixTimeMilliseconds( -1 );
var target = Timestamp.FromDateTimeOffset( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTimeOffset_UnixEpocPlus1Millisecond_OK()
{
var source = DateTimeOffset.FromUnixTimeMilliseconds( 1 );
var target = Timestamp.FromDateTimeOffset( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTimeOffset_UnixEpocMinus1Second_OK()
{
var source = DateTimeOffset.FromUnixTimeSeconds( -1 );
var target = Timestamp.FromDateTimeOffset( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestFromDateTimeOffset_UnixEpocPlus1Second_OK()
{
var source = DateTimeOffset.FromUnixTimeSeconds( 1 );
var target = Timestamp.FromDateTimeOffset( source );
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
}
[Test]
public void TestToDateTimeOffset_UnixEpoc_OK()
{
var source = default( Timestamp );
var target = source.ToDateTimeOffset();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestToDateTimeOffset_UnixEpocMinus1Millisecond_OK()
{
var source = default( Timestamp ).Add( TimeSpan.FromMilliseconds( -1 ) );
var target = source.ToDateTimeOffset();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestToDateTimeOffset_UnixEpocPlus1Millisecond_OK()
{
var source = default( Timestamp ).Add( TimeSpan.FromMilliseconds( 1 ) );
var target = source.ToDateTimeOffset();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestToDateTimeOffset_UnixEpocMinus1Second_OK()
{
var source = default( Timestamp ).Add( TimeSpan.FromSeconds( -1 ) );
var target = source.ToDateTimeOffset();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
[Test]
public void TestToDateTimeOffset_UnixEpocPlus1Second_OK()
{
var source = default( Timestamp ).Add( TimeSpan.FromSeconds( 1 ) );
var target = source.ToDateTimeOffset();
var expected = source;
Assert.That( target.Year, Is.EqualTo( expected.Year ), "Year" );
Assert.That( target.Month, Is.EqualTo( expected.Month ), "Month" );
Assert.That( target.Day, Is.EqualTo( expected.Day ), "Day" );
Assert.That( target.DayOfYear, Is.EqualTo( expected.DayOfYear ), "DayOfYear" );
Assert.That( target.DayOfWeek, Is.EqualTo( expected.DayOfWeek ), "DayOfWeek" );
Assert.That( target.Hour, Is.EqualTo( expected.Hour ), "Hour" );
Assert.That( target.Minute, Is.EqualTo( expected.Minute ), "Minute" );
Assert.That( target.Second, Is.EqualTo( expected.Second ), "Second" );
Assert.That( target.Millisecond, Is.EqualTo( expected.Millisecond ), "Millisecond" );
AssertSubseconds( target, expected );
AssertUtc( target );
}
#endif // NET35 && !SILVERLIGHT && !NETSTANDARD1_1
}
}
| |
using J2N.Collections.Generic.Extensions;
using J2N.Threading.Atomic;
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Store
{
/*
* 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 CodecUtil = Lucene.Net.Codecs.CodecUtil;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IOUtils = Lucene.Net.Util.IOUtils;
/// <summary>
/// Combines multiple files into a single compound file.
/// <para/>
/// @lucene.internal
/// </summary>
/// <seealso cref="CompoundFileDirectory"/>
internal sealed class CompoundFileWriter : IDisposable
{
private sealed class FileEntry
{
/// <summary>
/// source file </summary>
internal string File { get; set; }
internal long Length { get; set; }
/// <summary>
/// temporary holder for the start of this file's data section </summary>
internal long Offset { get; set; }
/// <summary>
/// the directory which contains the file. </summary>
internal Directory Dir { get; set; }
}
// Before versioning started.
internal const int FORMAT_PRE_VERSION = 0;
// Segment name is not written in the file names.
internal const int FORMAT_NO_SEGMENT_PREFIX = -1;
// versioning for the .cfs file
internal const string DATA_CODEC = "CompoundFileWriterData";
internal const int VERSION_START = 0;
internal const int VERSION_CHECKSUM = 1;
internal const int VERSION_CURRENT = VERSION_CHECKSUM;
// versioning for the .cfe file
internal const string ENTRY_CODEC = "CompoundFileWriterEntries";
private readonly Directory directory;
private readonly IDictionary<string, FileEntry> entries = new Dictionary<string, FileEntry>();
private readonly ISet<string> seenIDs = new JCG.HashSet<string>();
// all entries that are written to a sep. file but not yet moved into CFS
private readonly LinkedList<FileEntry> pendingEntries = new LinkedList<FileEntry>();
private bool closed = false;
private IndexOutput dataOut;
private readonly AtomicBoolean outputTaken = new AtomicBoolean(false);
internal readonly string entryTableName;
internal readonly string dataFileName;
/// <summary>
/// Create the compound stream in the specified file. The file name is the
/// entire name (no extensions are added).
/// </summary>
/// <exception cref="ArgumentNullException">
/// if <paramref name="dir"/> or <paramref name="name"/> is <c>null</c> </exception>
internal CompoundFileWriter(Directory dir, string name)
{
if (dir == null)
{
throw new ArgumentNullException("directory cannot be null");
}
if (name == null)
{
throw new ArgumentNullException("name cannot be null");
}
directory = dir;
entryTableName = IndexFileNames.SegmentFileName(IndexFileNames.StripExtension(name), "", IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION);
dataFileName = name;
}
private IndexOutput GetOutput()
{
lock (this)
{
if (dataOut == null)
{
bool success = false;
try
{
dataOut = directory.CreateOutput(dataFileName, IOContext.DEFAULT);
CodecUtil.WriteHeader(dataOut, DATA_CODEC, VERSION_CURRENT);
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(dataOut);
}
}
}
return dataOut;
}
}
/// <summary>
/// Returns the directory of the compound file. </summary>
internal Directory Directory => directory;
/// <summary>
/// Returns the name of the compound file. </summary>
internal string Name => dataFileName;
/// <summary>
/// Disposes all resources and writes the entry table
/// </summary>
/// <exception cref="InvalidOperationException">
/// if <see cref="Dispose"/> had been called before or if no file has been added to
/// this object </exception>
public void Dispose()
{
if (closed)
{
return;
}
IOException priorException = null;
IndexOutput entryTableOut = null;
// TODO this code should clean up after itself
// (remove partial .cfs/.cfe)
try
{
if (pendingEntries.Count > 0 || outputTaken)
{
throw new InvalidOperationException("CFS has pending open files");
}
closed = true;
// open the compound stream
GetOutput();
if (Debugging.AssertsEnabled) Debugging.Assert(dataOut != null);
CodecUtil.WriteFooter(dataOut);
}
catch (IOException e)
{
priorException = e;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorException, dataOut);
}
try
{
entryTableOut = directory.CreateOutput(entryTableName, IOContext.DEFAULT);
WriteEntryTable(entries.Values, entryTableOut);
}
catch (IOException e)
{
priorException = e;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorException, entryTableOut);
}
}
private void EnsureOpen()
{
if (closed)
{
throw new ObjectDisposedException(this.GetType().FullName, "CFS Directory is already closed");
}
}
/// <summary>
/// Copy the contents of the file with specified extension into the provided
/// output stream.
/// </summary>
private long CopyFileEntry(IndexOutput dataOut, FileEntry fileEntry)
{
IndexInput @is = fileEntry.Dir.OpenInput(fileEntry.File, IOContext.READ_ONCE);
bool success = false;
try
{
long startPtr = dataOut.GetFilePointer();
long length = fileEntry.Length;
dataOut.CopyBytes(@is, length);
// Verify that the output length diff is equal to original file
long endPtr = dataOut.GetFilePointer();
long diff = endPtr - startPtr;
if (diff != length)
{
throw new IOException("Difference in the output file offsets " + diff + " does not match the original file length " + length);
}
fileEntry.Offset = startPtr;
success = true;
return length;
}
finally
{
if (success)
{
IOUtils.Dispose(@is);
// copy successful - delete file
fileEntry.Dir.DeleteFile(fileEntry.File);
}
else
{
IOUtils.DisposeWhileHandlingException(@is);
}
}
}
private void WriteEntryTable(ICollection<FileEntry> entries, IndexOutput entryOut)
{
CodecUtil.WriteHeader(entryOut, ENTRY_CODEC, VERSION_CURRENT);
entryOut.WriteVInt32(entries.Count);
foreach (FileEntry fe in entries)
{
entryOut.WriteString(IndexFileNames.StripSegmentName(fe.File));
entryOut.WriteInt64(fe.Offset);
entryOut.WriteInt64(fe.Length);
}
CodecUtil.WriteFooter(entryOut);
}
internal IndexOutput CreateOutput(string name, IOContext context)
{
EnsureOpen();
bool success = false;
bool outputLocked = false;
try
{
if (Debugging.AssertsEnabled) Debugging.Assert(name != null, "name must not be null");
if (entries.ContainsKey(name))
{
throw new ArgumentException("File " + name + " already exists");
}
FileEntry entry = new FileEntry();
entry.File = name;
entries[name] = entry;
string id = IndexFileNames.StripSegmentName(name);
if (Debugging.AssertsEnabled) Debugging.Assert(!seenIDs.Contains(id), () => "file=\"" + name + "\" maps to id=\"" + id + "\", which was already written");
seenIDs.Add(id);
DirectCFSIndexOutput @out;
if ((outputLocked = outputTaken.CompareAndSet(false, true)))
{
@out = new DirectCFSIndexOutput(this, GetOutput(), entry, false);
}
else
{
entry.Dir = this.directory;
@out = new DirectCFSIndexOutput(this, directory.CreateOutput(name, context), entry, true);
}
success = true;
return @out;
}
finally
{
if (!success)
{
entries.Remove(name);
if (outputLocked) // release the output lock if not successful
{
if (Debugging.AssertsEnabled) Debugging.Assert(outputTaken);
ReleaseOutputLock();
}
}
}
}
internal void ReleaseOutputLock()
{
outputTaken.CompareAndSet(true, false);
}
private void PrunePendingEntries()
{
// claim the output and copy all pending files in
if (outputTaken.CompareAndSet(false, true))
{
try
{
while (pendingEntries.Count > 0)
{
FileEntry entry = pendingEntries.First.Value;
pendingEntries.Remove(entry); ;
CopyFileEntry(GetOutput(), entry);
entries[entry.File] = entry;
}
}
finally
{
bool compareAndSet = outputTaken.CompareAndSet(true, false);
if (Debugging.AssertsEnabled) Debugging.Assert(compareAndSet);
}
}
}
internal long FileLength(string name)
{
FileEntry fileEntry = entries[name];
if (fileEntry == null)
{
throw new FileNotFoundException(name + " does not exist");
}
return fileEntry.Length;
}
internal bool FileExists(string name)
{
return entries.ContainsKey(name);
}
internal string[] ListAll()
{
return entries.Keys.ToArray();
}
private sealed class DirectCFSIndexOutput : IndexOutput
{
private readonly CompoundFileWriter outerInstance;
private readonly IndexOutput @delegate;
private readonly long offset;
private bool closed;
private FileEntry entry;
private long writtenBytes;
private readonly bool isSeparate;
internal DirectCFSIndexOutput(CompoundFileWriter outerInstance, IndexOutput @delegate, FileEntry entry, bool isSeparate)
: base()
{
this.outerInstance = outerInstance;
this.@delegate = @delegate;
this.entry = entry;
entry.Offset = offset = @delegate.GetFilePointer();
this.isSeparate = isSeparate;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Flush()
{
@delegate.Flush();
}
protected override void Dispose(bool disposing)
{
if (disposing && !closed)
{
closed = true;
entry.Length = writtenBytes;
if (isSeparate)
{
@delegate.Dispose();
// we are a separate file - push into the pending entries
outerInstance.pendingEntries.AddLast(entry);
}
else
{
// we have been written into the CFS directly - release the lock
outerInstance.ReleaseOutputLock();
}
// now prune all pending entries and push them into the CFS
outerInstance.PrunePendingEntries();
}
}
public override long GetFilePointer()
{
return @delegate.GetFilePointer() - offset;
}
[Obsolete("(4.1) this method will be removed in Lucene 5.0")]
public override void Seek(long pos)
{
if (Debugging.AssertsEnabled) Debugging.Assert(!closed);
@delegate.Seek(offset + pos);
}
public override long Length
{
get
{
if (Debugging.AssertsEnabled) Debugging.Assert(!closed);
return @delegate.Length - offset;
}
}
public override void WriteByte(byte b)
{
if (Debugging.AssertsEnabled) Debugging.Assert(!closed);
writtenBytes++;
@delegate.WriteByte(b);
}
public override void WriteBytes(byte[] b, int offset, int length)
{
if (Debugging.AssertsEnabled) Debugging.Assert(!closed);
writtenBytes += length;
@delegate.WriteBytes(b, offset, length);
}
public override long Checksum => @delegate.Checksum;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SAEON.Observations.Data{
/// <summary>
/// Strongly-typed collection for the VObservationODatum class.
/// </summary>
[Serializable]
public partial class VObservationODatumCollection : ReadOnlyList<VObservationODatum, VObservationODatumCollection>
{
public VObservationODatumCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vObservationOData view.
/// </summary>
[Serializable]
public partial class VObservationODatum : ReadOnlyRecord<VObservationODatum>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("vObservationOData", TableType.View, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "ID";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = false;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = false;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarSensorID = new TableSchema.TableColumn(schema);
colvarSensorID.ColumnName = "SensorID";
colvarSensorID.DataType = DbType.Guid;
colvarSensorID.MaxLength = 0;
colvarSensorID.AutoIncrement = false;
colvarSensorID.IsNullable = false;
colvarSensorID.IsPrimaryKey = false;
colvarSensorID.IsForeignKey = false;
colvarSensorID.IsReadOnly = false;
schema.Columns.Add(colvarSensorID);
TableSchema.TableColumn colvarValueDate = new TableSchema.TableColumn(schema);
colvarValueDate.ColumnName = "ValueDate";
colvarValueDate.DataType = DbType.DateTime;
colvarValueDate.MaxLength = 0;
colvarValueDate.AutoIncrement = false;
colvarValueDate.IsNullable = false;
colvarValueDate.IsPrimaryKey = false;
colvarValueDate.IsForeignKey = false;
colvarValueDate.IsReadOnly = false;
schema.Columns.Add(colvarValueDate);
TableSchema.TableColumn colvarDataValue = new TableSchema.TableColumn(schema);
colvarDataValue.ColumnName = "DataValue";
colvarDataValue.DataType = DbType.Double;
colvarDataValue.MaxLength = 0;
colvarDataValue.AutoIncrement = false;
colvarDataValue.IsNullable = true;
colvarDataValue.IsPrimaryKey = false;
colvarDataValue.IsForeignKey = false;
colvarDataValue.IsReadOnly = false;
schema.Columns.Add(colvarDataValue);
TableSchema.TableColumn colvarTextValue = new TableSchema.TableColumn(schema);
colvarTextValue.ColumnName = "TextValue";
colvarTextValue.DataType = DbType.AnsiString;
colvarTextValue.MaxLength = 10;
colvarTextValue.AutoIncrement = false;
colvarTextValue.IsNullable = true;
colvarTextValue.IsPrimaryKey = false;
colvarTextValue.IsForeignKey = false;
colvarTextValue.IsReadOnly = false;
schema.Columns.Add(colvarTextValue);
TableSchema.TableColumn colvarLatitude = new TableSchema.TableColumn(schema);
colvarLatitude.ColumnName = "Latitude";
colvarLatitude.DataType = DbType.Double;
colvarLatitude.MaxLength = 0;
colvarLatitude.AutoIncrement = false;
colvarLatitude.IsNullable = true;
colvarLatitude.IsPrimaryKey = false;
colvarLatitude.IsForeignKey = false;
colvarLatitude.IsReadOnly = false;
schema.Columns.Add(colvarLatitude);
TableSchema.TableColumn colvarLongitude = new TableSchema.TableColumn(schema);
colvarLongitude.ColumnName = "Longitude";
colvarLongitude.DataType = DbType.Double;
colvarLongitude.MaxLength = 0;
colvarLongitude.AutoIncrement = false;
colvarLongitude.IsNullable = true;
colvarLongitude.IsPrimaryKey = false;
colvarLongitude.IsForeignKey = false;
colvarLongitude.IsReadOnly = false;
schema.Columns.Add(colvarLongitude);
TableSchema.TableColumn colvarElevation = new TableSchema.TableColumn(schema);
colvarElevation.ColumnName = "Elevation";
colvarElevation.DataType = DbType.Double;
colvarElevation.MaxLength = 0;
colvarElevation.AutoIncrement = false;
colvarElevation.IsNullable = true;
colvarElevation.IsPrimaryKey = false;
colvarElevation.IsForeignKey = false;
colvarElevation.IsReadOnly = false;
schema.Columns.Add(colvarElevation);
TableSchema.TableColumn colvarPhenomenonID = new TableSchema.TableColumn(schema);
colvarPhenomenonID.ColumnName = "PhenomenonID";
colvarPhenomenonID.DataType = DbType.Guid;
colvarPhenomenonID.MaxLength = 0;
colvarPhenomenonID.AutoIncrement = false;
colvarPhenomenonID.IsNullable = false;
colvarPhenomenonID.IsPrimaryKey = false;
colvarPhenomenonID.IsForeignKey = false;
colvarPhenomenonID.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonID);
TableSchema.TableColumn colvarPhenomenonCode = new TableSchema.TableColumn(schema);
colvarPhenomenonCode.ColumnName = "PhenomenonCode";
colvarPhenomenonCode.DataType = DbType.AnsiString;
colvarPhenomenonCode.MaxLength = 50;
colvarPhenomenonCode.AutoIncrement = false;
colvarPhenomenonCode.IsNullable = false;
colvarPhenomenonCode.IsPrimaryKey = false;
colvarPhenomenonCode.IsForeignKey = false;
colvarPhenomenonCode.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonCode);
TableSchema.TableColumn colvarPhenomenonName = new TableSchema.TableColumn(schema);
colvarPhenomenonName.ColumnName = "PhenomenonName";
colvarPhenomenonName.DataType = DbType.AnsiString;
colvarPhenomenonName.MaxLength = 150;
colvarPhenomenonName.AutoIncrement = false;
colvarPhenomenonName.IsNullable = false;
colvarPhenomenonName.IsPrimaryKey = false;
colvarPhenomenonName.IsForeignKey = false;
colvarPhenomenonName.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonName);
TableSchema.TableColumn colvarPhenomenonDescription = new TableSchema.TableColumn(schema);
colvarPhenomenonDescription.ColumnName = "PhenomenonDescription";
colvarPhenomenonDescription.DataType = DbType.AnsiString;
colvarPhenomenonDescription.MaxLength = 5000;
colvarPhenomenonDescription.AutoIncrement = false;
colvarPhenomenonDescription.IsNullable = true;
colvarPhenomenonDescription.IsPrimaryKey = false;
colvarPhenomenonDescription.IsForeignKey = false;
colvarPhenomenonDescription.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonDescription);
TableSchema.TableColumn colvarOfferingID = new TableSchema.TableColumn(schema);
colvarOfferingID.ColumnName = "OfferingID";
colvarOfferingID.DataType = DbType.Guid;
colvarOfferingID.MaxLength = 0;
colvarOfferingID.AutoIncrement = false;
colvarOfferingID.IsNullable = false;
colvarOfferingID.IsPrimaryKey = false;
colvarOfferingID.IsForeignKey = false;
colvarOfferingID.IsReadOnly = false;
schema.Columns.Add(colvarOfferingID);
TableSchema.TableColumn colvarOfferingCode = new TableSchema.TableColumn(schema);
colvarOfferingCode.ColumnName = "OfferingCode";
colvarOfferingCode.DataType = DbType.AnsiString;
colvarOfferingCode.MaxLength = 50;
colvarOfferingCode.AutoIncrement = false;
colvarOfferingCode.IsNullable = false;
colvarOfferingCode.IsPrimaryKey = false;
colvarOfferingCode.IsForeignKey = false;
colvarOfferingCode.IsReadOnly = false;
schema.Columns.Add(colvarOfferingCode);
TableSchema.TableColumn colvarOfferingName = new TableSchema.TableColumn(schema);
colvarOfferingName.ColumnName = "OfferingName";
colvarOfferingName.DataType = DbType.AnsiString;
colvarOfferingName.MaxLength = 150;
colvarOfferingName.AutoIncrement = false;
colvarOfferingName.IsNullable = false;
colvarOfferingName.IsPrimaryKey = false;
colvarOfferingName.IsForeignKey = false;
colvarOfferingName.IsReadOnly = false;
schema.Columns.Add(colvarOfferingName);
TableSchema.TableColumn colvarOfferingDescription = new TableSchema.TableColumn(schema);
colvarOfferingDescription.ColumnName = "OfferingDescription";
colvarOfferingDescription.DataType = DbType.AnsiString;
colvarOfferingDescription.MaxLength = 5000;
colvarOfferingDescription.AutoIncrement = false;
colvarOfferingDescription.IsNullable = true;
colvarOfferingDescription.IsPrimaryKey = false;
colvarOfferingDescription.IsForeignKey = false;
colvarOfferingDescription.IsReadOnly = false;
schema.Columns.Add(colvarOfferingDescription);
TableSchema.TableColumn colvarUnitOfMeasureID = new TableSchema.TableColumn(schema);
colvarUnitOfMeasureID.ColumnName = "UnitOfMeasureID";
colvarUnitOfMeasureID.DataType = DbType.Guid;
colvarUnitOfMeasureID.MaxLength = 0;
colvarUnitOfMeasureID.AutoIncrement = false;
colvarUnitOfMeasureID.IsNullable = false;
colvarUnitOfMeasureID.IsPrimaryKey = false;
colvarUnitOfMeasureID.IsForeignKey = false;
colvarUnitOfMeasureID.IsReadOnly = false;
schema.Columns.Add(colvarUnitOfMeasureID);
TableSchema.TableColumn colvarUnitOfMeasureCode = new TableSchema.TableColumn(schema);
colvarUnitOfMeasureCode.ColumnName = "UnitOfMeasureCode";
colvarUnitOfMeasureCode.DataType = DbType.AnsiString;
colvarUnitOfMeasureCode.MaxLength = 50;
colvarUnitOfMeasureCode.AutoIncrement = false;
colvarUnitOfMeasureCode.IsNullable = false;
colvarUnitOfMeasureCode.IsPrimaryKey = false;
colvarUnitOfMeasureCode.IsForeignKey = false;
colvarUnitOfMeasureCode.IsReadOnly = false;
schema.Columns.Add(colvarUnitOfMeasureCode);
TableSchema.TableColumn colvarUnitOfMeasureUnit = new TableSchema.TableColumn(schema);
colvarUnitOfMeasureUnit.ColumnName = "UnitOfMeasureUnit";
colvarUnitOfMeasureUnit.DataType = DbType.AnsiString;
colvarUnitOfMeasureUnit.MaxLength = 100;
colvarUnitOfMeasureUnit.AutoIncrement = false;
colvarUnitOfMeasureUnit.IsNullable = false;
colvarUnitOfMeasureUnit.IsPrimaryKey = false;
colvarUnitOfMeasureUnit.IsForeignKey = false;
colvarUnitOfMeasureUnit.IsReadOnly = false;
schema.Columns.Add(colvarUnitOfMeasureUnit);
TableSchema.TableColumn colvarUnitOfMeasureSymbol = new TableSchema.TableColumn(schema);
colvarUnitOfMeasureSymbol.ColumnName = "UnitOfMeasureSymbol";
colvarUnitOfMeasureSymbol.DataType = DbType.AnsiString;
colvarUnitOfMeasureSymbol.MaxLength = 20;
colvarUnitOfMeasureSymbol.AutoIncrement = false;
colvarUnitOfMeasureSymbol.IsNullable = false;
colvarUnitOfMeasureSymbol.IsPrimaryKey = false;
colvarUnitOfMeasureSymbol.IsForeignKey = false;
colvarUnitOfMeasureSymbol.IsReadOnly = false;
schema.Columns.Add(colvarUnitOfMeasureSymbol);
TableSchema.TableColumn colvarCorrelationID = new TableSchema.TableColumn(schema);
colvarCorrelationID.ColumnName = "CorrelationID";
colvarCorrelationID.DataType = DbType.Guid;
colvarCorrelationID.MaxLength = 0;
colvarCorrelationID.AutoIncrement = false;
colvarCorrelationID.IsNullable = true;
colvarCorrelationID.IsPrimaryKey = false;
colvarCorrelationID.IsForeignKey = false;
colvarCorrelationID.IsReadOnly = false;
schema.Columns.Add(colvarCorrelationID);
TableSchema.TableColumn colvarComment = new TableSchema.TableColumn(schema);
colvarComment.ColumnName = "Comment";
colvarComment.DataType = DbType.AnsiString;
colvarComment.MaxLength = 250;
colvarComment.AutoIncrement = false;
colvarComment.IsNullable = true;
colvarComment.IsPrimaryKey = false;
colvarComment.IsForeignKey = false;
colvarComment.IsReadOnly = false;
schema.Columns.Add(colvarComment);
TableSchema.TableColumn colvarStatusCode = new TableSchema.TableColumn(schema);
colvarStatusCode.ColumnName = "StatusCode";
colvarStatusCode.DataType = DbType.AnsiString;
colvarStatusCode.MaxLength = 50;
colvarStatusCode.AutoIncrement = false;
colvarStatusCode.IsNullable = true;
colvarStatusCode.IsPrimaryKey = false;
colvarStatusCode.IsForeignKey = false;
colvarStatusCode.IsReadOnly = false;
schema.Columns.Add(colvarStatusCode);
TableSchema.TableColumn colvarStatusName = new TableSchema.TableColumn(schema);
colvarStatusName.ColumnName = "StatusName";
colvarStatusName.DataType = DbType.AnsiString;
colvarStatusName.MaxLength = 150;
colvarStatusName.AutoIncrement = false;
colvarStatusName.IsNullable = true;
colvarStatusName.IsPrimaryKey = false;
colvarStatusName.IsForeignKey = false;
colvarStatusName.IsReadOnly = false;
schema.Columns.Add(colvarStatusName);
TableSchema.TableColumn colvarStatusDescription = new TableSchema.TableColumn(schema);
colvarStatusDescription.ColumnName = "StatusDescription";
colvarStatusDescription.DataType = DbType.AnsiString;
colvarStatusDescription.MaxLength = 500;
colvarStatusDescription.AutoIncrement = false;
colvarStatusDescription.IsNullable = true;
colvarStatusDescription.IsPrimaryKey = false;
colvarStatusDescription.IsForeignKey = false;
colvarStatusDescription.IsReadOnly = false;
schema.Columns.Add(colvarStatusDescription);
TableSchema.TableColumn colvarStatusReasonCode = new TableSchema.TableColumn(schema);
colvarStatusReasonCode.ColumnName = "StatusReasonCode";
colvarStatusReasonCode.DataType = DbType.AnsiString;
colvarStatusReasonCode.MaxLength = 50;
colvarStatusReasonCode.AutoIncrement = false;
colvarStatusReasonCode.IsNullable = true;
colvarStatusReasonCode.IsPrimaryKey = false;
colvarStatusReasonCode.IsForeignKey = false;
colvarStatusReasonCode.IsReadOnly = false;
schema.Columns.Add(colvarStatusReasonCode);
TableSchema.TableColumn colvarStatusReasonName = new TableSchema.TableColumn(schema);
colvarStatusReasonName.ColumnName = "StatusReasonName";
colvarStatusReasonName.DataType = DbType.AnsiString;
colvarStatusReasonName.MaxLength = 150;
colvarStatusReasonName.AutoIncrement = false;
colvarStatusReasonName.IsNullable = true;
colvarStatusReasonName.IsPrimaryKey = false;
colvarStatusReasonName.IsForeignKey = false;
colvarStatusReasonName.IsReadOnly = false;
schema.Columns.Add(colvarStatusReasonName);
TableSchema.TableColumn colvarStatusReasonDescription = new TableSchema.TableColumn(schema);
colvarStatusReasonDescription.ColumnName = "StatusReasonDescription";
colvarStatusReasonDescription.DataType = DbType.AnsiString;
colvarStatusReasonDescription.MaxLength = 500;
colvarStatusReasonDescription.AutoIncrement = false;
colvarStatusReasonDescription.IsNullable = true;
colvarStatusReasonDescription.IsPrimaryKey = false;
colvarStatusReasonDescription.IsForeignKey = false;
colvarStatusReasonDescription.IsReadOnly = false;
schema.Columns.Add(colvarStatusReasonDescription);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("vObservationOData",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VObservationODatum()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VObservationODatum(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VObservationODatum(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VObservationODatum(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get
{
return GetColumnValue<int>("ID");
}
set
{
SetColumnValue("ID", value);
}
}
[XmlAttribute("SensorID")]
[Bindable(true)]
public Guid SensorID
{
get
{
return GetColumnValue<Guid>("SensorID");
}
set
{
SetColumnValue("SensorID", value);
}
}
[XmlAttribute("ValueDate")]
[Bindable(true)]
public DateTime ValueDate
{
get
{
return GetColumnValue<DateTime>("ValueDate");
}
set
{
SetColumnValue("ValueDate", value);
}
}
[XmlAttribute("DataValue")]
[Bindable(true)]
public double? DataValue
{
get
{
return GetColumnValue<double?>("DataValue");
}
set
{
SetColumnValue("DataValue", value);
}
}
[XmlAttribute("TextValue")]
[Bindable(true)]
public string TextValue
{
get
{
return GetColumnValue<string>("TextValue");
}
set
{
SetColumnValue("TextValue", value);
}
}
[XmlAttribute("Latitude")]
[Bindable(true)]
public double? Latitude
{
get
{
return GetColumnValue<double?>("Latitude");
}
set
{
SetColumnValue("Latitude", value);
}
}
[XmlAttribute("Longitude")]
[Bindable(true)]
public double? Longitude
{
get
{
return GetColumnValue<double?>("Longitude");
}
set
{
SetColumnValue("Longitude", value);
}
}
[XmlAttribute("Elevation")]
[Bindable(true)]
public double? Elevation
{
get
{
return GetColumnValue<double?>("Elevation");
}
set
{
SetColumnValue("Elevation", value);
}
}
[XmlAttribute("PhenomenonID")]
[Bindable(true)]
public Guid PhenomenonID
{
get
{
return GetColumnValue<Guid>("PhenomenonID");
}
set
{
SetColumnValue("PhenomenonID", value);
}
}
[XmlAttribute("PhenomenonCode")]
[Bindable(true)]
public string PhenomenonCode
{
get
{
return GetColumnValue<string>("PhenomenonCode");
}
set
{
SetColumnValue("PhenomenonCode", value);
}
}
[XmlAttribute("PhenomenonName")]
[Bindable(true)]
public string PhenomenonName
{
get
{
return GetColumnValue<string>("PhenomenonName");
}
set
{
SetColumnValue("PhenomenonName", value);
}
}
[XmlAttribute("PhenomenonDescription")]
[Bindable(true)]
public string PhenomenonDescription
{
get
{
return GetColumnValue<string>("PhenomenonDescription");
}
set
{
SetColumnValue("PhenomenonDescription", value);
}
}
[XmlAttribute("OfferingID")]
[Bindable(true)]
public Guid OfferingID
{
get
{
return GetColumnValue<Guid>("OfferingID");
}
set
{
SetColumnValue("OfferingID", value);
}
}
[XmlAttribute("OfferingCode")]
[Bindable(true)]
public string OfferingCode
{
get
{
return GetColumnValue<string>("OfferingCode");
}
set
{
SetColumnValue("OfferingCode", value);
}
}
[XmlAttribute("OfferingName")]
[Bindable(true)]
public string OfferingName
{
get
{
return GetColumnValue<string>("OfferingName");
}
set
{
SetColumnValue("OfferingName", value);
}
}
[XmlAttribute("OfferingDescription")]
[Bindable(true)]
public string OfferingDescription
{
get
{
return GetColumnValue<string>("OfferingDescription");
}
set
{
SetColumnValue("OfferingDescription", value);
}
}
[XmlAttribute("UnitOfMeasureID")]
[Bindable(true)]
public Guid UnitOfMeasureID
{
get
{
return GetColumnValue<Guid>("UnitOfMeasureID");
}
set
{
SetColumnValue("UnitOfMeasureID", value);
}
}
[XmlAttribute("UnitOfMeasureCode")]
[Bindable(true)]
public string UnitOfMeasureCode
{
get
{
return GetColumnValue<string>("UnitOfMeasureCode");
}
set
{
SetColumnValue("UnitOfMeasureCode", value);
}
}
[XmlAttribute("UnitOfMeasureUnit")]
[Bindable(true)]
public string UnitOfMeasureUnit
{
get
{
return GetColumnValue<string>("UnitOfMeasureUnit");
}
set
{
SetColumnValue("UnitOfMeasureUnit", value);
}
}
[XmlAttribute("UnitOfMeasureSymbol")]
[Bindable(true)]
public string UnitOfMeasureSymbol
{
get
{
return GetColumnValue<string>("UnitOfMeasureSymbol");
}
set
{
SetColumnValue("UnitOfMeasureSymbol", value);
}
}
[XmlAttribute("CorrelationID")]
[Bindable(true)]
public Guid? CorrelationID
{
get
{
return GetColumnValue<Guid?>("CorrelationID");
}
set
{
SetColumnValue("CorrelationID", value);
}
}
[XmlAttribute("Comment")]
[Bindable(true)]
public string Comment
{
get
{
return GetColumnValue<string>("Comment");
}
set
{
SetColumnValue("Comment", value);
}
}
[XmlAttribute("StatusCode")]
[Bindable(true)]
public string StatusCode
{
get
{
return GetColumnValue<string>("StatusCode");
}
set
{
SetColumnValue("StatusCode", value);
}
}
[XmlAttribute("StatusName")]
[Bindable(true)]
public string StatusName
{
get
{
return GetColumnValue<string>("StatusName");
}
set
{
SetColumnValue("StatusName", value);
}
}
[XmlAttribute("StatusDescription")]
[Bindable(true)]
public string StatusDescription
{
get
{
return GetColumnValue<string>("StatusDescription");
}
set
{
SetColumnValue("StatusDescription", value);
}
}
[XmlAttribute("StatusReasonCode")]
[Bindable(true)]
public string StatusReasonCode
{
get
{
return GetColumnValue<string>("StatusReasonCode");
}
set
{
SetColumnValue("StatusReasonCode", value);
}
}
[XmlAttribute("StatusReasonName")]
[Bindable(true)]
public string StatusReasonName
{
get
{
return GetColumnValue<string>("StatusReasonName");
}
set
{
SetColumnValue("StatusReasonName", value);
}
}
[XmlAttribute("StatusReasonDescription")]
[Bindable(true)]
public string StatusReasonDescription
{
get
{
return GetColumnValue<string>("StatusReasonDescription");
}
set
{
SetColumnValue("StatusReasonDescription", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"ID";
public static string SensorID = @"SensorID";
public static string ValueDate = @"ValueDate";
public static string DataValue = @"DataValue";
public static string TextValue = @"TextValue";
public static string Latitude = @"Latitude";
public static string Longitude = @"Longitude";
public static string Elevation = @"Elevation";
public static string PhenomenonID = @"PhenomenonID";
public static string PhenomenonCode = @"PhenomenonCode";
public static string PhenomenonName = @"PhenomenonName";
public static string PhenomenonDescription = @"PhenomenonDescription";
public static string OfferingID = @"OfferingID";
public static string OfferingCode = @"OfferingCode";
public static string OfferingName = @"OfferingName";
public static string OfferingDescription = @"OfferingDescription";
public static string UnitOfMeasureID = @"UnitOfMeasureID";
public static string UnitOfMeasureCode = @"UnitOfMeasureCode";
public static string UnitOfMeasureUnit = @"UnitOfMeasureUnit";
public static string UnitOfMeasureSymbol = @"UnitOfMeasureSymbol";
public static string CorrelationID = @"CorrelationID";
public static string Comment = @"Comment";
public static string StatusCode = @"StatusCode";
public static string StatusName = @"StatusName";
public static string StatusDescription = @"StatusDescription";
public static string StatusReasonCode = @"StatusReasonCode";
public static string StatusReasonName = @"StatusReasonName";
public static string StatusReasonDescription = @"StatusReasonDescription";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using XnaVG;
using XnaFlash.Actions;
using XnaFlash.Content;
using XnaFlash.Swf;
using XnaFlash.Swf.Tags;
namespace XnaFlash
{
public class FlashDocument : Sprite
{
private Dictionary<ushort, ICharacter> _characters = new Dictionary<ushort, ICharacter>();
private Dictionary<string, ushort> _scenes = new Dictionary<string, ushort>();
private List<ushort> _initOrder = new List<ushort>();
public VGColor BackgroundColor { get; private set; }
public string Name { get; private set; }
public byte Version { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
public double FrameDelay { get; private set; }
public override Rectangle? Bounds { get { return new Rectangle(0, 0, Width, Height); } }
internal ICharacter this[ushort id]
{
get
{
ICharacter value;
if (!_characters.TryGetValue(id, out value))
return null;
return value;
}
}
public FlashDocument(string name, SwfStream stream, ISystemServices services)
: base(stream.ProcessFile(), 0, stream.FrameCount, services)
{
Name = name;
Version = stream.Version;
Width = stream.Rectangle.Width;
Height = stream.Rectangle.Height;
FrameDelay = 1000.0 / (double)stream.FrameRate;
}
protected override void UnhandledTag(ISwfTag tag, ISystemServices services)
{
if (tag is ISwfDefinitionTag)
{
var defTag = tag as ISwfDefinitionTag;
ICharacter character = null;
switch (defTag.Type)
{
case CharacterType.BinaryData: character = new BinaryData(defTag.CharacterID, (tag as DefineBinaryDataTag).Data); break;
case CharacterType.Bitmap: character = new Bitmap(defTag, services); break;
case CharacterType.Button: character = new ButtonInfo(defTag, services, this); break;
case CharacterType.Shape: character = new Shape(defTag, services, this); break;
case CharacterType.Text: character = new Text(tag as DefineTextTag, services, this); break;
case CharacterType.Sprite:
{
var sprite = tag as DefineSpriteTag;
character = new Sprite(sprite.Tags, defTag.CharacterID, sprite.FrameCount, services);
}
break;
case CharacterType.Font:
{
var font = new Font(defTag.CharacterID);
font.AddInfo(tag, services);
character = font;
}
break;
}
if (character != null)
_characters.Add(defTag.CharacterID, character);
}
else if (tag is SetBackgroundColorTag)
{
BackgroundColor = (tag as SetBackgroundColorTag).Color;
}
else if (tag is DefineScenesAndFrameLabelsTag)
{
var def = tag as DefineScenesAndFrameLabelsTag;
_frameLabels = new Dictionary<string, ushort>(def.FrameLabels);
_scenes = new Dictionary<string, ushort>(def.Scenes);
}
else if (tag is DefineFontInfoTag)
{
var fi = tag as DefineFontInfoTag;
(_characters[fi.FontID] as Font).AddInfo(tag, services);
}
else if (tag is DoInitActionTag)
{
var init = tag as DoInitActionTag;
(_characters[init.SpriteID] as Sprite).InitAction = init.Actions;
_initOrder.Add(init.SpriteID);
}
else if (tag is DefineButtonCxFormTag)
{
var cxf = tag as DefineButtonCxFormTag;
(_characters[cxf.CharacterID] as ButtonInfo).SetCxForm(cxf.CxForm);
}
#region Not implemented tags
/*
else if (tag is DefineEditTextTag) { }
*/
// else if (tag is SetTabIndexTag) { }
// else if (tag is DefineScalingGridTag) { }
else
base.UnhandledTag(tag, services);
#endregion
#region Unsupported tags
//TODO: Tags not yet implemented or unsupported
//DefineFontNameTag
//{14, "DefineSound"},
//{17, "DefineButtonSound"},
//{24, "Protect"},
//{46, "DefineMorphShape"},
//{56, "ExportAssets"},
//{57, "ImportAssets"},
//{58, "EnableDebugger"},
//{60, "DefineVideoStream"},
//{61, "VideoFrame"},
//{64, "EnableDebugger2"},
//{65, "ScriptLimits"},
//{69, "FileAttributes"},
//{71, "ImportAssets2"},
//{73, "DefineFontAlignZones"},
//{74, "CSMTextSettings"},
//{76, "SymbolClass"},
//{77, "Metadata"},
//{84, "DefineMorphShape2"},
//{89, "StartSound2"},
//{91, "DefineFont4"}
#endregion
}
public override void Dispose()
{
foreach (var c in _characters.Values)
c.Dispose();
_characters.Clear();
base.Dispose();
}
public void DumpCharacters(ISystemServices services, bool shapes, bool texts)
{
var dev = services.VectorDevice;
int i = 0;
foreach (var ch in _characters.Where(c => c.Value != null))
{
if (!ch.Value.Bounds.HasValue) continue;
dev.State.ResetDefaultValues();
dev.State.SetAntialiasing(VGAntialiasing.Better);
dev.State.NonScalingStroke = true;
dev.State.MaskingEnabled = false;
dev.State.FillRule = VGFillRule.EvenOdd;
dev.State.ColorTransformationEnabled = true;
dev.State.SetProjection(ch.Value.Bounds.Value.Width, ch.Value.Bounds.Value.Height);
dev.State.PathToSurface.Push(VGMatrix.Translate(-ch.Value.Bounds.Value.Left, -ch.Value.Bounds.Value.Top));
using (var surface = dev.CreateSurface(ch.Value.Bounds.Value.Width / 10, ch.Value.Bounds.Value.Height / 10, Microsoft.Xna.Framework.Graphics.SurfaceFormat.Color))
{
switch (ch.Value.Type)
{
case CharacterType.Shape:
if (shapes)
{
var shape = ch.Value as Shape;
using (var context = dev.BeginRendering(surface, new Movie.DisplayState(), true))
shape.Draw(context);
using (var fs = new System.IO.FileStream("Shape_" + ch.Key + ".tga", System.IO.FileMode.Create))
XnaVG.Loaders.TgaImage.SaveAsTga(fs, surface.Target);
}
break;
case CharacterType.Text:
if (texts)
{
var text = ch.Value as Text;
using (var context = dev.BeginRendering(surface, new Movie.DisplayState(), true))
text.Draw(context);
using (var fs = new System.IO.FileStream("Text_" + ch.Key + ".tga", System.IO.FileMode.Create))
XnaVG.Loaders.TgaImage.SaveAsTga(fs, surface.Target);
}
break;
}
}
i++;
Console.WriteLine(i + " / " + _characters.Count);
}
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using Gallio.VisualStudio.Tip.Resources;
using Microsoft.VisualStudio.TestTools.Common;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TestTools.Common.Xml;
namespace Gallio.VisualStudio.Tip
{
/// <summary>
/// Represents a Gallio test element.
/// </summary>
/// <remarks>
/// Be VERY careful not to refer to any Gallio types that are not
/// in the Tip Proxy assembly. They are not in the GAC, consequently Visual
/// Studio may be unable to load them when it needs to pass the test element instance
/// across a remoting channel.
/// </remarks>
[Serializable]
[Guid(Guids.GallioTestTypeGuidString)]
public sealed class GallioTestElement : TestElement
{
private const string GallioTestIdKey = "Gallio.TestId";
private const string AssemblyNameKey = "Gallio.AssemblyName";
private const string NamespaceNameKey = "Gallio.NamespaceName";
private const string TypeNameKey = "Gallio.TypeName";
private const string MemberNameKey = "Gallio.MemberName";
private const string ParameterNameKey = "Gallio.ParameterName";
private const string PathKey = "Gallio.Path";
private const string LineKey = "Gallio.Line";
private const string ColumnKey = "Gallio.Column";
[PersistenceElementName("gallioTestId")]
private string gallioTestId;
[PersistenceElementName("assemblyName")]
private string assemblyName;
[PersistenceElementName("namespaceName")]
private string namespaceName;
[PersistenceElementName("typeName")]
private string typeName;
[PersistenceElementName("memberName")]
private string memberName;
[PersistenceElementName("parameterName")]
private string parameterName;
[PersistenceElementName("path")]
private string path;
[PersistenceElementName("line")]
private int line;
[PersistenceElementName("column")]
private int column;
public GallioTestElement(string id, string name, string description, string assemblyPath)
: base(GenerateTestId(id), name, description, assemblyPath)
{
gallioTestId = id;
}
public GallioTestElement(GallioTestElement element)
: base(element)
{
gallioTestId = element.gallioTestId;
assemblyName = element.assemblyName;
namespaceName = element.namespaceName;
typeName = element.typeName;
memberName = element.memberName;
parameterName = element.parameterName;
path = element.path;
line = element.line;
column = element.column;
}
private GallioTestElement(SerializationInfo info, StreamingContext context)
: base(info, context)
{
gallioTestId = info.GetString(GallioTestIdKey);
assemblyName = info.GetString(AssemblyNameKey);
namespaceName = info.GetString(NamespaceNameKey);
typeName = info.GetString(TypeNameKey);
memberName = info.GetString(MemberNameKey);
parameterName = info.GetString(ParameterNameKey);
path = info.GetString(PathKey);
line = info.GetInt32(LineKey);
column = info.GetInt32(ColumnKey);
}
public override object Clone()
{
return new GallioTestElement(this);
}
public string AssemblyPath
{
get { return Storage; }
}
public string GallioTestId
{
get { return gallioTestId; }
}
public override string HumanReadableId
{
get { return Name; }
}
public override string Adapter
{
get { return typeof(GallioTestAdapterProxy).AssemblyQualifiedName; }
}
public override bool CanBeAggregated
{
get { return false; }
}
public override bool IsLoadTestCandidate
{
get { return false; }
}
public override string ControllerPlugin
{
get { return null; }
}
public override bool ReadOnly
{
get { return false; }
set { throw new NotSupportedException(); }
}
public override TestType TestType
{
get { return Guids.GallioTestType; }
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(GallioTestIdKey, gallioTestId);
info.AddValue(AssemblyNameKey, assemblyName);
info.AddValue(NamespaceNameKey, namespaceName);
info.AddValue(TypeNameKey, typeName);
info.AddValue(MemberNameKey, memberName);
info.AddValue(ParameterNameKey, parameterName);
info.AddValue(PathKey, path);
info.AddValue(LineKey, line);
info.AddValue(ColumnKey, column);
}
public override void Load(XmlElement element, XmlTestStoreParameters parameters)
{
base.Load(element, parameters);
gallioTestId = XmlPersistenceUtils.LoadFromAttribute(element, GallioTestIdKey);
assemblyName = XmlPersistenceUtils.LoadFromAttribute(element, AssemblyNameKey);
namespaceName = XmlPersistenceUtils.LoadFromAttribute(element, NamespaceNameKey);
typeName = XmlPersistenceUtils.LoadFromAttribute(element, TypeNameKey);
memberName = XmlPersistenceUtils.LoadFromAttribute(element, MemberNameKey);
parameterName = XmlPersistenceUtils.LoadFromAttribute(element, ParameterNameKey);
path = XmlPersistenceUtils.LoadFromAttribute(element, PathKey);
line = Convert.ToInt32(XmlPersistenceUtils.LoadFromAttribute(element, LineKey), CultureInfo.InvariantCulture);
column = Convert.ToInt32(XmlPersistenceUtils.LoadFromAttribute(element, ColumnKey), CultureInfo.InvariantCulture);
}
public override void Save(XmlElement element, XmlTestStoreParameters parameters)
{
base.Save(element, parameters);
XmlPersistenceUtils.SaveToAttribute(element, GallioTestIdKey, gallioTestId);
XmlPersistenceUtils.SaveToAttribute(element, AssemblyNameKey, assemblyName);
XmlPersistenceUtils.SaveToAttribute(element, NamespaceNameKey, namespaceName);
XmlPersistenceUtils.SaveToAttribute(element, TypeNameKey, typeName);
XmlPersistenceUtils.SaveToAttribute(element, MemberNameKey, memberName);
XmlPersistenceUtils.SaveToAttribute(element, ParameterNameKey, parameterName);
XmlPersistenceUtils.SaveToAttribute(element, PathKey, path);
XmlPersistenceUtils.SaveToAttribute(element, LineKey, line.ToString(CultureInfo.InvariantCulture));
XmlPersistenceUtils.SaveToAttribute(element, ColumnKey, column.ToString(CultureInfo.InvariantCulture));
}
[PropertyWindow]
[UserVisibleProperty("{2b5a8f49-d24c-4296-8b24-c96c42b707eb}")]
[TestCaseManagementDisplayName(typeof(VSPackage), VSPackageResourceIds.AssemblyNamePropertyNameKey)]
[LocalizedDescription(typeof(VSPackage), VSPackageResourceIds.AssemblyNamePropertyDescriptionKey)]
[GroupingProperty]
//[HelpKeyword("key")]
public string AssemblyName
{
get { return assemblyName; }
}
[PropertyWindow]
[UserVisibleProperty("{a6c1dfdb-bb98-4e3b-9bb5-523e4550e82f}")]
[TestCaseManagementDisplayName(typeof(VSPackage), VSPackageResourceIds.TypeNamePropertyNameKey)]
[LocalizedDescription(typeof(VSPackage), VSPackageResourceIds.TypeNamePropertyDescriptionKey)]
[GroupingProperty]
//[HelpKeyword("key")]
public string TypeName
{
get { return typeName; }
}
[PropertyWindow]
[UserVisibleProperty("{81728549-1eb7-4df1-9ce6-7f9836c9581f}")]
[TestCaseManagementDisplayName(typeof(VSPackage), VSPackageResourceIds.MemberNamePropertyNameKey)]
[LocalizedDescription(typeof(VSPackage), VSPackageResourceIds.MemberNamePropertyDescriptionKey)]
[GroupingProperty]
//[HelpKeyword("key")]
public string MemberName
{
get { return memberName; }
}
[PropertyWindow]
[UserVisibleProperty("{36ee7063-fa7f-4ae2-87f5-b93d69ec1657}")]
[TestCaseManagementDisplayName(typeof(VSPackage), VSPackageResourceIds.LocationPropertyNameKey)]
[LocalizedDescription(typeof(VSPackage), VSPackageResourceIds.LocationPropertyDescriptionKey)]
[GroupingProperty]
//[HelpKeyword("key")]
public string CodeLocation
{
get
{
if (line != 0)
{
if (column != 0)
return String.Format("{0}({1},{2})", path, line, column);
return String.Format("{0}({1})", path, line);
}
return path ?? "(unknown)";
}
}
public string Path
{
get { return path; }
}
public int Line
{
get { return line; }
}
public int Column
{
get { return column; }
}
public void SetCodeReference(string assemblyName, string namespaceName, string typeName, string memberName, string parameterName)
{
this.assemblyName = assemblyName;
this.namespaceName = namespaceName;
this.typeName = typeName;
this.memberName = memberName;
this.parameterName = parameterName;
}
public void SetCodeLocation(string path, int line, int column)
{
this.path = path;
this.line = line;
this.column = column;
}
private static TestId GenerateTestId(string testId)
{
Guid guid = new Guid(Encoding.ASCII.GetBytes(testId.PadRight(16)));
return new TestId(guid);
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 Outercurve Foundation 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.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace WebsitePanel.Portal
{
public partial class ContactDetails : WebsitePanelControlBase
{
private string companyName;
public string CompanyName
{
get { return txtCompanyName.Text; }
set { companyName = value; }
}
private string address;
public string Address
{
get { return txtAddress.Text; }
set { address = value; }
}
private string country;
public string Country
{
get
{
return ddlCountry.SelectedItem.Value;
}
set
{
country = value;
}
}
private string city;
public string City
{
get { return txtCity.Text; }
set { city = value; }
}
private string zip;
public string Zip
{
get { return txtZip.Text; }
set { zip = value; }
}
private string primaryPhone;
public string PrimaryPhone
{
get { return txtPrimaryPhone.Text; }
set { primaryPhone = value; }
}
private string secondaryPhone;
public string SecondaryPhone
{
get { return txtSecondaryPhone.Text; }
set { secondaryPhone = value; }
}
private string state;
public string State
{
get
{
if (ddlStates.Visible)
return ddlStates.SelectedItem.Text;
else
return txtState.Text;
}
set
{
state = value;
}
}
private string fax;
public string Fax
{
get { return txtFax.Text; }
set { fax = value; }
}
private string messengerId;
public string MessengerId
{
get { return txtMessengerId.Text; }
set { messengerId = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCountries();
BindContact();
}
}
private void BindContact()
{
txtCompanyName.Text = companyName;
txtAddress.Text = address;
txtCity.Text = city;
SetCountry(country);
BindStates();
SetState(state);
txtZip.Text = zip;
txtPrimaryPhone.Text = primaryPhone;
txtSecondaryPhone.Text = secondaryPhone;
txtFax.Text = fax;
txtMessengerId.Text = messengerId;
}
private void BindCountries()
{
/*DotNetNuke.Common.Lists.ListController lists = new DotNetNuke.Common.Lists.ListController();
DotNetNuke.Common.Lists.ListEntryInfoCollection countries = lists.GetListEntryInfoCollection("Country");*/
//ddlCountry.DataSource = countries;
/*ddlCountry.DataSource = new object();
ddlCountry.DataBind();*/
PortalUtils.LoadCountriesDropDownList(ddlCountry, null);
ddlCountry.Items.Insert(0, new ListItem("<Not specified>", ""));
}
private void SetCountry(string val)
{
SetDropdown(ddlCountry, val);
}
private void SetState(string val)
{
if (ddlStates.Visible)
SetDropdown(ddlStates, val);
else
txtState.Text = val;
}
private void SetDropdown(DropDownList dropdown, string val)
{
dropdown.SelectedItem.Selected = false;
ListItem item = dropdown.Items.FindByValue(val);
if (item == null)
item = dropdown.Items.FindByText(val);
if (item != null)
item.Selected = true;
}
private void BindStates()
{
ddlStates.Visible = false;
txtState.Visible = true;
if (ddlCountry.SelectedValue != "")
{
/*DotNetNuke.Common.Lists.ListController lists = new DotNetNuke.Common.Lists.ListController();
DotNetNuke.Common.Lists.ListEntryInfoCollection states = lists.GetListEntryInfoCollection("Region", "", "Country." + ddlCountry.SelectedValue);
if (states.Count > 0)
{
ddlStates.DataSource = states;
ddlStates.DataBind();
ddlStates.Items.Insert(0, new ListItem("<Not specified>", ""));
ddlStates.Visible = true;
txtState.Visible = false;
}*/
PortalUtils.LoadStatesDropDownList(ddlStates, ddlCountry.SelectedValue);
if (ddlStates.Items.Count > 0)
{
ddlStates.Items.Insert(0, new ListItem("<Not specified>", ""));
ddlStates.Visible = true;
txtState.Visible = false;
}
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
BindStates();
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Xsl;
using Palaso.Lift.Merging.XmlDiff;
using Palaso.Lift.Validation;
namespace Palaso.Lift
{
/// <summary>
/// This contains various static utility methods related to Lift file processing.
/// </summary>
public class Utilities
{
/// <summary>
/// Add guids
/// </summary>
/// <param name="inputPath"></param>
/// <returns>path to a processed version</returns>
static public string ProcessLiftForLaterMerging(string inputPath)
{
if (inputPath == null)
{
throw new ArgumentNullException("inputPath");
}
string outputOfPassOne = Path.GetTempFileName();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineOnAttributes = true;//ugly, but great for merging with revision control systems
// nb: don't use XmlTextWriter.Create, that's broken. Ignores the indent setting
using (XmlWriter writer = XmlWriter.Create(outputOfPassOne /*Console.Out*/, settings))
{
using (XmlReader reader = XmlReader.Create(inputPath))
{
//bool elementWasReplaced = false;
while (!reader.EOF)
{
ProcessNode(reader, writer);
}
}
}
XslCompiledTransform transform = new XslCompiledTransform();
using (Stream canonicalizeXsltStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Palaso.Lift.canonicalizeLift.xsl"))
{
if (canonicalizeXsltStream != null)
{
using (XmlReader xsltReader = XmlReader.Create(canonicalizeXsltStream))
{
transform.Load(xsltReader);
xsltReader.Close();
}
canonicalizeXsltStream.Close();
}
}
string outputOfPassTwo = Path.GetTempFileName();
using (Stream output = File.Create(outputOfPassTwo))
{
transform.Transform(outputOfPassOne, new XsltArgumentList(), output);
}
TempFileCollection tempfiles = transform.TemporaryFiles;
if (tempfiles != null) // tempfiles will be null when debugging is not enabled
{
tempfiles.Delete();
}
File.Delete(outputOfPassOne);
return outputOfPassTwo;
}
private static void ProcessNode(XmlReader reader, XmlWriter writer)
{
switch (reader.NodeType)
{
case XmlNodeType.EndElement:
case XmlNodeType.Element:
ProcessElement(reader, writer);
break;
default:
WriteShallowNode(reader, writer);
break;
}
}
private static void ProcessElement(XmlReader reader, XmlWriter writer)
{
if (reader.Name == "entry")
{
string guid = reader.GetAttribute("guid");
if (String.IsNullOrEmpty(guid))
{
guid = Guid.NewGuid().ToString();
writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteAttributes(reader, true);
writer.WriteAttributeString("guid", guid);
string s = reader.ReadInnerXml();//this seems to be enough to get the reader to the next element
writer.WriteRaw(s);
writer.WriteEndElement();
}
else
{
writer.WriteNode(reader, true);
}
}
else
{
WriteShallowNode(reader, writer);
}
}
///<summary>
/// Create an empty Lift file, unless a file of the given name exists already and
/// doOverwriteIfExists is false.
///</summary>
static public void CreateEmptyLiftFile(string path, string producerString, bool doOverwriteIfExists)
{
if (File.Exists(path))
{
if (doOverwriteIfExists)
{
File.Delete(path);
}
else
{
return;
}
}
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineOnAttributes = true;//ugly, but great for merging with revision control systems
using (XmlWriter writer = XmlWriter.Create(path, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("lift");
writer.WriteAttributeString("version", Validator.LiftVersion);
writer.WriteAttributeString("producer", producerString);
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
//came from a blog somewhere
static internal void WriteShallowNode(XmlReader reader, XmlWriter writer)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (writer == null)
{
throw new ArgumentNullException("writer");
}
switch (reader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteAttributes(reader, true);
if (reader.IsEmptyElement)
{
writer.WriteEndElement();
}
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
writer.WriteWhitespace(reader.Value);
break;
case XmlNodeType.CDATA:
writer.WriteCData(reader.Value);
break;
case XmlNodeType.EntityReference:
writer.WriteEntityRef(reader.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.DocumentType:
writer.WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"),
reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
reader.Read();
}
/// <summary>
/// Check wether the two XML elements (given as strings) are equal.
/// </summary>
public static bool AreXmlElementsEqual(string ours, string theirs)
{
StringReader osr = new StringReader(ours);
XmlReader or = XmlReader.Create(osr);
XmlDocument od = new XmlDocument();
XmlNode on = od.ReadNode(or);
if (on != null)
on.Normalize();
StringReader tsr = new StringReader(theirs);
XmlReader tr = XmlReader.Create(tsr);
XmlDocument td = new XmlDocument();
XmlNode tn = td.ReadNode(tr);
if (tn != null)
{
tn.Normalize();//doesn't do much
// StringBuilder builder = new StringBuilder();
// XmlWriter w = XmlWriter.Create(builder);
return AreXmlElementsEqual(on, tn);
}
return false;
}
/// <summary>
/// Check whether the two XML elements are equal.
/// </summary>
public static bool AreXmlElementsEqual(XmlNode ours, XmlNode theirs)
{
if (ours.NodeType == XmlNodeType.Text)
{
if (ours.NodeType != XmlNodeType.Text)
{
return false;
}
bool oursIsEmpty = (ours.InnerText.Trim() == string.Empty);
bool theirsIsEmpty = (theirs.InnerText.Trim() == string.Empty);
if(oursIsEmpty != theirsIsEmpty)
{
return false;
}
return ours.InnerText.Trim() == theirs.InnerText.Trim();
}
// DiffConfiguration config = new DiffConfiguration(WhitespaceHandling.None);
var diff = new XmlDiff(new XmlInput(ours.OuterXml), new XmlInput(theirs.OuterXml));//, config);
DiffResult d = diff.Compare();
return (d == null || d.Difference == null || !d.Difference.HasMajorDifference);
}
/// <summary>
/// Get an attribute value from the XML element, or throw an exception if it isn't there.
/// </summary>
public static string GetStringAttribute(XmlNode form, string attr)
{
try
{
if (form.Attributes != null)
return form.Attributes[attr].Value;
}
catch(NullReferenceException)
{
}
throw new LiftFormatException(string.Format("Expected a {0} attribute on {1}.", attr, form.OuterXml));
}
/// <summary>
/// Get an attribute value from the XML element, or return null if it isn't there.
/// </summary>
public static string GetOptionalAttributeString(XmlNode xmlNode, string attributeName)
{
if (xmlNode.Attributes == null)
return null;
XmlAttribute attr = xmlNode.Attributes[attributeName];
if (attr == null)
return null;
return attr.Value;
}
/// <summary>
/// Make the string safe for writing in an XML attribute value.
/// </summary>
public static string MakeSafeXmlAttribute(string sInput)
{
string sOutput = sInput;
if (sOutput != null && sOutput.Length != 0)
{
sOutput = sOutput.Replace("&", "&");
sOutput = sOutput.Replace("\"", """);
sOutput = sOutput.Replace("'", "'");
sOutput = sOutput.Replace("<", "<");
sOutput = sOutput.Replace(">", ">");
}
return sOutput;
}
/// <summary>
/// Parse a string into a new XmlNode that belongs to the same XmlDocument as
/// nodeMaker (which may be either the XmlDocument or a child XmlNode).
/// </summary>
public static XmlNode GetDocumentNodeFromRawXml(string outerXml, XmlNode nodeMaker)
{
if(string.IsNullOrEmpty(outerXml))
throw new ArgumentException("string outerXml is null or empty");
XmlDocument doc = nodeMaker as XmlDocument;
if(doc == null)
doc = nodeMaker.OwnerDocument;
if (doc == null)
throw new ArgumentException("Could not get XmlDocument from XmlNode nodeMaker");
using (StringReader sr = new StringReader(outerXml))
{
using (XmlReader r = XmlReader.Create(sr))
{
r.Read();
return doc.ReadNode(r);
}
}
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using System.ComponentModel;
using System.Text.RegularExpressions;
using Scintilla;
using Scintilla.Forms;
using Scintilla.Enums;
using Zeus;
using Zeus.Templates;
using MyGeneration.AutoCompletion;
namespace MyGeneration
{
public interface IEditControl
{
string Mode { get; }
string Language { get; }
string Text { get; set; }
void GrabFocus();
void Activate();
}
/// <summary>
/// Summary description for JScriptScintillaControl.
/// </summary>
public class ZeusScintillaControl : ScintillaControl, IEditControl, IScintillaNet
{
private const int WM_KEYDOWN = 0x0100;
private const int DEFAULT_CODE_PAGE = 65001;
private string _language;
private string _mode;
private string _fontFamilyOverride;
private int _codePageOverride = DEFAULT_CODE_PAGE;
private static string LastSearchTextStatic = string.Empty;
private static bool LastSearchIsCaseSensitiveStatic = true;
private static bool LastSearchIsRegexStatic = false;
private Hashtable ignoredKeys = new Hashtable();
public static FindForm FindDialog = new FindForm();
public static ReplaceForm ReplaceDialog = new ReplaceForm();
public static ScintillaConfigureDelegate StaticConfigure = null;
public ZeusScintillaControl() : base()
{
Scintilla.Forms.SearchHelper.Translations.MessageBoxTitle = "MyGeneration";
this.SmartIndentType = SmartIndent.Simple;
this.GotFocus += new EventHandler(ZeusScintillaControl_GotFocus);
this.Configure = StaticConfigure;
this.CharAdded += new EventHandler<CharAddedEventArgs>(ZeusScintillaControl_CharAdded);
this.AllowDrop = true;
this.IsAutoCIgnoreCase = true;
}
private void ZeusScintillaControl_CharAdded(object sender, CharAddedEventArgs e)
{
this.Cursor_ = (int)Scintilla.Enums.CursorShape.Wait;
AutoCompleteHelper.CharAdded(this, e.Ch);
this.Cursor_ = (int)Scintilla.Enums.CursorShape.Normal;
}
void ZeusScintillaControl_GotFocus(object sender, EventArgs e)
{
InitializeFindReplace();
}
public void InitializeFindReplace()
{
FindDialog.Initialize(this);
ReplaceDialog.Initialize(this);
}
public string FontFamilyOverride
{
get
{
return this._fontFamilyOverride;
}
set
{
if (value != _fontFamilyOverride)
{
_fontFamilyOverride = value;
UpdateCurrentStyles();
}
}
}
public int CodePageOverride
{
get
{
return this._codePageOverride;
}
set
{
int tmp = (value == -1) ? DEFAULT_CODE_PAGE : value;
if (tmp != _codePageOverride)
{
_codePageOverride = tmp;
UpdateCurrentStyles();
}
}
}
public string Mode
{
get
{
return this._mode;
}
}
public string Language
{
get
{
return this._language;
}
}
public string LastSearchText { get { return ZeusScintillaControl.LastSearchTextStatic; } }
public bool LastSearchIsCaseSensitive { get { return ZeusScintillaControl.LastSearchIsCaseSensitiveStatic; } }
public bool LastSearchIsRegex { get { return ZeusScintillaControl.LastSearchIsRegexStatic; } }
public override string Text
{
get
{
return base.Text;
}
set
{
if ((value != null) && (value.Length > 0))
base.Text = value;
}
}
public void SpecialRefresh()
{
UpdateCurrentStyles();
}
private void UpdateCurrentStyles()
{
UpdateModeAndLanguage(_language, _mode);
}
public void UpdateModeAndLanguage(string language, string mode)
{
this.StyleClearAll();
this.StyleResetDefault();
this.ClearDocumentStyle();
this._language = language;
this._mode = mode;
switch (this._language)
{
case ZeusConstants.Languages.VB:
case ZeusConstants.Languages.VBNET:
if (this.Mode == ZeusConstants.Modes.MARKUP) this.ConfigureControlForTaggedVBNet();
else this.ConfigureControlForVBNet();
break;
case ZeusConstants.Languages.JSCRIPT:
case ZeusConstants.Languages.JAVA:
if (this.Mode == ZeusConstants.Modes.MARKUP) this.ConfigureControlForTaggedJScript();
else this.ConfigureControlForJScript();
break;
case ZeusConstants.Languages.VBSCRIPT:
if (this.Mode == ZeusConstants.Modes.MARKUP) this.ConfigureControlForTaggedVBScript();
else this.ConfigureControlForVBScript();
break;
case ZeusConstants.Languages.CSHARP:
if (this.Mode == ZeusConstants.Modes.MARKUP) this.ConfigureControlForTaggedCSharp();
else this.ConfigureControlForCSharp();
break;
case ZeusConstants.Languages.TSQL:
this.ConfigureControlForMSSQL();
break;
case ZeusConstants.Languages.SQL:
case ZeusConstants.Languages.PLSQL:
this.ConfigureControlForSQL();
break;
case ZeusConstants.Languages.JETSQL:
this.ConfigureControlForJetSQL();
break;
case ZeusConstants.Languages.PHP:
this.ConfigureControlForPHP();
break;
default:
this.ConfigureControlForUnsupported();
break;
}
DefaultSettings settings = DefaultSettings.Instance;
this.TabWidth = settings.Tabs;
if (!string.IsNullOrEmpty(this.FontFamilyOverride))
{
Font f = new Font(this.FontFamilyOverride, this.Font.Size);
for (int i = 0; i < 128; i++)
{
this.StyleSetFont(i, f.Name);
}
}
this.CodePage = this.CodePageOverride;
this.Colorize(0, -1);
//this.Colourise(0, -1);
this.Refresh();
}
public void Activate()
{
this.InitializeFindReplace();
this.GrabFocus();
this.Focus();
}
#region Base Scintilla Settings
protected void ConfigureBaseSettings()
{
//SC_CP_UTF8 (65001)
this.CodePage = this.CodePageOverride;
this.Anchor_ = 0;
// this.BackSpaceUnIndents = false;
// this.BufferedDraw = true;
// this.CaretForeground = 0;
// this.CaretLineBackground = 65535;
// this.CaretLineVisible = false;
this.CaretPeriod = 500;
this.CaretWidth = 1;
//this.Configuration = null;
this.ConfigurationLanguage = "";
this.ControlCharSymbol = 0;
this.CurrentPos = 0;
this.Cursor_ = -1;
this.Dock = System.Windows.Forms.DockStyle.Fill;
//this.EdgeColour = 12632256;
this.EdgeColor = 12632256;
this.EdgeColumn = 0;
this.EdgeMode = 0;
// this.EndAtLastLine = true;
// this.EOLCharactersVisible = false;
this.EndOfLineMode = EndOfLine.Crlf;
// this.focus = false;
this.HighlightGuide = 0;
// this.HorizontalScrollBarVisible = true;
this.Indent = 0;
// this.IndentationGuidesVisible = false;
this.LayoutCache = 1;
this.Lexer = 0;
// this.LexerLanguage = null;
this.Location = new System.Drawing.Point(0, 0);
this.MarginLeft = 1;
this.MarginRight = 1;
this.ModEventMask = 3959;
// this.MouseDownCaptures = true;
this.MouseDwellTime = 10000000;
this.Name = "scintillaControl";
// this.Overtype = false;
this.PrintColorMode = 0;
this.PrintMagnification = 0;
this.PrintWrapMode = 1;
// this.ReadOnly = false;
this.ScrollWidth = 2000;
this.SearchFlags = 0;
this.SelectionEnd = 0;
this.SelectionStart = 0;
this.Size = new System.Drawing.Size(736, 721);
this.Status = 0;
this.StyleBits = 5;
// this.TabIndents = true;
this.TabIndex = 0;
this.TabWidth = 8;
this.TargetEnd = 0;
this.TargetStart = 0;
// this.UsePalette = false;
// this.UseTabs = true;
// this.VerticalScrollBarVisible = true;
// this.WhitespaceVisibleState = 0;
this.WrapMode = 0;
this.XOffset = 0;
this.Zoom = 0;
this.Visible = true;
this.Width = 200;
this.Height = 200;
this.Dock = DockStyle.Fill;
// this.TabIndents = true;
this.SetSelectionBackground(true, 65535); // yellow
this.SetSelectionForeground(true, 0);
}
#endregion
#region Default Control Setup
protected void ConfigureControlForUnsupported()
{
this.ConfigureBaseSettings();
}
#endregion
#region C# Setup
protected void ConfigureControlForCSharp()
{
this.ConfigureBaseSettings();
this.ConfigurationLanguage = "C#";
//this.LegacyConfigurationLanguage = "C#";
}
#endregion
#region VBNet Setup
protected void ConfigureControlForVBNet()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "VB.Net";
this.CaretFore = 0xffffff;
}
#endregion
#region PHP Setup
protected void ConfigureControlForPHP()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "PHP";
}
#endregion
#region JScript Setup
protected void ConfigureControlForJScript()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "JScript";
}
#endregion
#region VBScript Setup
protected void ConfigureControlForVBScript()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "VBScript";
}
#endregion
#region MSSQL Setup
protected void ConfigureControlForMSSQL()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "MSSQL";
}
#endregion
#region SQL Setup
protected void ConfigureControlForSQL()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "SQL";
}
#endregion
#region JetSQL Setup
protected void ConfigureControlForJetSQL()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "JetSQL";
}
#endregion
#region Tagged C# Setup
protected void ConfigureControlForTaggedCSharp()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "TaggedC#";
}
#endregion
#region Tagged JScript Setup
protected void ConfigureControlForTaggedJScript()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "TaggedJScript";
}
#endregion
#region Tagged VBScript Setup
protected void ConfigureControlForTaggedVBScript()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "TaggedVBScript";
this.CaretFore = 0x000000;
}
#endregion
#region Tagged VBNet Setup
protected void ConfigureControlForTaggedVBNet()
{
this.ConfigureBaseSettings();
//this.LegacyConfiguration = MDIParent.scintillaXmlConfig.scintilla;
this.ConfigurationLanguage = "TaggedVB.Net";
this.CaretFore = 0x000000;
}
#endregion
}
}
| |
using System;
using Google.GData.Apps.Groups;
using Google.GData.Client;
using Google.GData.Extensions.Apps;
namespace Google.GData.Apps
{
/// <summary>
/// The AppsService class provides a simpler interface
/// for executing common Google Apps provisioning
/// requests.
/// </summary>
public class AppsService
{
private readonly NicknameService nicknameService;
private readonly UserService userAccountService;
/// <summary>
/// Constructs an AppsService with the specified credentials
/// for accessing provisioning feeds on the specified domain.
/// </summary>
/// <param name="domain">the domain to access</param>
/// <param name="adminEmailAddress">the administrator's email address</param>
/// <param name="adminPassword">the administrator's password</param>
public AppsService(string domain, string adminEmailAddress, string adminPassword)
{
Domain = domain;
ApplicationName = "apps-" + domain;
nicknameService = new NicknameService(ApplicationName);
nicknameService.SetUserCredentials(adminEmailAddress, adminPassword);
userAccountService = new UserService(ApplicationName);
userAccountService.SetUserCredentials(adminEmailAddress, adminPassword);
Groups = new GroupsService(domain, ApplicationName);
Groups.SetUserCredentials(adminEmailAddress, adminPassword);
}
/// <summary>
/// Constructs an AppsService with the specified Authentication Token
/// for accessing provisioning feeds on the specified domain.
/// </summary>
/// <param name="domain">the domain to access</param>
/// <param name="authenticationToken">the administrator's Authentication Token</param>
public AppsService(string domain, string authenticationToken)
{
Domain = domain;
ApplicationName = "apps-" + domain;
nicknameService = new NicknameService(ApplicationName);
nicknameService.SetAuthenticationToken(authenticationToken);
userAccountService = new UserService(ApplicationName);
userAccountService.SetAuthenticationToken(authenticationToken);
Groups = new GroupsService(domain, ApplicationName);
Groups.SetAuthenticationToken(authenticationToken);
}
/// <summary>
/// ApplicationName property accessor
/// </summary>
public string ApplicationName { get; set; }
/// <summary>
/// Domain property accessor
/// </summary>
public string Domain { get; set; }
/// <summary>
/// GroupsService accessor
/// </summary>
public GroupsService Groups { get; }
/// <summary>indicates if the connection should be kept alive,
/// default is true
/// </summary>
/// <param name="keepAlive">bool to set if the connection should be keptalive</param>
public void KeepAlive(bool keepAlive)
{
((GDataRequestFactory) nicknameService.RequestFactory).KeepAlive = keepAlive;
((GDataRequestFactory) userAccountService.RequestFactory).KeepAlive = keepAlive;
((GDataRequestFactory) Groups.RequestFactory).KeepAlive = keepAlive;
}
/// <summary>
/// Generates a new Authentication Token for AppsService
/// with the specified credentials for accessing provisioning feeds on the specified domain.
/// </summary>
/// <param name="domain">the domain to access</param>
/// <param name="adminEmailAddress">the administrator's email address</param>
/// <param name="adminPassword">the administrator's password</param>
/// <returns>the newly generated authentication token</returns>
public static string GetNewAuthenticationToken(string domain, string adminEmailAddress, string adminPassword)
{
Service service = new Service(AppsNameTable.GAppsService, "apps-" + domain);
service.SetUserCredentials(adminEmailAddress, adminPassword);
return service.QueryClientLoginToken();
}
/// <summary>
/// Creates a new user account.
/// </summary>
/// <param name="username">the account's username</param>
/// <param name="givenName">the user's first (given) name</param>
/// <param name="familyName">the user's last (family) name</param>
/// <param name="password">the account's password</param>
/// <returns>the newly created UserEntry</returns>
public UserEntry CreateUser(string username,
string givenName,
string familyName,
string password)
{
UserEntry entry = new UserEntry();
entry.Name = new NameElement(familyName, givenName);
entry.Login = new LoginElement(username, password, false, false);
UserQuery query = new UserQuery(Domain);
return userAccountService.Insert(query.Uri, entry);
}
/// <summary>
/// Creates a new user account.
/// </summary>
/// <param name="username">the account's username</param>
/// <param name="givenName">the user's first (given) name</param>
/// <param name="familyName">the user's last (family) name</param>
/// <param name="password">the account's password</param>
/// <param name="quotaLimitInMb">the account's quota, in MB</param>
/// <returns>the newly created UserEntry</returns>
public UserEntry CreateUser(string username,
string givenName,
string familyName,
string password,
int quotaLimitInMb)
{
UserEntry entry = new UserEntry();
entry.Name = new NameElement(familyName, givenName);
entry.Login = new LoginElement(username, password, false, false);
entry.Quota = new QuotaElement(quotaLimitInMb);
UserQuery query = new UserQuery(Domain);
return userAccountService.Insert(query.Uri, entry);
}
/// <summary>
/// Creates a new user account.
/// </summary>
/// <param name="username">the account's username</param>
/// <param name="givenName">the user's first (given) name</param>
/// <param name="familyName">the user's last (family) name</param>
/// <param name="password">the account's password</param>
/// <param name="passwordHashFunction">the name of the hash function to hash the password</param>
/// <returns>the newly created UserEntry</returns>
public UserEntry CreateUser(string username,
string givenName,
string familyName,
string password,
string passwordHashFunction)
{
UserEntry entry = new UserEntry();
entry.Name = new NameElement(familyName, givenName);
entry.Login = new LoginElement(username, password, false, false, passwordHashFunction);
UserQuery query = new UserQuery(Domain);
return userAccountService.Insert(query.Uri, entry);
}
/// <summary>
/// Creates a new user account.
/// </summary>
/// <param name="username">the account's username</param>
/// <param name="givenName">the user's first (given) name</param>
/// <param name="familyName">the user's last (family) name</param>
/// <param name="password">the account's password</param>
/// <param name="passwordHashFunction">the name of the hash function to hash the password</param>
/// <param name="quotaLimitInMb">the account's quota, in MB</param>
/// <returns>the newly created UserEntry</returns>
public UserEntry CreateUser(string username,
string givenName,
string familyName,
string password,
string passwordHashFunction,
int quotaLimitInMb)
{
UserEntry entry = new UserEntry();
entry.Name = new NameElement(familyName, givenName);
entry.Login = new LoginElement(username, password, false, false, passwordHashFunction);
entry.Quota = new QuotaElement(quotaLimitInMb);
UserQuery query = new UserQuery(Domain);
return userAccountService.Insert(query.Uri, entry);
}
/// <summary>
/// Retrieves all user account entries on this domain.
/// </summary>
/// <returns>the feed containing all user account entries</returns>
public UserFeed RetrieveAllUsers()
{
UserQuery query = new UserQuery(Domain);
return userAccountService.Query(query);
}
/// <summary>
/// Retrieves a page of at most 100 users beginning with the
/// specified username. Usernames are ordered case-insensitively
/// by ASCII value.
/// </summary>
/// <param name="startUsername">the first username that should appear
/// in your result set</param>
/// <returns>the feed containing the matching user account entries</returns>
public UserFeed RetrievePageOfUsers(string startUsername)
{
UserQuery query = new UserQuery(Domain);
query.StartUserName = startUsername;
query.RetrieveAllUsers = false;
return userAccountService.Query(query);
}
/// <summary>
/// Retrieves the entry for the specified user.
/// </summary>
/// <param name="username">the username to retrieve</param>
/// <returns>the UserEntry for this user</returns>
public UserEntry RetrieveUser(string username)
{
UserQuery query = new UserQuery(Domain);
query.UserName = username;
UserFeed feed = userAccountService.Query(query);
// It's safe to access Entries[0] here, because the service will
// have already thrown an exception if the username was invalid.
return feed.Entries[0] as UserEntry;
}
/// <summary>
/// Updates the specified user account.
/// </summary>
/// <param name="entry">The updated entry; modified properties
/// can include the user's first name, last name, username and
/// password.</param>
/// <returns>the updated UserEntry</returns>
public UserEntry UpdateUser(UserEntry entry)
{
return entry.Update();
}
/// <summary>
/// the AppsService is an application object holding several
/// real services object. To allow the setting of advanced http properties,
/// proxies and other things, we allow setting the factory class that is used.
///
/// a getter does not make a lot of sense here, as which of the several factories in use
/// are we getting? It also would give the illusion that you could get one object and then
/// modify its settings.
/// </summary>
/// <param name="factory">The factory to use for the AppsService</param>
/// <returns></returns>
public void SetRequestFactory(IGDataRequestFactory factory)
{
if (factory == null)
{
throw new ArgumentNullException("factory", "The factory object should not be NULL");
}
nicknameService.RequestFactory = factory;
userAccountService.RequestFactory = factory;
Groups.RequestFactory = factory;
}
/// <summary>
/// this creates a default AppsService Factory object that can be used to
/// be modified and then set using SetRequestFactory()
/// </summary>
/// <returns></returns>
public IGDataRequestFactory CreateRequestFactory()
{
return new GDataGAuthRequestFactory(AppsNameTable.GAppsService, ApplicationName);
}
/// <summary>
/// Suspends a user account.
/// </summary>
/// <param name="username">the username whose account you wish to suspend</param>
/// <returns>the updated UserEntry</returns>
public UserEntry SuspendUser(string username)
{
UserEntry entry = RetrieveUser(username);
entry.Login.Suspended = true;
return UpdateUser(entry);
}
/// <summary>
/// Restores a user account.
/// </summary>
/// <param name="username">the username whose account you wish to restore</param>
/// <returns>the updated UserEntry</returns>
public UserEntry RestoreUser(string username)
{
UserEntry entry = RetrieveUser(username);
entry.Login.Suspended = false;
return UpdateUser(entry);
}
/// <summary>
/// Adds admin privileges for a user. Note that executing this method
/// on a user who is already an admin has no effect.
/// </summary>
/// <param name="username">the user to make an administrator</param>
/// <returns>the updated UserEntry</returns>
public UserEntry AddAdminPrivilege(string username)
{
UserEntry entry = RetrieveUser(username);
entry.Login.Admin = true;
return UpdateUser(entry);
}
/// <summary>
/// Removes admin privileges for a user. Note that executing this method
/// on a user who is not an admin has no effect.
/// </summary>
/// <param name="username">the user from which to revoke admin privileges</param>
/// <returns>the updated UserEntry</returns>
public UserEntry RemoveAdminPrivilege(string username)
{
UserEntry entry = RetrieveUser(username);
entry.Login.Admin = false;
return UpdateUser(entry);
}
/// <summary>
/// Forces the specified user to change his or her password at the next
/// login.
/// </summary>
/// <param name="username">the user who must change his/her password upon
/// logging in next</param>
/// <returns>the updated UserEntry</returns>
public UserEntry ForceUserToChangePassword(string username)
{
UserEntry entry = RetrieveUser(username);
entry.Login.ChangePasswordAtNextLogin = true;
return UpdateUser(entry);
}
/// <summary>
/// Deletes a user account.
/// </summary>
/// <param name="username">the username whose account you wish to delete</param>
public void DeleteUser(string username)
{
UserQuery query = new UserQuery(Domain);
query.UserName = username;
userAccountService.Delete(query.Uri);
}
/// <summary>
/// Creates a nickname for the specified user.
/// </summary>
/// <param name="username">the user account for which you are creating a nickname</param>
/// <param name="nickname">the nickname for the user account</param>
/// <returns>the newly created NicknameEntry object</returns>
public NicknameEntry CreateNickname(string username, string nickname)
{
NicknameQuery query = new NicknameQuery(Domain);
NicknameEntry entry = new NicknameEntry();
entry.Login = new LoginElement(username);
entry.Nickname = new NicknameElement(nickname);
return nicknameService.Insert(query.Uri, entry);
}
/// <summary>
/// Retrieves all nicknames on this domain.
/// </summary>
/// <returns>the feed containing all nickname entries</returns>
public NicknameFeed RetrieveAllNicknames()
{
NicknameQuery query = new NicknameQuery(Domain);
return nicknameService.Query(query);
}
/// <summary>
/// Retrieves a page of at most 100 nicknames beginning with the
/// specified nickname. Nicknames are ordered case-insensitively
/// by ASCII value.
/// </summary>
/// <param name="startNickname">the first nickname that should appear
/// in your result set</param>
/// <returns>the feed containing the matching nickname entries</returns>
public NicknameFeed RetrievePageOfNicknames(string startNickname)
{
NicknameQuery query = new NicknameQuery(Domain);
query.StartNickname = startNickname;
query.RetrieveAllNicknames = false;
return nicknameService.Query(query);
}
/// <summary>
/// Retrieves all nicknames for the specified user.
/// </summary>
/// <param name="username">the username for which you wish to retrieve nicknames</param>
/// <returns>the feed containing all nickname entries for this user</returns>
public NicknameFeed RetrieveNicknames(string username)
{
NicknameQuery query = new NicknameQuery(Domain);
query.UserName = username;
return nicknameService.Query(query);
}
/// <summary>
/// Retrieves the specified nickname.
/// </summary>
/// <param name="nickname">the nickname to retrieve</param>
/// <returns>the resulting NicknameEntry</returns>
public NicknameEntry RetrieveNickname(string nickname)
{
NicknameQuery query = new NicknameQuery(Domain);
query.Nickname = nickname;
NicknameFeed feed = nicknameService.Query(query);
// It's safe to access Entries[0] here, because the service will
// have already thrown an exception if the nickname was invalid.
return feed.Entries[0] as NicknameEntry;
}
/// <summary>
/// Deletes the specified nickname.
/// </summary>
/// <param name="nickname">the nickname that you wish to delete</param>
public void DeleteNickname(string nickname)
{
NicknameQuery query = new NicknameQuery(Domain);
query.Nickname = nickname;
nicknameService.Delete(query.Uri);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using Thrift.Collections;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift.Test;
namespace Test
{
public class TestClient
{
private class TestParams
{
public int numIterations = 1;
public string host = "localhost";
public int port = 9090;
public string url;
public string pipe;
public bool buffered;
public bool framed;
public string protocol;
public bool encrypted = false;
protected bool _isFirstTransport = true;
public TTransport CreateTransport()
{
if (url == null)
{
// endpoint transport
TTransport trans = null;
if (pipe != null)
trans = new TNamedPipeClientTransport(pipe);
else
{
if (encrypted)
{
string certPath = "../../../../test/keys/client.p12";
X509Certificate cert = new X509Certificate2(certPath, "thrift");
trans = new TTLSSocket(host, port, cert, (o, c, chain, errors) => true);
}
else
{
trans = new TSocket(host, port);
}
}
// layered transport
if (buffered)
trans = new TBufferedTransport(trans);
if (framed)
trans = new TFramedTransport(trans);
if (_isFirstTransport)
{
//ensure proper open/close of transport
trans.Open();
trans.Close();
_isFirstTransport = false;
}
return trans;
}
else
{
return new THttpClient(new Uri(url));
}
}
public TProtocol CreateProtocol(TTransport transport)
{
if (protocol == "compact")
return new TCompactProtocol(transport);
else if (protocol == "json")
return new TJSONProtocol(transport);
else
return new TBinaryProtocol(transport);
}
};
private const int ErrorBaseTypes = 1;
private const int ErrorStructs = 2;
private const int ErrorContainers = 4;
private const int ErrorExceptions = 8;
private const int ErrorUnknown = 64;
private class ClientTest
{
private readonly TTransport transport;
private readonly ThriftTest.Client client;
private readonly int numIterations;
private bool done;
public int ReturnCode { get; set; }
public ClientTest(TestParams param)
{
transport = param.CreateTransport();
client = new ThriftTest.Client(param.CreateProtocol(transport));
numIterations = param.numIterations;
}
public void Execute()
{
if (done)
{
Console.WriteLine("Execute called more than once");
throw new InvalidOperationException();
}
for (int i = 0; i < numIterations; i++)
{
try
{
if (!transport.IsOpen)
transport.Open();
}
catch (TTransportException ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Connect failed: " + ex.Message);
ReturnCode |= ErrorUnknown;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
continue;
}
try
{
ReturnCode |= ExecuteClientTest(client);
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
ReturnCode |= ErrorUnknown;
}
}
try
{
transport.Close();
}
catch(Exception ex)
{
Console.WriteLine("Error while closing transport");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
done = true;
}
}
public static int Execute(string[] args)
{
try
{
TestParams param = new TestParams();
int numThreads = 1;
try
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-u")
{
param.url = args[++i];
}
else if (args[i] == "-n")
{
param.numIterations = Convert.ToInt32(args[++i]);
}
else if (args[i] == "-pipe") // -pipe <name>
{
param.pipe = args[++i];
Console.WriteLine("Using named pipes transport");
}
else if (args[i].Contains("--host="))
{
param.host = args[i].Substring(args[i].IndexOf("=") + 1);
}
else if (args[i].Contains("--port="))
{
param.port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
param.buffered = true;
Console.WriteLine("Using buffered sockets");
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
param.framed = true;
Console.WriteLine("Using framed transport");
}
else if (args[i] == "-t")
{
numThreads = Convert.ToInt32(args[++i]);
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
param.protocol = "compact";
Console.WriteLine("Using compact protocol");
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
param.protocol = "json";
Console.WriteLine("Using JSON protocol");
}
else if (args[i] == "--ssl")
{
param.encrypted = true;
Console.WriteLine("Using encrypted transport");
}
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Error while parsing arguments");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
return ErrorUnknown;
}
var tests = Enumerable.Range(0, numThreads).Select(_ => new ClientTest(param)).ToArray();
//issue tests on separate threads simultaneously
var threads = tests.Select(test => new Thread(test.Execute)).ToArray();
DateTime start = DateTime.Now;
foreach (var t in threads)
t.Start();
foreach (var t in threads)
t.Join();
Console.WriteLine("Total time: " + (DateTime.Now - start));
Console.WriteLine();
return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2);
}
catch (Exception outerEx)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Unexpected error");
Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
return ErrorUnknown;
}
}
public static string BytesToHex(byte[] data) {
return BitConverter.ToString(data).Replace("-", string.Empty);
}
public static byte[] PrepareTestData(bool randomDist)
{
byte[] retval = new byte[0x100];
int initLen = Math.Min(0x100,retval.Length);
// linear distribution, unless random is requested
if (!randomDist) {
for (var i = 0; i < initLen; ++i) {
retval[i] = (byte)i;
}
return retval;
}
// random distribution
for (var i = 0; i < initLen; ++i) {
retval[i] = (byte)0;
}
var rnd = new Random();
for (var i = 1; i < initLen; ++i) {
while( true) {
int nextPos = rnd.Next() % initLen;
if (retval[nextPos] == 0) {
retval[nextPos] = (byte)i;
break;
}
}
}
return retval;
}
public static int ExecuteClientTest(ThriftTest.Client client)
{
int returnCode = 0;
Console.Write("testVoid()");
client.testVoid();
Console.WriteLine(" = void");
Console.Write("testString(\"Test\")");
string s = client.testString("Test");
Console.WriteLine(" = \"" + s + "\"");
if ("Test" != s)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testBool(true)");
bool t = client.testBool((bool)true);
Console.WriteLine(" = " + t);
if (!t)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testBool(false)");
bool f = client.testBool((bool)false);
Console.WriteLine(" = " + f);
if (f)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testByte(1)");
sbyte i8 = client.testByte((sbyte)1);
Console.WriteLine(" = " + i8);
if (1 != i8)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testI32(-1)");
int i32 = client.testI32(-1);
Console.WriteLine(" = " + i32);
if (-1 != i32)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testI64(-34359738368)");
long i64 = client.testI64(-34359738368);
Console.WriteLine(" = " + i64);
if (-34359738368 != i64)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
// TODO: Validate received message
Console.Write("testDouble(5.325098235)");
double dub = client.testDouble(5.325098235);
Console.WriteLine(" = " + dub);
if (5.325098235 != dub)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testDouble(-0.000341012439638598279)");
dub = client.testDouble(-0.000341012439638598279);
Console.WriteLine(" = " + dub);
if (-0.000341012439638598279 != dub)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
byte[] binOut = PrepareTestData(true);
Console.Write("testBinary(" + BytesToHex(binOut) + ")");
try
{
byte[] binIn = client.testBinary(binOut);
Console.WriteLine(" = " + BytesToHex(binIn));
if (binIn.Length != binOut.Length)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs)
if (binIn[ofs] != binOut[ofs])
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
}
catch (Thrift.TApplicationException ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
// binary equals? only with hashcode option enabled ...
Console.WriteLine("Test CrazyNesting");
if( typeof(CrazyNesting).GetMethod("Equals").DeclaringType == typeof(CrazyNesting))
{
CrazyNesting one = new CrazyNesting();
CrazyNesting two = new CrazyNesting();
one.String_field = "crazy";
two.String_field = "crazy";
one.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
if (!one.Equals(two))
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorContainers;
throw new Exception("CrazyNesting.Equals failed");
}
}
// TODO: Validate received message
Console.Write("testStruct({\"Zero\", 1, -3, -5})");
Xtruct o = new Xtruct();
o.String_thing = "Zero";
o.Byte_thing = (sbyte)1;
o.I32_thing = -3;
o.I64_thing = -5;
Xtruct i = client.testStruct(o);
Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}");
// TODO: Validate received message
Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})");
Xtruct2 o2 = new Xtruct2();
o2.Byte_thing = (sbyte)1;
o2.Struct_thing = o;
o2.I32_thing = 5;
Xtruct2 i2 = client.testNest(o2);
i = i2.Struct_thing;
Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}");
Dictionary<int, int> mapout = new Dictionary<int, int>();
for (int j = 0; j < 5; j++)
{
mapout[j] = j - 10;
}
Console.Write("testMap({");
bool first = true;
foreach (int key in mapout.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapout[key]);
}
Console.Write("})");
Dictionary<int, int> mapin = client.testMap(mapout);
Console.Write(" = {");
first = true;
foreach (int key in mapin.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapin[key]);
}
Console.WriteLine("}");
// TODO: Validate received message
List<int> listout = new List<int>();
for (int j = -2; j < 3; j++)
{
listout.Add(j);
}
Console.Write("testList({");
first = true;
foreach (int j in listout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
List<int> listin = client.testList(listout);
Console.Write(" = {");
first = true;
foreach (int j in listin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
//set
// TODO: Validate received message
THashSet<int> setout = new THashSet<int>();
for (int j = -2; j < 3; j++)
{
setout.Add(j);
}
Console.Write("testSet({");
first = true;
foreach (int j in setout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
THashSet<int> setin = client.testSet(setout);
Console.Write(" = {");
first = true;
foreach (int j in setin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
Console.Write("testEnum(ONE)");
Numberz ret = client.testEnum(Numberz.ONE);
Console.WriteLine(" = " + ret);
if (Numberz.ONE != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(TWO)");
ret = client.testEnum(Numberz.TWO);
Console.WriteLine(" = " + ret);
if (Numberz.TWO != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(THREE)");
ret = client.testEnum(Numberz.THREE);
Console.WriteLine(" = " + ret);
if (Numberz.THREE != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(FIVE)");
ret = client.testEnum(Numberz.FIVE);
Console.WriteLine(" = " + ret);
if (Numberz.FIVE != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(EIGHT)");
ret = client.testEnum(Numberz.EIGHT);
Console.WriteLine(" = " + ret);
if (Numberz.EIGHT != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testTypedef(309858235082523)");
long uid = client.testTypedef(309858235082523L);
Console.WriteLine(" = " + uid);
if (309858235082523L != uid)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
// TODO: Validate received message
Console.Write("testMapMap(1)");
Dictionary<int, Dictionary<int, int>> mm = client.testMapMap(1);
Console.Write(" = {");
foreach (int key in mm.Keys)
{
Console.Write(key + " => {");
Dictionary<int, int> m2 = mm[key];
foreach (int k2 in m2.Keys)
{
Console.Write(k2 + " => " + m2[k2] + ", ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
// TODO: Validate received message
Insanity insane = new Insanity();
insane.UserMap = new Dictionary<Numberz, long>();
insane.UserMap[Numberz.FIVE] = 5000L;
Xtruct truck = new Xtruct();
truck.String_thing = "Truck";
truck.Byte_thing = (sbyte)8;
truck.I32_thing = 8;
truck.I64_thing = 8;
insane.Xtructs = new List<Xtruct>();
insane.Xtructs.Add(truck);
Console.Write("testInsanity()");
Dictionary<long, Dictionary<Numberz, Insanity>> whoa = client.testInsanity(insane);
Console.Write(" = {");
foreach (long key in whoa.Keys)
{
Dictionary<Numberz, Insanity> val = whoa[key];
Console.Write(key + " => {");
foreach (Numberz k2 in val.Keys)
{
Insanity v2 = val[k2];
Console.Write(k2 + " => {");
Dictionary<Numberz, long> userMap = v2.UserMap;
Console.Write("{");
if (userMap != null)
{
foreach (Numberz k3 in userMap.Keys)
{
Console.Write(k3 + " => " + userMap[k3] + ", ");
}
}
else
{
Console.Write("null");
}
Console.Write("}, ");
List<Xtruct> xtructs = v2.Xtructs;
Console.Write("{");
if (xtructs != null)
{
foreach (Xtruct x in xtructs)
{
Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, ");
}
}
else
{
Console.Write("null");
}
Console.Write("}");
Console.Write("}, ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
sbyte arg0 = 1;
int arg1 = 2;
long arg2 = long.MaxValue;
Dictionary<short, string> multiDict = new Dictionary<short, string>();
multiDict[1] = "one";
Numberz arg4 = Numberz.FIVE;
long arg5 = 5000000;
Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + "," + multiDict + "," + arg4 + "," + arg5 + ")");
Xtruct multiResponse = client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5);
Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing
+ ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n");
try
{
Console.WriteLine("testException(\"Xception\")");
client.testException("Xception");
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Xception ex)
{
if (ex.ErrorCode != 1001 || ex.Message != "Xception")
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testException(\"TException\")");
client.testException("TException");
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Thrift.TException)
{
// OK
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testException(\"ok\")");
client.testException("ok");
// OK
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testMultiException(\"Xception\", ...)");
client.testMultiException("Xception", "ignore");
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Xception ex)
{
if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception")
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testMultiException(\"Xception2\", ...)");
client.testMultiException("Xception2", "ignore");
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Xception2 ex)
{
if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2")
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testMultiException(\"success\", \"OK\")");
if ("OK" != client.testMultiException("success", "OK").String_thing)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine("Test Oneway(1)");
client.testOneway(1);
sw.Stop();
if (sw.ElapsedMilliseconds > 1000)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("Test Calltime()");
var startt = DateTime.UtcNow;
for ( int k=0; k<1000; ++k )
client.testVoid();
Console.WriteLine(" = " + (DateTime.UtcNow - startt).TotalSeconds.ToString() + " ms a testVoid() call" );
return returnCode;
}
}
}
| |
//
// Copyright (c) 2017 The Material Components for iOS Xamarin Binding Authors.
// All Rights Reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using Foundation;
using UIKit;
using MaterialComponents;
using ObjCRuntime;
using CoreGraphics;
namespace MaterialComponents.MaterialCollections
{
using MaterialComponents.MaterialCollectionLayoutAttributes;
using MaterialComponents.MaterialInk;
// @protocol MDCCollectionViewEditing <NSObject>
public interface IMDCCollectionViewEditing { }
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface MDCCollectionViewEditing
{
// @required @property (readonly, nonatomic, weak) UICollectionView * _Nullable collectionView;
//FIXME: [Abstract]
[NullAllowed, Export("collectionView", ArgumentSemantic.Weak)]
UICollectionView CollectionView { get; }
[Wrap("WeakDelegate")] //FIXME: ", Abstract]"
[NullAllowed]
MDCCollectionViewEditingDelegate Delegate { get; set; }
// @required @property (nonatomic, weak) id<MDCCollectionViewEditingDelegate> _Nullable delegate;
//FIXME: [Abstract]
[NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @required @property (readonly, nonatomic, strong) NSIndexPath * _Nullable reorderingCellIndexPath;
[Abstract]
[NullAllowed, Export("reorderingCellIndexPath", ArgumentSemantic.Strong)]
NSIndexPath ReorderingCellIndexPath { get; }
// @required @property (readonly, nonatomic, strong) NSIndexPath * _Nullable dismissingCellIndexPath;
[Abstract]
[NullAllowed, Export("dismissingCellIndexPath", ArgumentSemantic.Strong)]
NSIndexPath DismissingCellIndexPath { get; }
// @required @property (readonly, assign, nonatomic) NSInteger dismissingSection;
[Abstract]
[Export("dismissingSection")]
nint DismissingSection { get; }
// @required @property (getter = isEditing, nonatomic) BOOL editing;
[Abstract]
[Export("editing")]
bool Editing { [Bind("isEditing")] get; set; }
// @required -(void)setEditing:(BOOL)editing animated:(BOOL)animated;
[Abstract]
[Export("setEditing:animated:")]
void Animated(bool editing, bool animated);
}
// @protocol MDCCollectionViewEditingDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface MDCCollectionViewEditingDelegate
{
// @optional -(BOOL)collectionViewAllowsEditing:(UICollectionView * _Nonnull)collectionView;
[Export("collectionViewAllowsEditing:")]
bool AllowsEditing(UICollectionView collectionView);
// @optional -(void)collectionViewWillBeginEditing:(UICollectionView * _Nonnull)collectionView;
[Export("collectionViewWillBeginEditing:")]
void WillBeginEditing(UICollectionView collectionView);
// @optional -(void)collectionViewDidBeginEditing:(UICollectionView * _Nonnull)collectionView;
[Export("collectionViewDidBeginEditing:")]
void DidBeginEditing(UICollectionView collectionView);
// @optional -(void)collectionViewWillEndEditing:(UICollectionView * _Nonnull)collectionView;
[Export("collectionViewWillEndEditing:")]
void WillEndEditing(UICollectionView collectionView);
// @optional -(void)collectionViewDidEndEditing:(UICollectionView * _Nonnull)collectionView;
[Export("collectionViewDidEndEditing:")]
void DidEndEditing(UICollectionView collectionView);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView canEditItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:canEditItemAtIndexPath:")]
bool CanEditItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView canSelectItemDuringEditingAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:canSelectItemDuringEditingAtIndexPath:")]
bool CanSelectItemDuringEditingAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(BOOL)collectionViewAllowsReordering:(UICollectionView * _Nonnull)collectionView;
[Export("collectionViewAllowsReordering:")]
bool AllowsReordering(UICollectionView collectionView);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView canMoveItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:canMoveItemAtIndexPath:")]
bool CanMoveItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView canMoveItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath toIndexPath:(NSIndexPath * _Nonnull)newIndexPath;
[Export("collectionView:canMoveItemAtIndexPath:toIndexPath:")]
bool CanMoveItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath, NSIndexPath newIndexPath);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView willMoveItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath toIndexPath:(NSIndexPath * _Nonnull)newIndexPath;
[Export("collectionView:willMoveItemAtIndexPath:toIndexPath:")]
void WillMoveItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath, NSIndexPath newIndexPath);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView didMoveItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath toIndexPath:(NSIndexPath * _Nonnull)newIndexPath;
[Export("collectionView:didMoveItemAtIndexPath:toIndexPath:")]
void DidMoveItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath, NSIndexPath newIndexPath);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView willBeginDraggingItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:willBeginDraggingItemAtIndexPath:")]
void WillBeginDraggingItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView didEndDraggingItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:didEndDraggingItemAtIndexPath:")]
void DidEndDraggingItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView willDeleteItemsAtIndexPaths:(NSArray<NSIndexPath *> * _Nonnull)indexPaths;
[Export("collectionView:willDeleteItemsAtIndexPaths:")]
void WillDeleteItemsAtIndexPaths(UICollectionView collectionView, NSIndexPath[] indexPaths);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView didDeleteItemsAtIndexPaths:(NSArray<NSIndexPath *> * _Nonnull)indexPaths;
[Export("collectionView:didDeleteItemsAtIndexPaths:")]
void DidDeleteItemsAtIndexPaths(UICollectionView collectionView, NSIndexPath[] indexPaths);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView willDeleteSections:(NSIndexSet * _Nonnull)sections;
[Export("collectionView:willDeleteSections:")]
void WillDeleteSections(UICollectionView collectionView, NSIndexSet sections);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView didDeleteSections:(NSIndexSet * _Nonnull)sections;
[Export("collectionView:didDeleteSections:")]
void DidDeletedSections(UICollectionView collectionView, NSIndexSet sections);
// @optional -(BOOL)collectionViewAllowsSwipeToDismissItem:(UICollectionView * _Nonnull)collectionView;
[Export("collectionViewAllowsSwipeToDismissItem:")]
bool AllowsSwipeToDismissItem(UICollectionView collectionView);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView canSwipeToDismissItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:canSwipeToDismissItemAtIndexPath:")]
bool CanSwipeToDismissItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView willBeginSwipeToDismissItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:willBeginSwipeToDismissItemAtIndexPath:")]
void WillBeginSwipeToDismissItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView didEndSwipeToDismissItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:didEndSwipeToDismissItemAtIndexPath:")]
void DidEndSwipeToDismissItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView didCancelSwipeToDismissItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:didCancelSwipeToDismissItemAtIndexPath:")]
void DidCancelSwipeToDismissItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(BOOL)collectionViewAllowsSwipeToDismissSection:(UICollectionView * _Nonnull)collectionView;
[Export("collectionViewAllowsSwipeToDismissSection:")]
bool AllowsSwipeToDismissSection(UICollectionView collectionView);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView canSwipeToDismissSection:(NSInteger)section;
[Export("collectionView:canSwipeToDismissSection:")]
bool CanSwipeToDismissSection(UICollectionView collectionView, nint section);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView willBeginSwipeToDismissSection:(NSInteger)section;
[Export("collectionView:willBeginSwipeToDismissSection:")]
void WillBeginSwipeToDismissSection(UICollectionView collectionView, nint section);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView didEndSwipeToDismissSection:(NSInteger)section;
[Export("collectionView:didEndSwipeToDismissSection:")]
void DidEndSwipeToDismissSection(UICollectionView collectionView, nint section);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView didCancelSwipeToDismissSection:(NSInteger)section;
[Export("collectionView:didCancelSwipeToDismissSection:")]
void DidCancelSwipeToDismissSection(UICollectionView collectionView, nint section);
}
// @protocol MDCCollectionViewStyling <NSObject>
// HACK: Fixed not an abstract class see details below
// 1. created pulbic interface IMDCCollectionViewStyling
// 2. used IMDCCollectionViewStyling everywhere
public interface IMDCCollectionViewStyling { }
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface MDCCollectionViewStyling
{
// @required @property (readonly, nonatomic, weak) UICollectionView * _Nullable collectionView;
//FIXME: [Abstract]
[NullAllowed, Export("collectionView", ArgumentSemantic.Weak)]
UICollectionView CollectionView { get; }
[Wrap("WeakDelegate")] // FIXME: ", Abstract]"
[NullAllowed]
MDCCollectionViewStylingDelegate Delegate { get; set; }
// @required @property (nonatomic, weak) id<MDCCollectionViewStylingDelegate> _Nullable delegate;
//FIXME: [Abstract]
[NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @required @property (assign, nonatomic) BOOL shouldInvalidateLayout;
[Abstract]
[Export("shouldInvalidateLayout")]
bool ShouldInvalidateLayout { get; set; }
// @required @property (nonatomic, strong) UIColor * _Nonnull cellBackgroundColor;
[Abstract]
[Export("cellBackgroundColor", ArgumentSemantic.Strong)]
UIColor CellBackgroundColor { get; set; }
// @required @property (assign, nonatomic) MDCCollectionViewCellLayoutType cellLayoutType;
[Abstract]
[Export("cellLayoutType", ArgumentSemantic.Assign)]
MDCCollectionViewCellLayoutType CellLayoutType { get; set; }
// @required @property (assign, nonatomic) NSInteger gridColumnCount;
[Abstract]
[Export("gridColumnCount")]
nint GridColumnCount { get; set; }
// @required @property (assign, nonatomic) CGFloat gridPadding;
[Abstract]
[Export("gridPadding")]
nfloat GridPadding { get; set; }
// @required @property (assign, nonatomic) MDCCollectionViewCellStyle cellStyle;
[Abstract]
[Export("cellStyle", ArgumentSemantic.Assign)]
MDCCollectionViewCellStyle CellStyle { get; set; }
// @required -(void)setCellStyle:(MDCCollectionViewCellStyle)cellStyle animated:(BOOL)animated;
[Abstract]
[Export("setCellStyle:animated:")]
void SetCellStyle(MDCCollectionViewCellStyle cellStyle, bool animated);
// @required -(MDCCollectionViewCellStyle)cellStyleAtSectionIndex:(NSInteger)section;
[Abstract]
[Export("cellStyleAtSectionIndex:")]
MDCCollectionViewCellStyle CellStyleAtSectionIndex(nint section);
// @required -(UIEdgeInsets)backgroundImageViewOutsetsForCellWithAttribute:(MDCCollectionViewLayoutAttributes * _Nonnull)attr;
[Abstract]
[Export("backgroundImageViewOutsetsForCellWithAttribute:")]
UIEdgeInsets BackgroundImageViewOutsetsForCellWithAttribute(MDCCollectionViewLayoutAttributes attr);
// @required -(UIImage * _Nullable)backgroundImageForCellLayoutAttributes:(MDCCollectionViewLayoutAttributes * _Nonnull)attr;
[Abstract]
[Export("backgroundImageForCellLayoutAttributes:")]
[return: NullAllowed]
UIImage BackgroundImageForCellLayoutAttributes(MDCCollectionViewLayoutAttributes attr);
// @required @property (nonatomic, strong) UIColor * _Nullable separatorColor;
[Abstract]
[NullAllowed, Export("separatorColor", ArgumentSemantic.Strong)]
UIColor SeparatorColor { get; set; }
// @required @property (nonatomic) UIEdgeInsets separatorInset;
[Abstract]
[Export("separatorInset", ArgumentSemantic.Assign)]
UIEdgeInsets SeparatorInset { get; set; }
// @required @property (nonatomic) CGFloat separatorLineHeight;
[Abstract]
[Export("separatorLineHeight")]
nfloat SeparatorLineHeight { get; set; }
// @required @property (nonatomic) BOOL shouldHideSeparators;
[Abstract]
[Export("shouldHideSeparators")]
bool ShouldHideSeparators { get; set; }
// @required -(BOOL)shouldHideSeparatorForCellLayoutAttributes:(MDCCollectionViewLayoutAttributes * _Nonnull)attr;
[Abstract]
[Export("shouldHideSeparatorForCellLayoutAttributes:")]
bool ShouldHideSeparatorForCellLayoutAttributes(MDCCollectionViewLayoutAttributes attr);
// @required @property (assign, nonatomic) BOOL allowsItemInlay;
[Abstract]
[Export("allowsItemInlay")]
bool AllowsItemInlay { get; set; }
// @required @property (assign, nonatomic) BOOL allowsMultipleItemInlays;
[Abstract]
[Export("allowsMultipleItemInlays")]
bool AllowsMultipleItemInlays { get; set; }
// @required -(NSArray<NSIndexPath *> * _Nullable)indexPathsForInlaidItems;
[Abstract]
[NullAllowed, Export("indexPathsForInlaidItems")]
//[Verify(MethodToProperty)]
NSIndexPath[] IndexPathsForInlaidItems { get; }
// @required -(BOOL)isItemInlaidAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Abstract]
[Export("isItemInlaidAtIndexPath:")]
bool IsItemInlaidAtIndexPath(NSIndexPath indexPath);
// @required -(void)applyInlayToItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath animated:(BOOL)animated;
[Abstract]
[Export("applyInlayToItemAtIndexPath:animated:")]
void ApplyInlayToItemAtIndexPath(NSIndexPath indexPath, bool animated);
// @required -(void)removeInlayFromItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath animated:(BOOL)animated;
[Abstract]
[Export("removeInlayFromItemAtIndexPath:animated:")]
void RemoveInlayFromItemAtIndexPath(NSIndexPath indexPath, bool animated);
// @required -(void)applyInlayToAllItemsAnimated:(BOOL)animated;
[Abstract]
[Export("applyInlayToAllItemsAnimated:")]
void ApplyInlayToAllItemsAnimated(bool animated);
// @required -(void)removeInlayFromAllItemsAnimated:(BOOL)animated;
[Abstract]
[Export("removeInlayFromAllItemsAnimated:")]
void RemoveInlayFromAllItemsAnimated(bool animated);
// @required -(void)resetIndexPathsForInlaidItems;
[Abstract]
[Export("resetIndexPathsForInlaidItems")]
void ResetIndexPathsForInlaidItems();
// @required @property (assign, nonatomic) BOOL shouldAnimateCellsOnAppearance;
[Abstract]
[Export("shouldAnimateCellsOnAppearance")]
bool ShouldAnimateCellsOnAppearance { get; set; }
// @required @property (readonly, assign, nonatomic) BOOL willAnimateCellsOnAppearance;
[Abstract]
[Export("willAnimateCellsOnAppearance")]
bool WillAnimateCellsOnAppearance { get; }
// @required @property (readonly, assign, nonatomic) CGFloat animateCellsOnAppearancePadding;
[Abstract]
[Export("animateCellsOnAppearancePadding")]
nfloat AnimateCellsOnAppearancePadding { get; }
// @required @property (readonly, assign, nonatomic) NSTimeInterval animateCellsOnAppearanceDuration;
[Abstract]
[Export("animateCellsOnAppearanceDuration")]
double AnimateCellsOnAppearanceDuration { get; }
// @required -(void)beginCellAppearanceAnimation;
[Abstract]
[Export("beginCellAppearanceAnimation")]
void BeginCellAppearanceAnimation();
}
// @protocol MDCCollectionViewStylingDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface MDCCollectionViewStylingDelegate
{
// @optional -(CGFloat)collectionView:(UICollectionView * _Nonnull)collectionView cellHeightAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:cellHeightAtIndexPath:")]
nfloat CellHeightAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(MDCCollectionViewCellStyle)collectionView:(UICollectionView * _Nonnull)collectionView cellStyleForSection:(NSInteger)section;
[Export("collectionView:cellStyleForSection:")]
MDCCollectionViewCellStyle CellStyleForSection(UICollectionView collectionView, nint section);
// @optional -(UIColor * _Nullable)collectionView:(UICollectionView * _Nonnull)collectionView cellBackgroundColorAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:cellBackgroundColorAtIndexPath:")]
[return: NullAllowed]
UIColor CellBackgroundColorAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView shouldHideItemBackgroundAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:shouldHideItemBackgroundAtIndexPath:")]
bool ShouldHideItemBackgroundAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView shouldHideHeaderBackgroundForSection:(NSInteger)section;
[Export("collectionView:shouldHideHeaderBackgroundForSection:")]
bool ShouldHideHeaderBackgroundForSection(UICollectionView collectionView, nint section);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView shouldHideFooterBackgroundForSection:(NSInteger)section;
[Export("collectionView:shouldHideFooterBackgroundForSection:")]
bool ShouldHideFooterBackgroundForSection(UICollectionView collectionView, nint section);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView shouldHideItemSeparatorAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:shouldHideItemSeparatorAtIndexPath:")]
bool ShouldHideItemSeparatorAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView shouldHideHeaderSeparatorForSection:(NSInteger)section;
[Export("collectionView:shouldHideHeaderSeparatorForSection:")]
bool ShouldHideHeaderSeparatorForSection(UICollectionView collectionView, nint section);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView shouldHideFooterSeparatorForSection:(NSInteger)section;
[Export("collectionView:shouldHideFooterSeparatorForSection:")]
bool ShouldHideFooterSeparatorForSection(UICollectionView collectionView, nint section);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView didApplyInlayToItemAtIndexPaths:(NSArray<NSIndexPath *> * _Nonnull)indexPaths;
[Export("collectionView:didApplyInlayToItemAtIndexPaths:")]
void DidApplyInlayToItemAtIndexPaths(UICollectionView collectionView, NSIndexPath[] indexPaths);
// @optional -(void)collectionView:(UICollectionView * _Nonnull)collectionView didRemoveInlayFromItemAtIndexPaths:(NSArray<NSIndexPath *> * _Nonnull)indexPaths;
[Export("collectionView:didRemoveInlayFromItemAtIndexPaths:")]
void DidRemoveInlayFromItemAtIndexPaths(UICollectionView collectionView, NSIndexPath[] indexPaths);
// @optional -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView hidesInkViewAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:hidesInkViewAtIndexPath:")]
bool HidesInkViewAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(UIColor * _Nullable)collectionView:(UICollectionView * _Nonnull)collectionView inkColorAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:inkColorAtIndexPath:")]
[return: NullAllowed]
UIColor InkColorAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// @optional -(MDCInkView * _Nonnull)collectionView:(UICollectionView * _Nonnull)collectionView inkTouchController:(MDCInkTouchController * _Nonnull)inkTouchController inkViewAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
[Export("collectionView:inkTouchController:inkViewAtIndexPath:")]
MDCInkView InkTouchController(UICollectionView collectionView, MDCInkTouchController inkTouchController, NSIndexPath indexPath);
}
// @interface MDCCollectionViewController : UICollectionViewController <MDCCollectionViewEditingDelegate, MDCCollectionViewStylingDelegate, UICollectionViewDelegateFlowLayout>
// HACK: Remove [
//[Protocol,[
//[ Model]
[BaseType(typeof(UICollectionViewController))]
interface MDCCollectionViewController : MDCCollectionViewEditingDelegate, MDCCollectionViewStylingDelegate, IUICollectionViewDelegateFlowLayout
{
// @property (readonly, nonatomic, strong) id<MDCCollectionViewStyling> _Nonnull styler;
[Export("styler", ArgumentSemantic.Strong)]
IMDCCollectionViewStyling Styler { get; }
// @property (readonly, nonatomic, strong) id<MDCCollectionViewEditing> _Nonnull editor;
[Export("editor", ArgumentSemantic.Strong)]
IMDCCollectionViewEditing Editor { get; }
// -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath __attribute__((objc_requires_super));
[Export("collectionView:shouldHighlightItemAtIndexPath:")]
//FIXME: Enable when Generator is updated [RequiresSuper]
bool ShouldHighlightItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// -(void)collectionView:(UICollectionView * _Nonnull)collectionView didHighlightItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath __attribute__((objc_requires_super));
[Export("collectionView:didHighlightItemAtIndexPath:")]
//[RequiresSuper]
void DidHighlightItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// -(void)collectionView:(UICollectionView * _Nonnull)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath __attribute__((objc_requires_super));
[Export("collectionView:didUnhighlightItemAtIndexPath:")]
//[RequiresSuper]
void DidUnhighlightItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView shouldSelectItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath __attribute__((objc_requires_super));
[Export("collectionView:shouldSelectItemAtIndexPath:")]
//[RequiresSuper]
bool ShouldSelectItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// -(BOOL)collectionView:(UICollectionView * _Nonnull)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath __attribute__((objc_requires_super));
[Export("collectionView:shouldDeselectItemAtIndexPath:")]
//[RequiresSuper]
bool ShouldDeselectItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// -(void)collectionView:(UICollectionView * _Nonnull)collectionView didSelectItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath __attribute__((objc_requires_super));
[Export("collectionView:didSelectItemAtIndexPath:")]
//[RequiresSuper]
void DidSelectItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// -(void)collectionView:(UICollectionView * _Nonnull)collectionView didDeselectItemAtIndexPath:(NSIndexPath * _Nonnull)indexPath __attribute__((objc_requires_super));
[Export("collectionView:didDeselectItemAtIndexPath:")]
//[RequiresSuper]
void DidDeselectItemAtIndexPath(UICollectionView collectionView, NSIndexPath indexPath);
// -(void)collectionViewWillBeginEditing:(UICollectionView * _Nonnull)collectionView __attribute__((objc_requires_super));
[Export("collectionViewWillBeginEditing:")]
//[RequiresSuper]
new void WillBeginEditing(UICollectionView collectionView);
// -(void)collectionViewWillEndEditing:(UICollectionView * _Nonnull)collectionView __attribute__((objc_requires_super));
[Export("collectionViewWillEndEditing:")]
//[RequiresSuper]
//FIXME: added new
new void WillEndEditing(UICollectionView collectionView);
// -(CGFloat)cellWidthAtSectionIndex:(NSInteger)section;
[Export("cellWidthAtSectionIndex:")]
nfloat CellWidthAtSectionIndex(nint section);
[Export("initWithCollectionViewLayout:")]
[DesignatedInitializer]
IntPtr Constructor(UICollectionViewLayout layout);
}
// @interface MDCCollectionViewFlowLayout : UICollectionViewFlowLayout
[BaseType(typeof(UICollectionViewFlowLayout))]
interface MDCCollectionViewFlowLayout
{
}
// @interface MDCCollectionViewCell : UICollectionViewCell
[BaseType(typeof(UICollectionViewCell))]
interface MDCCollectionViewCell
{
// @property (nonatomic) MDCCollectionViewCellAccessoryType accessoryType;
[Export("accessoryType", ArgumentSemantic.Assign)]
MDCCollectionViewCellAccessoryType AccessoryType { get; set; }
// @property (nonatomic, strong) UIView * _Nullable accessoryView;
[NullAllowed, Export("accessoryView", ArgumentSemantic.Strong)]
UIView AccessoryView { get; set; }
// @property (nonatomic) UIEdgeInsets accessoryInset;
[Export("accessoryInset", ArgumentSemantic.Assign)]
UIEdgeInsets AccessoryInset { get; set; }
// @property (nonatomic) BOOL shouldHideSeparator;
[Export("shouldHideSeparator")]
bool ShouldHideSeparator { get; set; }
// @property (nonatomic) UIEdgeInsets separatorInset;
[Export("separatorInset", ArgumentSemantic.Assign)]
UIEdgeInsets SeparatorInset { get; set; }
// @property (nonatomic) BOOL allowsCellInteractionsWhileEditing;
[Export("allowsCellInteractionsWhileEditing")]
bool AllowsCellInteractionsWhileEditing { get; set; }
// @property (getter = isEditing, nonatomic) BOOL editing;
[Export("editing")]
bool Editing { [Bind("isEditing")] get; set; }
// @property (nonatomic, strong) UIColor * _Null_unspecified editingSelectorColor __attribute__((annotate("ui_appearance_selector")));
[Export("editingSelectorColor", ArgumentSemantic.Strong)]
UIColor EditingSelectorColor { get; set; }
// -(void)setEditing:(BOOL)editing animated:(BOOL)animated;
[Export("setEditing:animated:")]
void SetEditing(bool editing, bool animated);
// @property (nonatomic, strong) MDCInkView * _Nullable inkView;
[NullAllowed, Export("inkView", ArgumentSemantic.Strong)]
MDCInkView InkView { get; set; }
[Export("initWithFrame:")]
[DesignatedInitializer]
IntPtr Constructor(CGRect frame);
}
[Static]
//[Verify(ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern const CGFloat MDCCellDefaultOneLineHeight;
[Field("MDCCellDefaultOneLineHeight", "__Internal")]
nfloat MDCCellDefaultOneLineHeight { get; }
// extern const CGFloat MDCCellDefaultOneLineWithAvatarHeight;
[Field("MDCCellDefaultOneLineWithAvatarHeight", "__Internal")]
nfloat MDCCellDefaultOneLineWithAvatarHeight { get; }
// extern const CGFloat MDCCellDefaultTwoLineHeight;
[Field("MDCCellDefaultTwoLineHeight", "__Internal")]
nfloat MDCCellDefaultTwoLineHeight { get; }
// extern const CGFloat MDCCellDefaultThreeLineHeight;
[Field("MDCCellDefaultThreeLineHeight", "__Internal")]
nfloat MDCCellDefaultThreeLineHeight { get; }
// extern NSString *const _Nonnull kSelectedCellAccessibilityHintKey;
[Field("kSelectedCellAccessibilityHintKey", "__Internal")]
NSString kSelectedCellAccessibilityHintKey { get; }
// extern NSString *const _Nonnull kDeselectedCellAccessibilityHintKey;
[Field("kDeselectedCellAccessibilityHintKey", "__Internal")]
NSString kDeselectedCellAccessibilityHintKey { get; }
// extern const CGFloat MDCCollectionViewCellStyleCardSectionInset;
[Field("MDCCollectionViewCellStyleCardSectionInset", "__Internal")]
float MDCCollectionViewCellStyleCardSectionInset { get; }
}
// @interface MDCCollectionViewTextCell : MDCCollectionViewCell
[BaseType(typeof(MDCCollectionViewCell))]
interface MDCCollectionViewTextCell
{
// @property (readonly, nonatomic, strong) UILabel * _Nullable textLabel;
[NullAllowed, Export("textLabel", ArgumentSemantic.Strong)]
UILabel TextLabel { get; }
// @property (readonly, nonatomic, strong) UILabel * _Nullable detailTextLabel;
[NullAllowed, Export("detailTextLabel", ArgumentSemantic.Strong)]
UILabel DetailTextLabel { get; }
// @property (readonly, nonatomic, strong) UIImageView * _Nullable imageView;
[NullAllowed, Export("imageView", ArgumentSemantic.Strong)]
UIImageView ImageView { get; }
}
}
| |
///////////////////////////////////////////////////////////////////////////////
//File: Wrapper_Decal.cs
//
//Description: Contains MetaViewWrapper classes implementing Decal views.
//
//References required:
// System.Drawing
// Decal.Adapter
//
//This file is Copyright (c) 2010 VirindiPlugins
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
///////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using Decal.Adapter;
using Decal.Adapter.Wrappers;
#if METAVIEW_PUBLIC_NS
namespace Zegeger.Decal.VVS.DecalControls
#else
namespace Zegeger.Decal.VVS.DecalControls
#endif
{
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class View : IView
{
ViewWrapper myView;
public ViewWrapper Underlying { get { return myView; } }
#region IView Members
public void Initialize(PluginHost p, string pXML)
{
myView = p.LoadViewResource(pXML);
}
public void InitializeRawXML(PluginHost p, string pXML)
{
myView = p.LoadView(pXML);
}
public void SetIcon(int icon, int iconlibrary)
{
myView.SetIcon(icon, iconlibrary);
}
public void SetIcon(int portalicon)
{
//throw new Exception("The method or operation is not implemented.");
}
public string Title
{
get
{
return myView.Title;
}
set
{
myView.Title = value;
}
}
public bool Visible
{
get
{
return myView.Activated;
}
set
{
myView.Activated = value;
}
}
public bool Activated
{
get
{
return Visible;
}
set
{
Visible = value;
}
}
public void Activate()
{
Visible = true;
}
public void Deactivate()
{
Visible = false;
}
public System.Drawing.Point Location
{
get
{
return new System.Drawing.Point(myView.Position.X, myView.Position.Y);
}
set
{
int w = myView.Position.Width;
int h = myView.Position.Height;
myView.Position = new System.Drawing.Rectangle(value.X, value.Y, w, h);
}
}
public System.Drawing.Rectangle Position
{
get
{
return myView.Position;
}
set
{
myView.Position = value;
}
}
public System.Drawing.Size Size
{
get
{
return new System.Drawing.Size(myView.Position.Width, myView.Position.Height);
}
}
#if VVS_WRAPPERS_PUBLIC
internal
#else
public
#endif
ViewSystemSelector.eViewSystem ViewType { get { return ViewSystemSelector.eViewSystem.DecalInject; } }
public IControl this[string id]
{
get
{
Control ret = null;
IControlWrapper iret = myView.Controls[id];
if (iret.GetType() == typeof(PushButtonWrapper))
ret = new Button();
if (iret.GetType() == typeof(CheckBoxWrapper))
ret = new CheckBox();
if (iret.GetType() == typeof(TextBoxWrapper))
ret = new TextBox();
if (iret.GetType() == typeof(ChoiceWrapper))
ret = new Combo();
if (iret.GetType() == typeof(SliderWrapper))
ret = new Slider();
if (iret.GetType() == typeof(ListWrapper))
ret = new List();
if (iret.GetType() == typeof(StaticWrapper))
ret = new StaticText();
if (iret.GetType() == typeof(NotebookWrapper))
ret = new Notebook();
if (iret.GetType() == typeof(ProgressWrapper))
ret = new ProgressBar();
if (ret == null) return null;
ret.myControl = iret;
ret.myName = id;
ret.Initialize();
allocatedcontrols.Add(ret);
return ret;
}
}
List<Control> allocatedcontrols = new List<Control>();
#endregion
#region IDisposable Members
bool disposed = false;
public void Dispose()
{
if (disposed) return;
disposed = true;
GC.SuppressFinalize(this);
foreach (Control c in allocatedcontrols)
c.Dispose();
myView.Dispose();
}
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class Control : IControl
{
internal IControlWrapper myControl;
public IControlWrapper Underlying { get { return myControl; } }
internal string myName;
public virtual void Initialize()
{
}
#region IControl Members
public string Name
{
get { return myName; }
}
public bool Visible
{
get { throw new Exception("The method or operation is not implemented."); }
}
public string TooltipText
{
get
{
return "";
}
set
{
}
}
#endregion
#region IDisposable Members
bool disposed = false;
public virtual void Dispose()
{
if (disposed) return;
disposed = true;
//myControl.Dispose();
}
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class Button : Control, IButton
{
public override void Initialize()
{
base.Initialize();
((PushButtonWrapper)myControl).Hit += new EventHandler<ControlEventArgs>(Button_Hit);
((PushButtonWrapper)myControl).Click += new EventHandler<ControlEventArgs>(Button_Click);
}
public override void Dispose()
{
base.Dispose();
((PushButtonWrapper)myControl).Hit -= new EventHandler<ControlEventArgs>(Button_Hit);
((PushButtonWrapper)myControl).Click -= new EventHandler<ControlEventArgs>(Button_Click);
}
void Button_Hit(object sender, ControlEventArgs e)
{
if (Hit != null)
Hit(this, null);
}
void Button_Click(object sender, ControlEventArgs e)
{
if (Click != null)
Click(this, new MVControlEventArgs(0));
}
#region IButton Members
public string Text
{
get
{
return ((PushButtonWrapper)myControl).Text;
//throw new Exception("The method or operation is not implemented.");
}
set
{
((PushButtonWrapper)myControl).Text = value;
//throw new Exception("The method or operation is not implemented.");
}
}
public System.Drawing.Color TextColor
{
get
{
return ((PushButtonWrapper)myControl).TextColor;
}
set
{
((PushButtonWrapper)myControl).TextColor = value;
}
}
public event EventHandler Hit;
public event EventHandler<MVControlEventArgs> Click;
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class CheckBox : Control, ICheckBox
{
public override void Initialize()
{
base.Initialize();
((CheckBoxWrapper)myControl).Change += new EventHandler<CheckBoxChangeEventArgs>(CheckBox_Change);
}
public override void Dispose()
{
base.Dispose();
((CheckBoxWrapper)myControl).Change -= new EventHandler<CheckBoxChangeEventArgs>(CheckBox_Change);
}
void CheckBox_Change(object sender, CheckBoxChangeEventArgs e)
{
if (Change != null)
Change(this, new MVCheckBoxChangeEventArgs(0, Checked));
if (Change_Old != null)
Change_Old(this, null);
}
#region ICheckBox Members
public string Text
{
get
{
return ((CheckBoxWrapper)myControl).Text;
}
set
{
((CheckBoxWrapper)myControl).Text = value;
}
}
public bool Checked
{
get
{
return ((CheckBoxWrapper)myControl).Checked;
}
set
{
((CheckBoxWrapper)myControl).Checked = value;
}
}
public event EventHandler<MVCheckBoxChangeEventArgs> Change;
public event EventHandler Change_Old;
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class TextBox : Control, ITextBox
{
public override void Initialize()
{
base.Initialize();
((TextBoxWrapper)myControl).Change += new EventHandler<TextBoxChangeEventArgs>(TextBox_Change);
((TextBoxWrapper)myControl).End += new EventHandler<TextBoxEndEventArgs>(TextBox_End);
}
public override void Dispose()
{
base.Dispose();
((TextBoxWrapper)myControl).Change -= new EventHandler<TextBoxChangeEventArgs>(TextBox_Change);
((TextBoxWrapper)myControl).End -= new EventHandler<TextBoxEndEventArgs>(TextBox_End);
}
void TextBox_Change(object sender, TextBoxChangeEventArgs e)
{
if (Change != null)
Change(this, new MVTextBoxChangeEventArgs(0, e.Text));
if (Change_Old != null)
Change_Old(this, null);
}
void TextBox_End(object sender, TextBoxEndEventArgs e)
{
if (End != null)
End(this, new MVTextBoxEndEventArgs(0, e.Success));
}
#region ITextBox Members
public string Text
{
get
{
return ((TextBoxWrapper)myControl).Text;
}
set
{
((TextBoxWrapper)myControl).Text = value;
}
}
public int Caret
{
get
{
return ((TextBoxWrapper)myControl).Caret;
}
set
{
((TextBoxWrapper)myControl).Caret = value;
}
}
public event EventHandler<MVTextBoxChangeEventArgs> Change;
public event EventHandler Change_Old;
public event EventHandler<MVTextBoxEndEventArgs> End;
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class Combo : Control, ICombo
{
public override void Initialize()
{
base.Initialize();
((ChoiceWrapper)myControl).Change += new EventHandler<IndexChangeEventArgs>(Combo_Change);
}
public override void Dispose()
{
base.Dispose();
((ChoiceWrapper)myControl).Change -= new EventHandler<IndexChangeEventArgs>(Combo_Change);
}
void Combo_Change(object sender, IndexChangeEventArgs e)
{
if (Change != null)
Change(this, new MVIndexChangeEventArgs(0, e.Index));
if (Change_Old != null)
Change_Old(this, null);
}
#region ICombo Members
public IComboIndexer Text
{
get
{
return new ComboIndexer(this);
}
}
public IComboDataIndexer Data
{
get
{
return new ComboDataIndexer(this);
}
}
public int Count
{
get
{
return ((ChoiceWrapper)myControl).Count;
}
}
public int Selected
{
get
{
return ((ChoiceWrapper)myControl).Selected;
}
set
{
((ChoiceWrapper)myControl).Selected = value;
}
}
public event EventHandler<MVIndexChangeEventArgs> Change;
public event EventHandler Change_Old;
public void Add(string text)
{
((ChoiceWrapper)myControl).Add(text, null);
}
public void Add(string text, object obj)
{
((ChoiceWrapper)myControl).Add(text, obj);
}
public void Insert(int index, string text)
{
throw new Exception("The method or operation is not implemented.");
}
public void RemoveAt(int index)
{
((ChoiceWrapper)myControl).Remove(index);
}
public void Remove(int index)
{
RemoveAt(index);
}
public void Clear()
{
((ChoiceWrapper)myControl).Clear();
}
#endregion
internal class ComboIndexer: IComboIndexer
{
Combo myCombo;
internal ComboIndexer(Combo c)
{
myCombo = c;
}
#region IComboIndexer Members
public string this[int index]
{
get
{
return ((ChoiceWrapper)myCombo.myControl).Text[index];
}
set
{
((ChoiceWrapper)myCombo.myControl).Text[index] = value;
}
}
#endregion
}
internal class ComboDataIndexer : IComboDataIndexer
{
Combo myCombo;
internal ComboDataIndexer(Combo c)
{
myCombo = c;
}
#region IComboIndexer Members
public object this[int index]
{
get
{
return ((ChoiceWrapper)myCombo.myControl).Data[index];
}
set
{
((ChoiceWrapper)myCombo.myControl).Data[index] = value;
}
}
#endregion
}
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class Slider : Control, ISlider
{
public override void Initialize()
{
base.Initialize();
((SliderWrapper)myControl).Change += new EventHandler<IndexChangeEventArgs>(Slider_Change);
}
public override void Dispose()
{
base.Dispose();
((SliderWrapper)myControl).Change -= new EventHandler<IndexChangeEventArgs>(Slider_Change);
}
void Slider_Change(object sender, IndexChangeEventArgs e)
{
if (Change != null)
Change(this, new MVIndexChangeEventArgs(0, e.Index));
if (Change_Old != null)
Change_Old(this, null);
}
#region ISlider Members
public int Position
{
get
{
return ((SliderWrapper)myControl).Position;
}
set
{
((SliderWrapper)myControl).Position = value;
}
}
public event EventHandler<MVIndexChangeEventArgs> Change;
public event EventHandler Change_Old;
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class List : Control, IList
{
public override void Initialize()
{
base.Initialize();
((ListWrapper)myControl).Selected += new EventHandler<ListSelectEventArgs>(List_Selected);
}
public override void Dispose()
{
base.Dispose();
((ListWrapper)myControl).Selected -= new EventHandler<ListSelectEventArgs>(List_Selected);
}
void List_Selected(object sender, ListSelectEventArgs e)
{
if (Click != null)
Click(this, e.Row, e.Column);
if (Selected != null)
Selected(this, new MVListSelectEventArgs(0, e.Row, e.Column));
}
#region IList Members
public event dClickedList Click;
public event EventHandler<MVListSelectEventArgs> Selected;
public void Clear()
{
((ListWrapper)myControl).Clear();
}
public IListRow this[int row]
{
get
{
return new ListRow(this, row);
}
}
public IListRow AddRow()
{
((ListWrapper)myControl).Add();
return new ListRow(this, ((ListWrapper)myControl).RowCount - 1);
}
public IListRow Add()
{
return AddRow();
}
public IListRow InsertRow(int pos)
{
((ListWrapper)myControl).Insert(pos);
return new ListRow(this, pos);
}
public IListRow Insert(int pos)
{
return InsertRow(pos);
}
public int RowCount
{
get { return ((ListWrapper)myControl).RowCount; }
}
public void RemoveRow(int index)
{
((ListWrapper)myControl).Delete(index);
}
public void Delete(int index)
{
RemoveRow(index);
}
public int ColCount
{
get
{
return ((ListWrapper)myControl).ColCount;
}
}
public int ScrollPosition
{
get
{
return ((ListWrapper)myControl).ScrollPosition;
}
set
{
((ListWrapper)myControl).ScrollPosition = value;
}
}
#endregion
public class ListRow : IListRow
{
internal List myList;
internal int myRow;
internal ListRow(List l, int r)
{
myList = l;
myRow = r;
}
#region IListRow Members
public IListCell this[int col]
{
get { return new ListCell(myList, myRow, col); }
}
#endregion
}
public class ListCell : IListCell
{
internal List myList;
internal int myRow;
internal int myCol;
public ListCell(List l, int r, int c)
{
myList = l;
myRow = r;
myCol = c;
}
#region IListCell Members
public void ResetColor()
{
Color = System.Drawing.Color.White;
}
public System.Drawing.Color Color
{
get
{
return ((ListWrapper)myList.myControl)[myRow][myCol].Color;
}
set
{
((ListWrapper)myList.myControl)[myRow][myCol].Color = value;
}
}
public int Width
{
get
{
return ((ListWrapper)myList.myControl)[myRow][myCol].Width;
}
set
{
((ListWrapper)myList.myControl)[myRow][myCol].Width = value;
}
}
public object this[int subval]
{
get
{
return ((ListWrapper)myList.myControl)[myRow][myCol][subval];
}
set
{
((ListWrapper)myList.myControl)[myRow][myCol][subval] = value;
}
}
#endregion
}
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class StaticText : Control, IStaticText
{
#region IStaticText Members
public string Text
{
get
{
return ((StaticWrapper)myControl).Text;
}
set
{
((StaticWrapper)myControl).Text = value;
}
}
#pragma warning disable 0067
public event EventHandler<MVControlEventArgs> Click;
#pragma warning restore 0067
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class Notebook : Control, INotebook
{
public override void Initialize()
{
base.Initialize();
((NotebookWrapper)myControl).Change += new EventHandler<IndexChangeEventArgs>(Notebook_Change);
}
public override void Dispose()
{
base.Dispose();
((NotebookWrapper)myControl).Change -= new EventHandler<IndexChangeEventArgs>(Notebook_Change);
}
void Notebook_Change(object sender, IndexChangeEventArgs e)
{
if (Change != null)
Change(this, new MVIndexChangeEventArgs(0, e.Index));
}
#region INotebook Members
public event EventHandler<MVIndexChangeEventArgs> Change;
public int ActiveTab
{
get
{
return ((NotebookWrapper)myControl).ActiveTab;
}
set
{
((NotebookWrapper)myControl).ActiveTab = value;
}
}
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class ProgressBar : Control, IProgressBar
{
#region IProgressBar Members
public int Position
{
get
{
return ((ProgressWrapper)myControl).Value;
}
set
{
((ProgressWrapper)myControl).Value = value;
}
}
public int Value
{
get
{
return Position;
}
set
{
Position = value;
}
}
public string PreText
{
get
{
return ((ProgressWrapper)myControl).PreText;
}
set
{
((ProgressWrapper)myControl).PreText = value;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol.Models
{
using System.Linq;
/// <summary>
/// An Azure Batch job to add.
/// </summary>
public partial class JobAddParameter
{
/// <summary>
/// Initializes a new instance of the JobAddParameter class.
/// </summary>
public JobAddParameter() { }
/// <summary>
/// Initializes a new instance of the JobAddParameter class.
/// </summary>
/// <param name="id">A string that uniquely identifies the job within
/// the account.</param>
/// <param name="poolInfo">The pool on which the Batch service runs the
/// job's tasks.</param>
/// <param name="displayName">The display name for the job.</param>
/// <param name="priority">The priority of the job.</param>
/// <param name="constraints">The execution constraints for the
/// job.</param>
/// <param name="jobManagerTask">Details of a Job Manager task to be
/// launched when the job is started.</param>
/// <param name="jobPreparationTask">The Job Preparation task.</param>
/// <param name="jobReleaseTask">The Job Release task.</param>
/// <param name="commonEnvironmentSettings">The list of common
/// environment variable settings. These environment variables are set
/// for all tasks in the job (including the Job Manager, Job
/// Preparation and Job Release tasks).</param>
/// <param name="onAllTasksComplete">The action the Batch service
/// should take when all tasks in the job are in the completed
/// state.</param>
/// <param name="onTaskFailure">The action the Batch service should
/// take when any task in the job fails. A task is considered to have
/// failed if it completes with a non-zero exit code and has exhausted
/// its retry count, or if it had a scheduling error.</param>
/// <param name="metadata">A list of name-value pairs associated with
/// the job as metadata.</param>
/// <param name="usesTaskDependencies">The flag that determines if this
/// job will use tasks with dependencies.</param>
public JobAddParameter(string id, PoolInformation poolInfo, string displayName = default(string), int? priority = default(int?), JobConstraints constraints = default(JobConstraints), JobManagerTask jobManagerTask = default(JobManagerTask), JobPreparationTask jobPreparationTask = default(JobPreparationTask), JobReleaseTask jobReleaseTask = default(JobReleaseTask), System.Collections.Generic.IList<EnvironmentSetting> commonEnvironmentSettings = default(System.Collections.Generic.IList<EnvironmentSetting>), OnAllTasksComplete? onAllTasksComplete = default(OnAllTasksComplete?), OnTaskFailure? onTaskFailure = default(OnTaskFailure?), System.Collections.Generic.IList<MetadataItem> metadata = default(System.Collections.Generic.IList<MetadataItem>), bool? usesTaskDependencies = default(bool?))
{
Id = id;
DisplayName = displayName;
Priority = priority;
Constraints = constraints;
JobManagerTask = jobManagerTask;
JobPreparationTask = jobPreparationTask;
JobReleaseTask = jobReleaseTask;
CommonEnvironmentSettings = commonEnvironmentSettings;
PoolInfo = poolInfo;
OnAllTasksComplete = onAllTasksComplete;
OnTaskFailure = onTaskFailure;
Metadata = metadata;
UsesTaskDependencies = usesTaskDependencies;
}
/// <summary>
/// Gets or sets a string that uniquely identifies the job within the
/// account.
/// </summary>
/// <remarks>
/// The ID can contain any combination of alphanumeric characters
/// including hyphens and underscores, and cannot contain more than 64
/// characters. It is common to use a GUID for the id.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the display name for the job.
/// </summary>
/// <remarks>
/// The display name need not be unique and can contain any Unicode
/// characters up to a maximum length of 1024.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the priority of the job.
/// </summary>
/// <remarks>
/// Priority values can range from -1000 to 1000, with -1000 being the
/// lowest priority and 1000 being the highest priority. The default
/// value is 0.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "priority")]
public int? Priority { get; set; }
/// <summary>
/// Gets or sets the execution constraints for the job.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "constraints")]
public JobConstraints Constraints { get; set; }
/// <summary>
/// Gets or sets details of a Job Manager task to be launched when the
/// job is started.
/// </summary>
/// <remarks>
/// If the job does not specify a Job Manager task, the user must
/// explicitly add tasks to the job. If the job does specify a Job
/// Manager task, the Batch service creates the Job Manager task when
/// the job is created, and will try to schedule the Job Manager task
/// before scheduling other tasks in the job. The Job Manager task's
/// typical purpose is to control and/or monitor job execution, for
/// example by deciding what additional tasks to run, determining when
/// the work is complete, etc. (However, a Job Manager task is not
/// restricted to these activities - it is a fully-fledged task in the
/// system and perform whatever actions are required for the job.) For
/// example, a Job Manager task might download a file specified as a
/// parameter, analyze the contents of that file and submit additional
/// tasks based on those contents.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "jobManagerTask")]
public JobManagerTask JobManagerTask { get; set; }
/// <summary>
/// Gets or sets the Job Preparation task.
/// </summary>
/// <remarks>
/// If a job has a Job Preparation task, the Batch service will run the
/// Job Preparation task on a compute node before starting any tasks of
/// that job on that compute node.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "jobPreparationTask")]
public JobPreparationTask JobPreparationTask { get; set; }
/// <summary>
/// Gets or sets the Job Release task.
/// </summary>
/// <remarks>
/// A Job Release task cannot be specified without also specifying a
/// Job Preparation task for the job. The Batch service runs the Job
/// Release task on the compute nodes that have run the Job Preparation
/// task. The primary purpose of the Job Release task is to undo
/// changes to compute nodes made by the Job Preparation task. Example
/// activities include deleting local files, or shutting down services
/// that were started as part of job preparation.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "jobReleaseTask")]
public JobReleaseTask JobReleaseTask { get; set; }
/// <summary>
/// Gets or sets the list of common environment variable settings.
/// These environment variables are set for all tasks in the job
/// (including the Job Manager, Job Preparation and Job Release tasks).
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "commonEnvironmentSettings")]
public System.Collections.Generic.IList<EnvironmentSetting> CommonEnvironmentSettings { get; set; }
/// <summary>
/// Gets or sets the pool on which the Batch service runs the job's
/// tasks.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "poolInfo")]
public PoolInformation PoolInfo { get; set; }
/// <summary>
/// Gets or sets the action the Batch service should take when all
/// tasks in the job are in the completed state.
/// </summary>
/// <remarks>
/// Note that if a job contains no tasks, then all tasks are considered
/// complete. This option is therefore most commonly used with a Job
/// Manager task; if you want to use automatic job termination without
/// a Job Manager, you should initially set onAllTasksComplete to
/// noAction and update the job properties to set onAllTasksComplete to
/// terminateJob once you have finished adding tasks. Permitted values
/// are: noAction - do nothing. The job remains active unless
/// terminated or disabled by some other means. terminateJob -
/// terminate the job. The job's terminateReason is set to
/// 'AllTasksComplete'. The default is noAction. Possible values
/// include: 'noAction', 'terminateJob'
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "onAllTasksComplete")]
public OnAllTasksComplete? OnAllTasksComplete { get; set; }
/// <summary>
/// Gets or sets the action the Batch service should take when any task
/// in the job fails. A task is considered to have failed if it
/// completes with a non-zero exit code and has exhausted its retry
/// count, or if it had a scheduling error.
/// </summary>
/// <remarks>
/// noAction - do nothing. performExitOptionsJobAction - take the
/// action associated with the task exit condition in the task's
/// exitConditions collection. (This may still result in no action
/// being taken, if that is what the task specifies.) The default is
/// noAction. Possible values include: 'noAction',
/// 'performExitOptionsJobAction'
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "onTaskFailure")]
public OnTaskFailure? OnTaskFailure { get; set; }
/// <summary>
/// Gets or sets a list of name-value pairs associated with the job as
/// metadata.
/// </summary>
/// <remarks>
/// The Batch service does not assign any meaning to metadata; it is
/// solely for the use of user code.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "metadata")]
public System.Collections.Generic.IList<MetadataItem> Metadata { get; set; }
/// <summary>
/// Gets or sets the flag that determines if this job will use tasks
/// with dependencies.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "usesTaskDependencies")]
public bool? UsesTaskDependencies { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Id == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "Id");
}
if (PoolInfo == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "PoolInfo");
}
if (this.JobManagerTask != null)
{
this.JobManagerTask.Validate();
}
if (this.JobPreparationTask != null)
{
this.JobPreparationTask.Validate();
}
if (this.JobReleaseTask != null)
{
this.JobReleaseTask.Validate();
}
if (this.CommonEnvironmentSettings != null)
{
foreach (var element in this.CommonEnvironmentSettings)
{
if (element != null)
{
element.Validate();
}
}
}
if (this.PoolInfo != null)
{
this.PoolInfo.Validate();
}
if (this.Metadata != null)
{
foreach (var element1 in this.Metadata)
{
if (element1 != null)
{
element1.Validate();
}
}
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gciv = Google.Cloud.Iam.V1;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Iap.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedIdentityAwareProxyAdminServiceClientTest
{
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient> mockGrpcClient = new moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IdentityAwareProxyAdminServiceClient client = new IdentityAwareProxyAdminServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient> mockGrpcClient = new moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IdentityAwareProxyAdminServiceClient client = new IdentityAwareProxyAdminServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient> mockGrpcClient = new moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IdentityAwareProxyAdminServiceClient client = new IdentityAwareProxyAdminServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient> mockGrpcClient = new moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IdentityAwareProxyAdminServiceClient client = new IdentityAwareProxyAdminServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient> mockGrpcClient = new moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IdentityAwareProxyAdminServiceClient client = new IdentityAwareProxyAdminServiceClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient> mockGrpcClient = new moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IdentityAwareProxyAdminServiceClient client = new IdentityAwareProxyAdminServiceClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIapSettingsRequestObject()
{
moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient> mockGrpcClient = new moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient>(moq::MockBehavior.Strict);
GetIapSettingsRequest request = new GetIapSettingsRequest
{
Name = "name1c9368b0",
};
IapSettings expectedResponse = new IapSettings
{
Name = "name1c9368b0",
AccessSettings = new AccessSettings(),
ApplicationSettings = new ApplicationSettings(),
};
mockGrpcClient.Setup(x => x.GetIapSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IdentityAwareProxyAdminServiceClient client = new IdentityAwareProxyAdminServiceClientImpl(mockGrpcClient.Object, null);
IapSettings response = client.GetIapSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIapSettingsRequestObjectAsync()
{
moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient> mockGrpcClient = new moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient>(moq::MockBehavior.Strict);
GetIapSettingsRequest request = new GetIapSettingsRequest
{
Name = "name1c9368b0",
};
IapSettings expectedResponse = new IapSettings
{
Name = "name1c9368b0",
AccessSettings = new AccessSettings(),
ApplicationSettings = new ApplicationSettings(),
};
mockGrpcClient.Setup(x => x.GetIapSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IapSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IdentityAwareProxyAdminServiceClient client = new IdentityAwareProxyAdminServiceClientImpl(mockGrpcClient.Object, null);
IapSettings responseCallSettings = await client.GetIapSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IapSettings responseCancellationToken = await client.GetIapSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateIapSettingsRequestObject()
{
moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient> mockGrpcClient = new moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient>(moq::MockBehavior.Strict);
UpdateIapSettingsRequest request = new UpdateIapSettingsRequest
{
IapSettings = new IapSettings(),
UpdateMask = new wkt::FieldMask(),
};
IapSettings expectedResponse = new IapSettings
{
Name = "name1c9368b0",
AccessSettings = new AccessSettings(),
ApplicationSettings = new ApplicationSettings(),
};
mockGrpcClient.Setup(x => x.UpdateIapSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IdentityAwareProxyAdminServiceClient client = new IdentityAwareProxyAdminServiceClientImpl(mockGrpcClient.Object, null);
IapSettings response = client.UpdateIapSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateIapSettingsRequestObjectAsync()
{
moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient> mockGrpcClient = new moq::Mock<IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient>(moq::MockBehavior.Strict);
UpdateIapSettingsRequest request = new UpdateIapSettingsRequest
{
IapSettings = new IapSettings(),
UpdateMask = new wkt::FieldMask(),
};
IapSettings expectedResponse = new IapSettings
{
Name = "name1c9368b0",
AccessSettings = new AccessSettings(),
ApplicationSettings = new ApplicationSettings(),
};
mockGrpcClient.Setup(x => x.UpdateIapSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IapSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IdentityAwareProxyAdminServiceClient client = new IdentityAwareProxyAdminServiceClientImpl(mockGrpcClient.Object, null);
IapSettings responseCallSettings = await client.UpdateIapSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IapSettings responseCancellationToken = await client.UpdateIapSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
/*
* 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://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// HudsonMasterComputerexecutors
/// </summary>
[DataContract(Name = "HudsonMasterComputerexecutors")]
public partial class HudsonMasterComputerexecutors : IEquatable<HudsonMasterComputerexecutors>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="HudsonMasterComputerexecutors" /> class.
/// </summary>
/// <param name="currentExecutable">currentExecutable.</param>
/// <param name="idle">idle.</param>
/// <param name="likelyStuck">likelyStuck.</param>
/// <param name="number">number.</param>
/// <param name="progress">progress.</param>
/// <param name="_class">_class.</param>
public HudsonMasterComputerexecutors(FreeStyleBuild currentExecutable = default(FreeStyleBuild), bool idle = default(bool), bool likelyStuck = default(bool), int number = default(int), int progress = default(int), string _class = default(string))
{
this.CurrentExecutable = currentExecutable;
this.Idle = idle;
this.LikelyStuck = likelyStuck;
this.Number = number;
this.Progress = progress;
this.Class = _class;
}
/// <summary>
/// Gets or Sets CurrentExecutable
/// </summary>
[DataMember(Name = "currentExecutable", EmitDefaultValue = false)]
public FreeStyleBuild CurrentExecutable { get; set; }
/// <summary>
/// Gets or Sets Idle
/// </summary>
[DataMember(Name = "idle", EmitDefaultValue = true)]
public bool Idle { get; set; }
/// <summary>
/// Gets or Sets LikelyStuck
/// </summary>
[DataMember(Name = "likelyStuck", EmitDefaultValue = true)]
public bool LikelyStuck { get; set; }
/// <summary>
/// Gets or Sets Number
/// </summary>
[DataMember(Name = "number", EmitDefaultValue = false)]
public int Number { get; set; }
/// <summary>
/// Gets or Sets Progress
/// </summary>
[DataMember(Name = "progress", EmitDefaultValue = false)]
public int Progress { get; set; }
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name = "_class", EmitDefaultValue = false)]
public string Class { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class HudsonMasterComputerexecutors {\n");
sb.Append(" CurrentExecutable: ").Append(CurrentExecutable).Append("\n");
sb.Append(" Idle: ").Append(Idle).Append("\n");
sb.Append(" LikelyStuck: ").Append(LikelyStuck).Append("\n");
sb.Append(" Number: ").Append(Number).Append("\n");
sb.Append(" Progress: ").Append(Progress).Append("\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as HudsonMasterComputerexecutors);
}
/// <summary>
/// Returns true if HudsonMasterComputerexecutors instances are equal
/// </summary>
/// <param name="input">Instance of HudsonMasterComputerexecutors to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(HudsonMasterComputerexecutors input)
{
if (input == null)
{
return false;
}
return
(
this.CurrentExecutable == input.CurrentExecutable ||
(this.CurrentExecutable != null &&
this.CurrentExecutable.Equals(input.CurrentExecutable))
) &&
(
this.Idle == input.Idle ||
this.Idle.Equals(input.Idle)
) &&
(
this.LikelyStuck == input.LikelyStuck ||
this.LikelyStuck.Equals(input.LikelyStuck)
) &&
(
this.Number == input.Number ||
this.Number.Equals(input.Number)
) &&
(
this.Progress == input.Progress ||
this.Progress.Equals(input.Progress)
) &&
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.CurrentExecutable != null)
{
hashCode = (hashCode * 59) + this.CurrentExecutable.GetHashCode();
}
hashCode = (hashCode * 59) + this.Idle.GetHashCode();
hashCode = (hashCode * 59) + this.LikelyStuck.GetHashCode();
hashCode = (hashCode * 59) + this.Number.GetHashCode();
hashCode = (hashCode * 59) + this.Progress.GetHashCode();
if (this.Class != null)
{
hashCode = (hashCode * 59) + this.Class.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
///////////////////////////////////////////////////////////////////
// Ported to C# by Martin Kraner <martinkraner@outlook.com> //
// from https://code.google.com/p/language-detection/ //
///////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Newtonsoft.Json;
#pragma warning disable 1591
namespace Frost.SharpLanguageDetect.Util {
/**
* {@link LangProfile} is a Language Profile Class.
* Users don't use this class directly.
*
* @author Nakatani Shuyo
*/
public class LangProfile : ILanguageProfile {
private const int MINIMUM_FREQ = 2;
private const int LESS_FREQ_RATIO = 100000;
[NonSerialized]
private static readonly Regex Regex1 = new Regex("^[A-Za-z]$", RegexOptions.Compiled);
[NonSerialized]
private static readonly Regex Regex2 = new Regex(".*[A-Za-z].*", RegexOptions.Compiled);
[JsonProperty("n_words")]
public readonly int[] _nWords = new int[NGram.N_GRAM];
[JsonProperty("freq")]
private Dictionary<string, int> _frequency;
public Dictionary<string, int> Frequency {
get { return _frequency; }
private set { _frequency = value; }
}
[JsonProperty("name")]
public string Name { get; private set; }
public int[] NWords { get { return _nWords; } }
public LangProfile() {
}
/**
* Normal Constructor
* @param name language name
*/
public LangProfile(string name) {
Frequency = new Dictionary<string, int>();
Name = name;
}
public LangProfile(string name, int[] nWords) {
Name = name;
_nWords = nWords;
}
/**
* Add n-gram to profile
* @param gram
*/
public void Add(string gram) {
if (Name == null || gram == null) {
return; // Illegal
}
int len = gram.Length;
if (len < 1 || len > NGram.N_GRAM) {
return; // Illegal
}
++NWords[len - 1];
if (Frequency.ContainsKey(gram)) {
Frequency[gram]++;
}
else {
Frequency.Add(gram, 1);
}
}
/**
* Eliminate below less frequency n-grams and noise Latin alphabets
*/
public void OmitLessFrequent() {
if (Name == null) {
return; // Illegal
}
int threshold = NWords[0] / LESS_FREQ_RATIO;
if (threshold < MINIMUM_FREQ) {
threshold = MINIMUM_FREQ;
}
IEnumerable<string> keys = Frequency.Keys;
List<string> keyToRemove = new List<string>();
int roman = 0;
foreach (string key in keys) {
int count = Frequency[key];
if (count <= threshold) {
NWords[key.Length - 1] -= count;
//Frequency.Remove(key); //exception
keyToRemove.Add(key);
}
else {
if (Regex1.IsMatch(key)) {
roman += count;
}
}
}
foreach (string key in keyToRemove) {
Frequency.Remove(key);
}
keyToRemove.Clear();
// roman check
if (roman < NWords[0] / 3) {
IEnumerable<string> keys2 = Frequency.Keys;
foreach (string key in keys2) {
if (Regex2.IsMatch(key)) {
NWords[key.Length - 1] -= Frequency[key];
keyToRemove.Add(key);
//Frequency.Remove(key); //Exception
}
}
foreach (string key in keyToRemove) {
Frequency.Remove(key);
}
}
}
/// <summary>Load Wikipedia abstract database file and generate its language profile</summary>
/// <param name="lang">Target language name.</param>
/// <param name="file">File target database file path.</param>
/// <returns>Language profile instance parsed from the database.</returns>
/// <exception cref="LangDetectException">Throws if the file is not an XML file or can't be opened.</exception>
public static LangProfile LoadFromWikipediaAbstract(string lang, FileInfo file) {
LangProfile profile = new LangProfile(lang);
try {
using (StreamReader sr = file.Name.EndsWith(".gz") ? new StreamReader(new GZipStream(file.OpenRead(), CompressionMode.Decompress)) : new StreamReader(file.OpenRead())) {
TagExtractor tagExtractor = new TagExtractor("abstract", 100);
using (XmlReader reader = XmlReader.Create(sr)) {
while (reader.Read()) {
switch (reader.NodeType) {
case XmlNodeType.Element:
tagExtractor.SetTag(reader.LocalName);
break;
case XmlNodeType.Text:
tagExtractor.Add(reader.Value);
break;
case XmlNodeType.EndElement:
tagExtractor.CloseTag(profile);
break;
}
}
Console.WriteLine(@"{0}:{1}", lang, tagExtractor.Count());
}
}
}
catch (XmlException) {
throw new LangDetectException(ErrorCode.TrainDataFormatError, string.Format("Training database file '{0}' is an invalid XML.", file.Name));
}
catch (Exception) {
throw new LangDetectException(ErrorCode.CantOpenTrainData, string.Format("Can't open training database file '{0}'", file.Name));
}
return profile;
}
/// <summary>Load text file with UTF-8 and generate its language profile</summary>
/// <param name="lang">target language name</param>
/// <param name="file">file target file path</param>
/// <returns>Language profile instance</returns>
/// <exception cref="LangDetectException">Throws when the training database file can't be opened.</exception>
public static LangProfile LoadFromText(string lang, FileInfo file) {
LangProfile profile = new LangProfile(lang);
StreamReader sr = null;
try {
sr = new StreamReader(file.OpenRead(), Encoding.UTF8);
int count = 0;
while (!sr.EndOfStream) {
string line = sr.ReadLine();
NGram gram = new NGram();
if (line != null) {
foreach (char ch in line) {
gram.AddChar(ch);
for (int n = 1; n <= NGram.N_GRAM; ++n) {
profile.Add(gram[n]);
}
}
}
++count;
}
Console.WriteLine(lang + ":" + count);
}
catch (IOException) {
throw new LangDetectException(ErrorCode.CantOpenTrainData, "Can't open training database file '" + file.Name + "'");
}
finally {
if (sr != null) {
sr.Close();
}
}
return profile;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Internal.Cryptography.Pal;
namespace System.Security.Cryptography.X509Certificates
{
public class X509Certificate2Collection : X509CertificateCollection
{
public X509Certificate2Collection()
{
}
public X509Certificate2Collection(X509Certificate2 certificate)
{
Add(certificate);
}
public X509Certificate2Collection(X509Certificate2[] certificates)
{
AddRange(certificates);
}
public X509Certificate2Collection(X509Certificate2Collection certificates)
{
AddRange(certificates);
}
public new X509Certificate2 this[int index]
{
get
{
return (X509Certificate2)(base[index]);
}
set
{
base[index] = value;
}
}
public int Add(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException("certificate");
return base.Add(certificate);
}
public void AddRange(X509Certificate2[] certificates)
{
if (certificates == null)
throw new ArgumentNullException("certificates");
int i = 0;
try
{
for (; i < certificates.Length; i++)
{
Add(certificates[i]);
}
}
catch
{
for (int j = 0; j < i; j++)
{
Remove(certificates[j]);
}
throw;
}
}
public void AddRange(X509Certificate2Collection certificates)
{
if (certificates == null)
throw new ArgumentNullException("certificates");
int i = 0;
try
{
for (; i < certificates.Count; i++)
{
Add(certificates[i]);
}
}
catch
{
for (int j = 0; j < i; j++)
{
Remove(certificates[j]);
}
throw;
}
}
public bool Contains(X509Certificate2 certificate)
{
// This method used to throw ArgumentNullException, but it has been deliberately changed
// to no longer throw to match the behavior of X509CertificateCollection.Contains and the
// IList.Contains implementation, which do not throw.
return base.Contains(certificate);
}
public byte[] Export(X509ContentType contentType)
{
return Export(contentType, password: null);
}
public byte[] Export(X509ContentType contentType, string password)
{
using (IStorePal storePal = StorePal.LinkFromCertificateCollection(this))
{
return storePal.Export(contentType, password);
}
}
public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly)
{
if (findValue == null)
throw new ArgumentNullException("findValue");
return FindPal.FindFromCollection(this, findType, findValue, validOnly);
}
public new X509Certificate2Enumerator GetEnumerator()
{
return new X509Certificate2Enumerator(this);
}
public void Import(byte[] rawData)
{
Import(rawData, password: null, keyStorageFlags: X509KeyStorageFlags.DefaultKeySet);
}
public void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
if (rawData == null)
throw new ArgumentNullException("rawData");
using (IStorePal storePal = StorePal.FromBlob(rawData, password, keyStorageFlags))
{
storePal.CopyTo(this);
}
}
public void Import(string fileName)
{
Import(fileName, password: null, keyStorageFlags: X509KeyStorageFlags.DefaultKeySet);
}
public void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
using (IStorePal storePal = StorePal.FromFile(fileName, password, keyStorageFlags))
{
storePal.CopyTo(this);
}
}
public void Insert(int index, X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException("certificate");
base.Insert(index, certificate);
}
public void Remove(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException("certificate");
base.Remove(certificate);
}
public void RemoveRange(X509Certificate2[] certificates)
{
if (certificates == null)
throw new ArgumentNullException("certificates");
int i = 0;
try
{
for (; i < certificates.Length; i++)
{
Remove(certificates[i]);
}
}
catch
{
for (int j = 0; j < i; j++)
{
Add(certificates[j]);
}
throw;
}
}
public void RemoveRange(X509Certificate2Collection certificates)
{
if (certificates == null)
throw new ArgumentNullException("certificates");
int i = 0;
try
{
for (; i < certificates.Count; i++)
{
Remove(certificates[i]);
}
}
catch
{
for (int j = 0; j < i; j++)
{
Add(certificates[j]);
}
throw;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Drawing.Tests
{
public class FontTests
{
public static IEnumerable<object[]> Ctor_Family_Size_TestData()
{
yield return new object[] { FontFamily.GenericMonospace, 1 };
yield return new object[] { FontFamily.GenericSerif, float.MaxValue };
}
public static IEnumerable<object[]> FontFamily_Equals_SameFamily_TestData()
{
yield return new object[] { FontFamily.GenericMonospace, 1 };
yield return new object[] { FontFamily.GenericSerif, float.MaxValue };
yield return new object[] { FontFamily.GenericSansSerif, 10 };
}
public static IEnumerable<object[]> FontFamily_Equals_DifferentFamily_TestData()
{
yield return new object[] { FontFamily.GenericMonospace, FontFamily.GenericSerif };
yield return new object[] { FontFamily.GenericSansSerif, FontFamily.GenericSerif };
yield return new object[] { FontFamily.GenericSansSerif, FontFamily.GenericMonospace };
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(FontFamily_Equals_SameFamily_TestData))]
public void Font_Equals_SameFontFamily(FontFamily fontFamily, float size)
{
using (var font1 = new Font(fontFamily, size))
using (var font2 = new Font(fontFamily, size))
{
Assert.True(font1.Equals(font2));
}
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(FontFamily_Equals_DifferentFamily_TestData))]
public void Font_Equals_DifferentFontFamily(FontFamily fontFamily1, FontFamily fontFamily2)
{
using (var font1 = new Font(fontFamily1, 9))
using (var font2 = new Font(fontFamily2, 9))
{
// In some Linux distros all the default fonts live under the same family (Fedora, Centos, Redhat)
if (font1.FontFamily.GetHashCode() != font2.FontFamily.GetHashCode())
Assert.False(font1.Equals(font2));
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void FontFamily_Equals_NullObject()
{
FontFamily nullFamily = null;
Assert.False(FontFamily.GenericMonospace.Equals(nullFamily));
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_TestData))]
public void Ctor_Family_Size(FontFamily fontFamily, float emSize)
{
try
{
using (var font = new Font(fontFamily, emSize))
{
VerifyFont(font, fontFamily.Name, emSize, FontStyle.Regular, GraphicsUnit.Point, 1, false);
}
}
finally
{
fontFamily.Dispose();
}
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_TestData))]
public void Ctor_FamilyName_Size(FontFamily fontFamily, float emSize)
{
try
{
using (var font = new Font(fontFamily.Name, emSize))
{
VerifyFont(font, fontFamily.Name, emSize, FontStyle.Regular, GraphicsUnit.Point, 1, false);
}
}
finally
{
fontFamily.Dispose();
}
}
public static IEnumerable<object[]> Ctor_Family_Size_Style_TestData()
{
yield return new object[] { FontFamily.GenericMonospace, 1, FontStyle.Bold };
yield return new object[] { FontFamily.GenericSerif, 2, FontStyle.Italic };
yield return new object[] { FontFamily.GenericSansSerif, 3, FontStyle.Regular };
yield return new object[] { FontFamily.GenericSerif, 4, FontStyle.Strikeout };
yield return new object[] { FontFamily.GenericSerif, float.MaxValue, FontStyle.Underline };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)(-1) };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MinValue };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MaxValue };
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_Style_TestData))]
public void Ctor_Family_Size_Style(FontFamily fontFamily, float emSize, FontStyle style)
{
try
{
using (var font = new Font(fontFamily, emSize, style))
{
VerifyFont(font, fontFamily.Name, emSize, style, GraphicsUnit.Point, 1, false);
}
}
finally
{
fontFamily.Dispose();
}
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_Style_TestData))]
public void Ctor_FamilyName_Size_Style(FontFamily fontFamily, float emSize, FontStyle style)
{
try
{
using (var font = new Font(fontFamily.Name, emSize, style))
{
VerifyFont(font, fontFamily.Name, emSize, style, GraphicsUnit.Point, 1, false);
}
}
finally
{
fontFamily.Dispose();
}
}
public static IEnumerable<object[]> Ctor_Family_Size_Unit_TestData()
{
yield return new object[] { FontFamily.GenericMonospace, 1, GraphicsUnit.Document };
yield return new object[] { FontFamily.GenericSerif, 2, GraphicsUnit.Inch };
yield return new object[] { FontFamily.GenericSansSerif, 3, GraphicsUnit.Millimeter };
yield return new object[] { FontFamily.GenericSerif, 4, GraphicsUnit.Point };
yield return new object[] { FontFamily.GenericSerif, float.MaxValue, GraphicsUnit.Pixel };
yield return new object[] { FontFamily.GenericSerif, 16, GraphicsUnit.World };
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_Unit_TestData))]
public void Ctor_Family_Size_Unit(FontFamily fontFamily, float emSize, GraphicsUnit unit)
{
try
{
using (var font = new Font(fontFamily, emSize, unit))
{
VerifyFont(font, fontFamily.Name, emSize, FontStyle.Regular, unit, 1, false);
}
}
finally
{
fontFamily.Dispose();
}
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_Unit_TestData))]
public void Ctor_FamilyName_Size_Unit(FontFamily fontFamily, float emSize, GraphicsUnit unit)
{
try
{
using (var font = new Font(fontFamily.Name, emSize, unit))
{
VerifyFont(font, fontFamily.Name, emSize, FontStyle.Regular, unit, 1, false);
}
}
finally
{
fontFamily.Dispose();
}
}
public static IEnumerable<object[]> Ctor_Family_Size_Style_Unit_TestData()
{
yield return new object[] { FontFamily.GenericMonospace, 1, FontStyle.Bold, GraphicsUnit.Document };
yield return new object[] { FontFamily.GenericSerif, 2, FontStyle.Italic, GraphicsUnit.Inch };
yield return new object[] { FontFamily.GenericSansSerif, 3, FontStyle.Regular, GraphicsUnit.Millimeter };
yield return new object[] { FontFamily.GenericSerif, 4, FontStyle.Strikeout, GraphicsUnit.Point };
yield return new object[] { FontFamily.GenericSerif, float.MaxValue, FontStyle.Underline, GraphicsUnit.Pixel };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)(-1), GraphicsUnit.World };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MinValue, GraphicsUnit.Millimeter };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MaxValue, GraphicsUnit.Millimeter };
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_Style_Unit_TestData))]
public void Ctor_Family_Size_Style_Unit(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit)
{
try
{
using (var font = new Font(fontFamily, emSize, style, unit))
{
VerifyFont(font, fontFamily.Name, emSize, style, unit, 1, false);
}
}
finally
{
fontFamily.Dispose();
}
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_Style_Unit_TestData))]
public void Ctor_FamilyName_Size_Style_Unit(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit)
{
try
{
using (var font = new Font(fontFamily.Name, emSize, style, unit))
{
VerifyFont(font, fontFamily.Name, emSize, style, unit, 1, false);
}
}
finally
{
fontFamily.Dispose();
}
}
public static IEnumerable<object[]> Ctor_Family_Size_Style_Unit_GdiCharSet_TestData()
{
yield return new object[] { FontFamily.GenericMonospace, 1, FontStyle.Bold, GraphicsUnit.Document, 0 };
yield return new object[] { FontFamily.GenericSerif, 2, FontStyle.Italic, GraphicsUnit.Inch, 1 };
yield return new object[] { FontFamily.GenericSansSerif, 3, FontStyle.Regular, GraphicsUnit.Millimeter, 255 };
yield return new object[] { FontFamily.GenericSerif, 4, FontStyle.Strikeout, GraphicsUnit.Point, 10 };
yield return new object[] { FontFamily.GenericSerif, float.MaxValue, FontStyle.Underline, GraphicsUnit.Pixel, 10 };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)(-1), GraphicsUnit.World, 8 };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MinValue, GraphicsUnit.Millimeter, 127 };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MaxValue, GraphicsUnit.Millimeter, 200 };
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_Style_Unit_GdiCharSet_TestData))]
public void Ctor_Family_Size_Style_Unit_GdiCharSet(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)
{
try
{
using (var font = new Font(fontFamily, emSize, style, unit, gdiCharSet))
{
VerifyFont(font, fontFamily.Name, emSize, style, unit, gdiCharSet, false);
}
}
finally
{
fontFamily.Dispose();
}
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_Style_Unit_GdiCharSet_TestData))]
public void Ctor_FamilyName_Size_Style_Unit_GdiCharSet(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)
{
try
{
using (var font = new Font(fontFamily.Name, emSize, style, unit, gdiCharSet))
{
VerifyFont(font, fontFamily.Name, emSize, style, unit, gdiCharSet, false);
}
}
finally
{
fontFamily.Dispose();
}
}
public static IEnumerable<object[]> Ctor_Family_Size_Style_Unit_GdiCharSet_GdiVerticalFont_TestData()
{
yield return new object[] { FontFamily.GenericMonospace, 1, FontStyle.Bold, GraphicsUnit.Document, 0, true };
yield return new object[] { FontFamily.GenericSerif, 2, FontStyle.Italic, GraphicsUnit.Inch, 1, false };
yield return new object[] { FontFamily.GenericSansSerif, 3, FontStyle.Regular, GraphicsUnit.Millimeter, 255, true };
yield return new object[] { FontFamily.GenericSerif, 4, FontStyle.Strikeout, GraphicsUnit.Point, 10, false };
yield return new object[] { FontFamily.GenericSerif, float.MaxValue, FontStyle.Underline, GraphicsUnit.Pixel, 10, true };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)(-1), GraphicsUnit.World, 8, false };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MinValue, GraphicsUnit.Millimeter, 127, true };
yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MaxValue, GraphicsUnit.Millimeter, 200, false };
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_Style_Unit_GdiCharSet_GdiVerticalFont_TestData))]
public void Ctor_Family_Size_Style_Unit_GdiCharSet_GdiVerticalFont(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
try
{
using (var font = new Font(fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont))
{
VerifyFont(font, fontFamily.Name, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
}
finally
{
fontFamily.Dispose();
}
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Ctor_Family_Size_Style_Unit_GdiCharSet_GdiVerticalFont_TestData))]
public void Ctor_FamilyName_Size_Style_Unit_GdiCharSet_GdiVerticalFont(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
try
{
using (var font = new Font(fontFamily.Name, emSize, style, unit, gdiCharSet, gdiVerticalFont))
{
VerifyFont(font, fontFamily.Name, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
}
finally
{
fontFamily.Dispose();
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Ctor_FamilyNamePrefixedWithAtSign_StripsSign()
{
using (FontFamily family = FontFamily.GenericMonospace)
using (var font = new Font($"@{family.Name}", 10))
{
Assert.Equal(family.Name, font.Name);
Assert.Equal($"@{family.Name}", font.OriginalFontName);
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Ctor_NullFont_ThrowsNullReferenceException()
{
Assert.Throws<NullReferenceException>(() => new Font(null, FontStyle.Regular));
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Ctor_DisposedFont_Success()
{
using (FontFamily family = FontFamily.GenericSerif)
{
var font = new Font(family, 10);
font.Dispose();
using (var copy = new Font(font, FontStyle.Italic))
{
Assert.Equal(FontStyle.Italic, copy.Style);
Assert.Equal(family.Name, copy.Name);
}
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Ctor_NullFamily_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10));
AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10, FontStyle.Italic));
AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10, GraphicsUnit.Display));
AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10, FontStyle.Italic, GraphicsUnit.Display));
AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10, FontStyle.Italic, GraphicsUnit.Display, 10));
AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10, FontStyle.Italic, GraphicsUnit.Display, 10, gdiVerticalFont: true));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Ctor_DisposedFamily_ThrowsArgumentException()
{
FontFamily family = FontFamily.GenericSansSerif;
family.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, GraphicsUnit.Display));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, GraphicsUnit.Display));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, GraphicsUnit.Display, 10));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, GraphicsUnit.Display, 10, gdiVerticalFont: true));
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData(-1)]
[InlineData(0)]
[InlineData(float.NaN)]
[InlineData(float.NegativeInfinity)]
[InlineData(float.PositiveInfinity)]
public void Ctor_InvalidEmSize_ThrowsArgumentException(float emSize)
{
using (FontFamily family = FontFamily.GenericSansSerif)
{
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize, FontStyle.Italic));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize, FontStyle.Italic));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize, GraphicsUnit.Document));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize, GraphicsUnit.Document));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize, FontStyle.Italic, GraphicsUnit.Document));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize, FontStyle.Italic, GraphicsUnit.Document));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize, FontStyle.Italic, GraphicsUnit.Document, 10));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize, FontStyle.Italic, GraphicsUnit.Document, 10));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize, FontStyle.Italic, GraphicsUnit.Document, 10, gdiVerticalFont: true));
AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize, FontStyle.Italic, GraphicsUnit.Document, 10, gdiVerticalFont: true));
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData(GraphicsUnit.Display)]
[InlineData(GraphicsUnit.World - 1)]
[InlineData(GraphicsUnit.Millimeter + 1)]
public void Ctor_InvalidUnit_ThrowsArgumentException(GraphicsUnit unit)
{
using (FontFamily family = FontFamily.GenericSansSerif)
{
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, unit));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family.Name, 10, unit));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, unit));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family.Name, 10, FontStyle.Italic, unit));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, unit, 10));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family.Name, 10, FontStyle.Italic, unit, 10));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, unit, 10, gdiVerticalFont: true));
AssertExtensions.Throws<ArgumentException>(null, () => new Font(family.Name, 10, FontStyle.Italic, unit, 10, gdiVerticalFont: true));
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Clone_Invoke_ReturnsExpected()
{
using (FontFamily family = FontFamily.GenericSansSerif)
using (var font = new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true))
{
Font clone = Assert.IsType<Font>(font.Clone());
Assert.NotSame(font, clone);
Assert.Equal(font.Name, clone.FontFamily.Name);
Assert.Equal(font.Size, clone.Size);
Assert.Equal(font.Style, clone.Style);
Assert.Equal(font.Unit, clone.Unit);
Assert.Equal(font.GdiCharSet, clone.GdiCharSet);
Assert.Equal(font.GdiVerticalFont, clone.GdiVerticalFont);
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Clone_DisposedFont_ThrowsArgumentException()
{
using (FontFamily family = FontFamily.GenericSansSerif)
{
var font = new Font(family, 10);
font.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => font.Clone());
}
}
public static IEnumerable<object[]> Equals_TestData()
{
FontFamily family = FontFamily.GenericSansSerif;
var font = new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true);
yield return new object[] { font, font, true };
// [ActiveIssue(20884, TestPlatforms.AnyUnix)]
if (PlatformDetection.IsWindows)
{
yield return new object[] { font.Clone(), new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true), false };
}
yield return new object[] { font.Clone(), new Font(family, 9, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true), false };
yield return new object[] { font.Clone(), new Font(family, 10, FontStyle.Italic, GraphicsUnit.Millimeter, 10, gdiVerticalFont: true), false };
yield return new object[] { font.Clone(), new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 9, gdiVerticalFont: true), false };
yield return new object[] { font.Clone(), new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: false), false };
yield return new object[] { new Font(family, 10), new object(), false };
yield return new object[] { new Font(family, 10), null, false };
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Equals_TestData))]
public void Equals_Other_ReturnsExpected(Font font, object other, bool expected)
{
// Windows7 GDI+ returns different results than later versions of Windows.
if (PlatformDetection.IsWindows7)
{
return;
}
try
{
Assert.Equal(expected, font.Equals(other));
Assert.Equal(font.GetHashCode(), font.GetHashCode());
}
finally
{
font.Dispose();
if (other is Font otherFont && !ReferenceEquals(font, otherFont))
{
otherFont.Dispose();
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void FromHdc_ZeroHdc_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => Font.FromHdc(IntPtr.Zero));
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void FromHdc_GraphicsHdc_ThrowsArgumentException()
{
using (var image = new Bitmap(10, 10))
using (Graphics graphics = Graphics.FromImage(image))
{
IntPtr hdc = graphics.GetHdc();
try
{
AssertExtensions.Throws<ArgumentException>(null, () => Font.FromHdc(hdc));
}
finally
{
graphics.ReleaseHdc();
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void FromHfont_Zero_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => Font.FromHfont(IntPtr.Zero));
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetHeight_Parameterless_ReturnsExpected()
{
using (FontFamily family = FontFamily.GenericSansSerif)
using (var font = new Font(family, 10))
{
float height = font.GetHeight();
AssertExtensions.GreaterThan(height, 0);
Assert.Equal((int)Math.Ceiling(height), font.Height);
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetHeight_Graphics_ReturnsExpected()
{
using (FontFamily family = FontFamily.GenericSansSerif)
using (var font = new Font(family, 10))
using (var image = new Bitmap(10, 10))
using (Graphics graphics = Graphics.FromImage(image))
{
Assert.Equal(font.GetHeight(graphics.DpiY), font.GetHeight(graphics), 5);
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData(0, 0)]
[InlineData(-1, -0.1571995)]
[InlineData(1, 0.1571995)]
[InlineData(float.NaN, float.NaN)]
[InlineData(float.PositiveInfinity, float.PositiveInfinity)]
[InlineData(float.NegativeInfinity, float.NegativeInfinity)]
public void GetHeight_Dpi_ReturnsExpected(float dpi, float expected)
{
using (FontFamily family = FontFamily.GenericSansSerif)
using (var font = new Font(family, 10))
{
Assert.Equal(expected, font.GetHeight(dpi), 5);
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetHeight_NullGraphics_ThrowsArgumentNullException()
{
using (FontFamily family = FontFamily.GenericSansSerif)
using (var font = new Font(family, 10))
{
AssertExtensions.Throws<ArgumentNullException>("graphics", () => font.GetHeight(null));
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
[ActiveIssue(22571)] // PR issue, This causes an AccessViolation in GDI+.
public void GetHeight_DisposedGraphics_ThrowsArgumentException()
{
using (FontFamily family = FontFamily.GenericMonospace)
using (var font = new Font(family, 10))
using (var image = new Bitmap(10, 10))
{
Graphics graphics = Graphics.FromImage(image);
graphics.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => font.GetHeight(graphics));
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void GetHeight_Disposed_ThrowsArgumentException()
{
using (FontFamily family = FontFamily.GenericSansSerif)
using (var image = new Bitmap(10, 10))
using (Graphics graphics = Graphics.FromImage(image))
{
var font = new Font(family, 10);
font.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => font.GetHeight());
AssertExtensions.Throws<ArgumentException>(null, () => font.GetHeight(10));
AssertExtensions.Throws<ArgumentException>(null, () => font.GetHeight(graphics));
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData(FontStyle.Bold, int.MinValue, 0)]
[InlineData(FontStyle.Bold, -2147483099, 0)]
[InlineData(FontStyle.Regular, -2147483098, 0)]
[InlineData(FontStyle.Regular, -1, 0)]
[InlineData(FontStyle.Regular, 0, 0)]
[InlineData(FontStyle.Regular, 300, 0)]
[InlineData(FontStyle.Regular, 400, 0)]
[InlineData(FontStyle.Strikeout | FontStyle.Underline | FontStyle.Italic, 549, 1)]
[InlineData(FontStyle.Strikeout | FontStyle.Underline | FontStyle.Italic | FontStyle.Bold, 550, 1)]
[InlineData(FontStyle.Strikeout | FontStyle.Underline | FontStyle.Bold | FontStyle.Italic, int.MaxValue, 1)]
public void FromLogFont_ValidLogFont_ReturnsExpected(FontStyle fontStyle, int weight, byte charSet)
{
// The boundary values of the weight that is considered Bold are different between Windows 7 and Windows 8.
if (PlatformDetection.IsWindows7 || PlatformDetection.IsWindows8x)
{
return;
}
using (FontFamily family = FontFamily.GenericMonospace)
{
var logFont = new LOGFONT
{
lfFaceName = family.Name,
lfWeight = weight,
lfItalic = (fontStyle & FontStyle.Italic) != 0 ? (byte)1 : (byte)0,
lfStrikeOut = (fontStyle & FontStyle.Strikeout) != 0 ? (byte)1 : (byte)0,
lfUnderline = (fontStyle & FontStyle.Underline) != 0 ? (byte)1 : (byte)0,
lfCharSet = charSet
};
using (Font font = Font.FromLogFont(logFont))
{
VerifyFont(font, family.Name, font.Size, fontStyle, GraphicsUnit.World, charSet, expectedGdiVerticalFont: false);
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void FromLogFont_NullLogFont_ThrowsArgumentNullException()
{
using (var image = new Bitmap(10, 10))
using (Graphics graphics = Graphics.FromImage(image))
{
IntPtr hdc = graphics.GetHdc();
try
{
if (PlatformDetection.IsFullFramework)
{
AssertExtensions.Throws<ArgumentException>(null, () => Font.FromLogFont(null));
AssertExtensions.Throws<ArgumentException>(null, () => Font.FromLogFont(null, hdc));
}
else
{
AssertExtensions.Throws<ArgumentNullException>("lf", () => Font.FromLogFont(null));
AssertExtensions.Throws<ArgumentNullException>("lf", () => Font.FromLogFont(null, hdc));
}
}
finally
{
graphics.ReleaseHdc();
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void FromLogFont_InvalidLogFont_ThrowsArgumentException()
{
using (var image = new Bitmap(10, 10))
using (Graphics graphics = Graphics.FromImage(image))
{
IntPtr hdc = graphics.GetHdc();
try
{
var logFont = new LOGFONT();
AssertExtensions.Throws<ArgumentException>(null, () => Font.FromLogFont(logFont));
AssertExtensions.Throws<ArgumentException>(null, () => Font.FromLogFont(logFont, hdc));
}
finally
{
graphics.ReleaseHdc();
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void FromLogFont_UnblittableStruct()
{
const byte OUT_TT_ONLY_PRECIS = 7;
using (var image = new Bitmap(10, 10))
using (Graphics graphics = Graphics.FromImage(image))
{
IntPtr hdc = graphics.GetHdc();
try
{
var logFont = new UnblittableLOGFONT
{
lfOutPrecision = OUT_TT_ONLY_PRECIS
};
using (Font font = Font.FromLogFont(logFont))
{
Assert.NotNull(font);
Assert.NotEmpty(font.Name);
}
}
finally
{
graphics.ReleaseHdc();
}
}
}
[Serializable()]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct UnblittableLOGFONT
{
public int lfHeight;
public int lfWidth;
public int lfEscapement;
public int lfOrientation;
public int lfWeight;
public byte lfItalic;
public byte lfUnderline;
public byte lfStrikeOut;
public byte lfCharSet;
public byte lfOutPrecision;
public byte lfClipPrecision;
public byte lfQuality;
public byte lfPitchAndFamily;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string lfFaceName;
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData(GraphicsUnit.Document)]
[InlineData(GraphicsUnit.Inch)]
[InlineData(GraphicsUnit.Millimeter)]
[InlineData(GraphicsUnit.Pixel)]
[InlineData(GraphicsUnit.Point)]
[InlineData(GraphicsUnit.World)]
public void SizeInPoints_Get_ReturnsExpected(GraphicsUnit unit)
{
using (FontFamily family = FontFamily.GenericMonospace)
using (var font = new Font(family, 10, unit))
{
float sizeInPoints = font.SizeInPoints;
if (unit == GraphicsUnit.Point)
{
Assert.Equal(font.Size, sizeInPoints);
}
else
{
Assert.True(sizeInPoints > 0);
}
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData(FontStyle.Strikeout | FontStyle.Bold | FontStyle.Italic, 255, true, "@", 700)]
[InlineData(FontStyle.Regular, 0, false, "", 400)]
[InlineData(FontStyle.Regular, 10, false, "", 400)]
public void ToLogFont_Invoke_ReturnsExpected(FontStyle fontStyle, byte gdiCharSet, bool gdiVerticalFont, string expectedNamePrefix, int expectedWeight)
{
using (FontFamily family = FontFamily.GenericMonospace)
using (var font = new Font(family, 10, fontStyle, GraphicsUnit.Point, gdiCharSet, gdiVerticalFont))
{
var logFont = new LOGFONT();
font.ToLogFont(logFont);
Assert.Equal(-13, logFont.lfHeight);
Assert.Equal(0, logFont.lfWidth);
Assert.Equal(0, logFont.lfEscapement);
Assert.Equal(0, logFont.lfOrientation);
Assert.Equal(expectedWeight, logFont.lfWeight);
Assert.Equal(font.Italic ? 1 : 0, logFont.lfItalic);
Assert.Equal(font.Underline ? 1 : 0, logFont.lfUnderline);
Assert.Equal(font.Strikeout ? 1 : 0, logFont.lfStrikeOut);
Assert.Equal(font.GdiCharSet, logFont.lfCharSet);
Assert.Equal(0, logFont.lfOutPrecision);
Assert.Equal(0, logFont.lfClipPrecision);
Assert.Equal(0, logFont.lfQuality);
Assert.Equal(0, logFont.lfPitchAndFamily);
Assert.Equal($"{expectedNamePrefix}{family.Name}", logFont.lfFaceName);
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData(TextRenderingHint.SystemDefault)]
[InlineData(TextRenderingHint.AntiAlias)]
[InlineData(TextRenderingHint.AntiAliasGridFit)]
[InlineData(TextRenderingHint.SingleBitPerPixel)]
[InlineData(TextRenderingHint.SingleBitPerPixelGridFit)]
[InlineData(TextRenderingHint.ClearTypeGridFit)]
public void ToLogFont_InvokeGraphics_ReturnsExpected(TextRenderingHint textRenderingHint)
{
using (FontFamily family = FontFamily.GenericMonospace)
using (var font = new Font(family, 10))
using (var image = new Bitmap(10, 10))
using (Graphics graphics = Graphics.FromImage(image))
{
graphics.TextRenderingHint = textRenderingHint;
var logFont = new LOGFONT();
font.ToLogFont(logFont, graphics);
Assert.Equal(-13, logFont.lfHeight);
Assert.Equal(0, logFont.lfWidth);
Assert.Equal(0, logFont.lfEscapement);
Assert.Equal(0, logFont.lfOrientation);
Assert.Equal(400, logFont.lfWeight);
Assert.Equal(0, logFont.lfItalic);
Assert.Equal(0, logFont.lfUnderline);
Assert.Equal(0, logFont.lfStrikeOut);
Assert.Equal(1, logFont.lfCharSet);
Assert.Equal(0, logFont.lfOutPrecision);
Assert.Equal(0, logFont.lfClipPrecision);
Assert.Equal(0, logFont.lfQuality);
Assert.Equal(0, logFont.lfPitchAndFamily);
Assert.Equal(family.Name, logFont.lfFaceName);
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "AV Exception is wrapped in a TargetInvocationException in the .NET Framework.")]
public void ToLogFont_NullLogFont_ThrowsArgumentNullException()
{
using (FontFamily family = FontFamily.GenericMonospace)
using (var font = new Font(family, 10))
using (var image = new Bitmap(10, 10))
using (Graphics graphics = Graphics.FromImage(image))
{
Assert.Throws<ArgumentNullException>(() => font.ToLogFont(null));
Assert.Throws<ArgumentNullException>(() => font.ToLogFont(null, graphics));
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ToLogFont_NullGraphics_ThrowsArgumentNullException()
{
using (FontFamily family = FontFamily.GenericMonospace)
using (var font = new Font(family, 10))
{
AssertExtensions.Throws<ArgumentNullException>("graphics", () => font.ToLogFont(new LOGFONT(), null));
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ToLogFont_DisposedGraphics_ThrowsArgumentException()
{
using (FontFamily family = FontFamily.GenericMonospace)
using (var font = new Font(family, 10))
using (var image = new Bitmap(10, 10))
{
Graphics graphics = Graphics.FromImage(image);
graphics.Dispose();
Assert.Throws<ArgumentException>(() => font.ToLogFont(new LOGFONT(), graphics));
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class LOGFONT
{
public int lfHeight;
public int lfWidth;
public int lfEscapement;
public int lfOrientation;
public int lfWeight;
public byte lfItalic;
public byte lfUnderline;
public byte lfStrikeOut;
public byte lfCharSet;
public byte lfOutPrecision;
public byte lfClipPrecision;
public byte lfQuality;
public byte lfPitchAndFamily;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string lfFaceName;
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ToHfont_SimpleFont_Roundtrips()
{
using (FontFamily family = FontFamily.GenericSansSerif)
using (var font = new Font(family, 10))
{
IntPtr hfont = font.ToHfont();
Assert.NotEqual(IntPtr.Zero, hfont);
Assert.NotEqual(hfont, font.ToHfont());
Font newFont = Font.FromHfont(hfont);
Assert.Equal(font.Name, newFont.Name);
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ToHfont_ComplicatedFont_DoesNotRoundtrip()
{
using (FontFamily family = FontFamily.GenericSansSerif)
using (var font = new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true))
{
IntPtr hfont = font.ToHfont();
Assert.NotEqual(IntPtr.Zero, hfont);
Assert.NotEqual(hfont, font.ToHfont());
Font newFont = Font.FromHfont(hfont);
Assert.NotEqual(font.Name, newFont.Name);
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ToHfont_Disposed_ThrowsArgumentException()
{
using (FontFamily family = FontFamily.GenericSansSerif)
using (var image = new Bitmap(10, 10))
using (Graphics graphics = Graphics.FromImage(image))
{
var font = new Font(family, 10);
font.Dispose();
AssertExtensions.Throws<ArgumentException>(null, () => font.ToHfont());
}
}
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ToString_Invoke_ReturnsExpected()
{
using (FontFamily family = FontFamily.GenericSansSerif)
using (var font = new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true))
{
Assert.Equal($"[Font: Name={family.Name}, Size=10, Units=4, GdiCharSet=10, GdiVerticalFont=True]", font.ToString());
}
}
private static void VerifyFont(Font font, string expectedName, float expectedEmSize, FontStyle expectedStyle, GraphicsUnit expectedUnit, byte expectedGdiCharset, bool expectedGdiVerticalFont)
{
Assert.Equal(expectedName, font.Name);
Assert.Equal(expectedEmSize, font.Size);
Assert.Equal(expectedStyle, font.Style);
Assert.Equal((expectedStyle & FontStyle.Bold) != 0, font.Bold);
Assert.Equal((expectedStyle & FontStyle.Italic) != 0, font.Italic);
Assert.Equal((expectedStyle & FontStyle.Strikeout) != 0, font.Strikeout);
Assert.Equal((expectedStyle & FontStyle.Underline) != 0, font.Underline);
Assert.Equal(expectedUnit, font.Unit);
Assert.Equal(expectedGdiCharset, font.GdiCharSet);
Assert.Equal(expectedGdiVerticalFont, font.GdiVerticalFont);
Assert.False(font.IsSystemFont);
Assert.Empty(font.SystemFontName);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpSelectionValidator : SelectionValidator
{
public CSharpSelectionValidator(
SemanticDocument document,
TextSpan textSpan,
OptionSet options) :
base(document, textSpan, options)
{
}
public override async Task<SelectionResult> GetValidSelectionAsync(CancellationToken cancellationToken)
{
if (!this.ContainsValidSelection)
{
return NullSelection;
}
var text = this.SemanticDocument.Text;
var root = this.SemanticDocument.Root;
var model = this.SemanticDocument.SemanticModel;
// go through pipe line and calculate information about the user selection
var selectionInfo = GetInitialSelectionInfo(root, text, cancellationToken);
selectionInfo = AssignInitialFinalTokens(selectionInfo, root, cancellationToken);
selectionInfo = AdjustFinalTokensBasedOnContext(selectionInfo, model, cancellationToken);
selectionInfo = AssignFinalSpan(selectionInfo, text, cancellationToken);
selectionInfo = ApplySpecialCases(selectionInfo, text, cancellationToken);
selectionInfo = CheckErrorCasesAndAppendDescriptions(selectionInfo, root, cancellationToken);
// there was a fatal error that we couldn't even do negative preview, return error result
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return new ErrorSelectionResult(selectionInfo.Status);
}
var controlFlowSpan = GetControlFlowSpan(selectionInfo);
if (!selectionInfo.SelectionInExpression)
{
var statementRange = GetStatementRangeContainedInSpan<StatementSyntax>(root, controlFlowSpan, cancellationToken);
if (statementRange == null)
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.CantDetermineValidRangeOfStatements));
return new ErrorSelectionResult(selectionInfo.Status);
}
var isFinalSpanSemanticallyValid = IsFinalSpanSemanticallyValidSpan(model, controlFlowSpan, statementRange, cancellationToken);
if (!isFinalSpanSemanticallyValid)
{
// check control flow only if we are extracting statement level, not expression
// level. you can not have goto that moves control out of scope in expression level
// (even in lambda)
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.NotAllCodePathReturns));
}
}
return await CSharpSelectionResult.CreateAsync(
selectionInfo.Status,
selectionInfo.OriginalSpan,
selectionInfo.FinalSpan,
this.Options,
selectionInfo.SelectionInExpression,
this.SemanticDocument,
selectionInfo.FirstTokenInFinalSpan,
selectionInfo.LastTokenInFinalSpan,
cancellationToken).ConfigureAwait(false);
}
private SelectionInfo ApplySpecialCases(SelectionInfo selectionInfo, SourceText text, CancellationToken cancellationToken)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion() || !selectionInfo.SelectionInExpression)
{
return selectionInfo;
}
var expressionNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
if (!expressionNode.IsAnyAssignExpression())
{
return selectionInfo;
}
var assign = (AssignmentExpressionSyntax)expressionNode;
// make sure there is a visible token at right side expression
if (assign.Right.GetLastToken().Kind() == SyntaxKind.None)
{
return selectionInfo;
}
return AssignFinalSpan(selectionInfo.With(s => s.FirstTokenInFinalSpan = assign.Right.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = assign.Right.GetLastToken(includeZeroWidth: true)),
text, cancellationToken);
}
private TextSpan GetControlFlowSpan(SelectionInfo selectionInfo)
{
return TextSpan.FromBounds(selectionInfo.FirstTokenInFinalSpan.SpanStart, selectionInfo.LastTokenInFinalSpan.Span.End);
}
private SelectionInfo AdjustFinalTokensBasedOnContext(
SelectionInfo selectionInfo,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
// don't need to adjust anything if it is multi-statements case
if (!selectionInfo.SelectionInExpression && !selectionInfo.SelectionInSingleStatement)
{
return selectionInfo;
}
// get the node that covers the selection
var node = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
var validNode = Check(semanticModel, node, cancellationToken);
if (validNode)
{
return selectionInfo;
}
var firstValidNode = node.GetAncestors<SyntaxNode>().FirstOrDefault(n => Check(semanticModel, n, cancellationToken));
if (firstValidNode == null)
{
// couldn't find any valid node
return selectionInfo.WithStatus(s => new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.SelectionDoesNotContainAValidNode))
.With(s => s.FirstTokenInFinalSpan = default(SyntaxToken))
.With(s => s.LastTokenInFinalSpan = default(SyntaxToken));
}
firstValidNode = (firstValidNode.Parent is ExpressionStatementSyntax) ? firstValidNode.Parent : firstValidNode;
return selectionInfo.With(s => s.SelectionInExpression = firstValidNode is ExpressionSyntax)
.With(s => s.SelectionInSingleStatement = firstValidNode is StatementSyntax)
.With(s => s.FirstTokenInFinalSpan = firstValidNode.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = firstValidNode.GetLastToken(includeZeroWidth: true));
}
private SelectionInfo GetInitialSelectionInfo(SyntaxNode root, SourceText text, CancellationToken cancellationToken)
{
var adjustedSpan = GetAdjustedSpan(text, this.OriginalSpan);
var firstTokenInSelection = root.FindTokenOnRightOfPosition(adjustedSpan.Start, includeSkipped: false);
var lastTokenInSelection = root.FindTokenOnLeftOfPosition(adjustedSpan.End, includeSkipped: false);
if (firstTokenInSelection.Kind() == SyntaxKind.None || lastTokenInSelection.Kind() == SyntaxKind.None)
{
return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.InvalidSelection), OriginalSpan = adjustedSpan };
}
if (!adjustedSpan.Contains(firstTokenInSelection.Span) && !adjustedSpan.Contains(lastTokenInSelection.Span))
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.SelectionDoesNotContainAValidToken),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
if (!firstTokenInSelection.UnderValidContext() || !lastTokenInSelection.UnderValidContext())
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.NoValidSelectionToPerformExtraction),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
var commonRoot = firstTokenInSelection.GetCommonRoot(lastTokenInSelection);
if (commonRoot == null)
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.NoCommonRootNodeForExtraction),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
var selectionInExpression = commonRoot is ExpressionSyntax;
if (!selectionInExpression && !commonRoot.UnderValidContext())
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.NoValidSelectionToPerformExtraction),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
return new SelectionInfo
{
Status = OperationStatus.Succeeded,
OriginalSpan = adjustedSpan,
CommonRootFromOriginalSpan = commonRoot,
SelectionInExpression = selectionInExpression,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
private SelectionInfo CheckErrorCasesAndAppendDescriptions(SelectionInfo selectionInfo, SyntaxNode root, CancellationToken cancellationToken)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
if (selectionInfo.FirstTokenInFinalSpan.IsMissing || selectionInfo.LastTokenInFinalSpan.IsMissing)
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.ContainsInvalidSelection));
}
// get the node that covers the selection
var commonNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
if ((selectionInfo.SelectionInExpression || selectionInfo.SelectionInSingleStatement) && commonNode.HasDiagnostics())
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.TheSelectionContainsSyntacticErrors));
}
var tokens = root.DescendantTokens(selectionInfo.FinalSpan);
if (tokens.ContainPreprocessorCrossOver(selectionInfo.FinalSpan))
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.SelectionCanNotCrossOverPreprocessorDirectives));
}
// TODO : check whether this can be handled by control flow analysis engine
if (tokens.Any(t => t.Kind() == SyntaxKind.YieldKeyword))
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.SelectionCanNotContainAYieldStatement));
}
// TODO : check behavior of control flow analysis engine around exception and exception handling.
if (tokens.ContainArgumentlessThrowWithoutEnclosingCatch(selectionInfo.FinalSpan))
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.SelectionCanNotContainThrowStatement));
}
if (selectionInfo.SelectionInExpression && commonNode.PartOfConstantInitializerExpression())
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.SelectionCanNotBePartOfConstInitializerExpr));
}
if (commonNode.IsUnsafeContext())
{
selectionInfo = selectionInfo.WithStatus(s => s.With(s.Flag, CSharpFeaturesResources.TheSelectedCodeIsInsideAnUnsafeContext));
}
var selectionChanged = selectionInfo.FirstTokenInOriginalSpan != selectionInfo.FirstTokenInFinalSpan || selectionInfo.LastTokenInOriginalSpan != selectionInfo.LastTokenInFinalSpan;
if (selectionChanged)
{
selectionInfo = selectionInfo.WithStatus(s => s.MarkSuggestion());
}
return selectionInfo;
}
private SelectionInfo AssignInitialFinalTokens(SelectionInfo selectionInfo, SyntaxNode root, CancellationToken cancellationToken)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
if (selectionInfo.SelectionInExpression)
{
// simple expression case
return selectionInfo.With(s => s.FirstTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetLastToken(includeZeroWidth: true));
}
var range = GetStatementRangeContainingSpan<StatementSyntax>(
root, TextSpan.FromBounds(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.LastTokenInOriginalSpan.Span.End),
cancellationToken);
if (range == null)
{
return selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.NoValidStatementRangeToExtractOut));
}
var statement1 = (StatementSyntax)range.Item1;
var statement2 = (StatementSyntax)range.Item2;
if (statement1 == statement2)
{
// check one more time to see whether it is an expression case
var expression = selectionInfo.CommonRootFromOriginalSpan.GetAncestor<ExpressionSyntax>();
if (expression != null && statement1.Span.Contains(expression.Span))
{
return selectionInfo.With(s => s.SelectionInExpression = true)
.With(s => s.FirstTokenInFinalSpan = expression.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = expression.GetLastToken(includeZeroWidth: true));
}
// single statement case
return selectionInfo.With(s => s.SelectionInSingleStatement = true)
.With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = statement1.GetLastToken(includeZeroWidth: true));
}
// move only statements inside of the block
return selectionInfo.With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = statement2.GetLastToken(includeZeroWidth: true));
}
private SelectionInfo AssignFinalSpan(SelectionInfo selectionInfo, SourceText text, CancellationToken cancellationToken)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
// set final span
var start = (selectionInfo.FirstTokenInOriginalSpan == selectionInfo.FirstTokenInFinalSpan) ?
Math.Min(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.OriginalSpan.Start) :
selectionInfo.FirstTokenInFinalSpan.FullSpan.Start;
var end = (selectionInfo.LastTokenInOriginalSpan == selectionInfo.LastTokenInFinalSpan) ?
Math.Max(selectionInfo.LastTokenInOriginalSpan.Span.End, selectionInfo.OriginalSpan.End) :
selectionInfo.LastTokenInFinalSpan.FullSpan.End;
return selectionInfo.With(s => s.FinalSpan = GetAdjustedSpan(text, TextSpan.FromBounds(start, end)));
}
public override bool ContainsNonReturnExitPointsStatements(IEnumerable<SyntaxNode> jumpsOutOfRegion)
{
return jumpsOutOfRegion.Where(n => !(n is ReturnStatementSyntax)).Any();
}
public override IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode commonRoot, IEnumerable<SyntaxNode> jumpsOutOfRegion)
{
var returnStatements = jumpsOutOfRegion.Where(s => s is ReturnStatementSyntax);
var container = commonRoot.GetAncestorsOrThis<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault();
if (container == null)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var returnableConstructPairs = returnStatements.Select(r => Tuple.Create(r, r.GetAncestors<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault()))
.Where(p => p.Item2 != null);
// now filter return statements to only include the one under outmost container
return returnableConstructPairs.Where(p => p.Item2 == container).Select(p => p.Item1);
}
public override bool IsFinalSpanSemanticallyValidSpan(
SyntaxNode root, TextSpan textSpan,
IEnumerable<SyntaxNode> returnStatements, CancellationToken cancellationToken)
{
// return statement shouldn't contain any return value
if (returnStatements.Cast<ReturnStatementSyntax>().Any(r => r.Expression != null))
{
return false;
}
var lastToken = root.FindToken(textSpan.End);
if (lastToken.Kind() == SyntaxKind.None)
{
return false;
}
var container = lastToken.GetAncestors<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct());
if (container == null)
{
return false;
}
var body = container.GetBlockBody();
if (body == null)
{
return false;
}
// make sure that next token of the last token in the selection is the close braces of containing block
if (body.CloseBraceToken != lastToken.GetNextToken(includeZeroWidth: true))
{
return false;
}
// alright, for these constructs, it must be okay to be extracted
switch (container.Kind())
{
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
return true;
}
// now, only method is okay to be extracted out
var method = body.Parent as MethodDeclarationSyntax;
if (method == null)
{
return false;
}
// make sure this method doesn't have return type.
return method.ReturnType.TypeSwitch((PredefinedTypeSyntax p) => p.Keyword.Kind() == SyntaxKind.VoidKeyword);
}
private static TextSpan GetAdjustedSpan(SourceText text, TextSpan textSpan)
{
// beginning of a file
if (textSpan.IsEmpty || textSpan.End == 0)
{
return textSpan;
}
// if it is a start of new line, make it belong to previous line
var line = text.Lines.GetLineFromPosition(textSpan.End);
if (line.Start != textSpan.End)
{
return textSpan;
}
// get previous line
Contract.ThrowIfFalse(line.LineNumber > 0);
var previousLine = text.Lines[line.LineNumber - 1];
return TextSpan.FromBounds(textSpan.Start, previousLine.End);
}
private class SelectionInfo
{
public OperationStatus Status { get; set; }
public TextSpan OriginalSpan { get; set; }
public TextSpan FinalSpan { get; set; }
public SyntaxNode CommonRootFromOriginalSpan { get; set; }
public SyntaxToken FirstTokenInOriginalSpan { get; set; }
public SyntaxToken LastTokenInOriginalSpan { get; set; }
public SyntaxToken FirstTokenInFinalSpan { get; set; }
public SyntaxToken LastTokenInFinalSpan { get; set; }
public bool SelectionInExpression { get; set; }
public bool SelectionInSingleStatement { get; set; }
public SelectionInfo WithStatus(Func<OperationStatus, OperationStatus> statusGetter)
{
return With(s => s.Status = statusGetter(s.Status));
}
public SelectionInfo With(Action<SelectionInfo> valueSetter)
{
var newInfo = this.Clone();
valueSetter(newInfo);
return newInfo;
}
public SelectionInfo Clone()
{
return (SelectionInfo)this.MemberwiseClone();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.GrainDirectory;
using Orleans.Runtime;
using TestGrainInterfaces;
using Orleans.Internal;
using Orleans.TestingHost;
using Xunit;
using Xunit.Abstractions;
using Orleans.Hosting;
using Orleans.Configuration;
// ReSharper disable InconsistentNaming
namespace Tests.GeoClusterTests
{
// We need use ClientWrapper to load a client object in a new app domain.
// This allows us to create multiple clients that are connected to different silos.
[TestCategory("GeoCluster")]
public class GlobalSingleInstanceClusterTests : TestingClusterHost
{
public GlobalSingleInstanceClusterTests(ITestOutputHelper output) : base(output)
{
}
/// <summary>
/// Run all tests on a small configuration (two clusters, one silo each, one client each)
/// </summary>
/// <returns></returns>
[SkippableFact(Skip="https://github.com/dotnet/orleans/issues/4281"), TestCategory("Functional")]
public async Task All_Small()
{
await Setup_Clusters(false);
numGrains = 600;
await RunWithTimeout("IndependentCreation", 5000, IndependentCreation);
await RunWithTimeout("CreationRace", 10000, CreationRace);
await RunWithTimeout("ConflictResolution", 40000, ConflictResolution);
}
/// <summary>
/// Run all tests on a larger configuration (two clusters with 3 or 4 silos, respectively, and two clients each)
/// </summary>
/// <returns></returns>
[SkippableFact]
public async Task All_Large()
{
await Setup_Clusters(true);
numGrains = 2000;
await RunWithTimeout("IndependentCreation", 20000, IndependentCreation);
await RunWithTimeout("CreationRace", 60000, CreationRace);
await RunWithTimeout("ConflictResolution", 120000, ConflictResolution);
}
public class ClientWrapper : ClientWrapperBase
{
public static readonly Func<string, int, string, Action<IClientBuilder>, ClientWrapper> Factory =
(name, gwPort, clusterId, clientConfgirator) => new ClientWrapper(name, gwPort, clusterId, clientConfgirator);
public ClientWrapper(string name, int gatewayport, string clusterId, Action<IClientBuilder> clientConfigurator) : base(name, gatewayport, clusterId, clientConfigurator)
{
this.systemManagement = this.GrainFactory.GetGrain<IManagementGrain>(0);
}
public int CallGrain(int i)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
Task<int> toWait = grainRef.SayHelloAsync();
toWait.Wait();
return toWait.GetResult();
}
public void InjectMultiClusterConf(string[] clusters, string comment = "", bool checkForLaggingSilos = true)
{
systemManagement.InjectMultiClusterConfiguration(clusters, comment, checkForLaggingSilos).GetResult();
}
IManagementGrain systemManagement;
}
private Random random = new Random();
private int numGrains;
private string cluster0;
private string cluster1;
private ClientWrapper[] clients;
public class SiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.Configure<MultiClusterOptions>(options => options.GlobalSingleInstanceRetryInterval = TimeSpan.FromSeconds(5));
}
}
private async Task Setup_Clusters(bool largesetup)
{
await RunWithTimeout("Setup_Clusters", largesetup ? 120000 : 60000, async () =>
{
// use a random global service id for testing purposes
var globalserviceid = Guid.NewGuid();
// Create two clusters, each with a single silo.
cluster0 = "cluster0";
cluster1 = "cluster1";
NewGeoCluster<SiloConfigurator>(globalserviceid, cluster0, (short)(largesetup ? 3 : 1));
NewGeoCluster<SiloConfigurator>(globalserviceid, cluster1, (short)(largesetup ? 4 : 1));
if (!largesetup)
{
// Create one client per cluster
clients = new ClientWrapper[]
{
NewClient<ClientWrapper>(cluster0, 0, ClientWrapper.Factory),
NewClient<ClientWrapper>(cluster1, 0, ClientWrapper.Factory),
};
}
else
{
clients = new ClientWrapper[]
{
NewClient<ClientWrapper>(cluster0, 0, ClientWrapper.Factory),
NewClient<ClientWrapper>(cluster1, 0, ClientWrapper.Factory),
NewClient<ClientWrapper>(cluster0, 1, ClientWrapper.Factory),
NewClient<ClientWrapper>(cluster1, 1, ClientWrapper.Factory),
};
}
await WaitForLivenessToStabilizeAsync();
// Configure multicluster
clients[0].InjectMultiClusterConf(new string[] { cluster0, cluster1 });
await WaitForMultiClusterGossipToStabilizeAsync(false);
});
}
private Task IndependentCreation()
{
int offset = random.Next();
int base_own0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Owned).Count;
int base_own1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Owned).Count;
int base_requested0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.RequestedOwnership).Count;
int base_requested1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.RequestedOwnership).Count;
int base_doubtful0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Doubtful).Count;
int base_doubtful1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Doubtful).Count;
WriteLog("Counts: Cluster 0 => Owned={0} Requested={1} Doubtful={2}", base_own0, base_requested0, base_doubtful0);
WriteLog("Counts: Cluster 1 => Owned={0} Requested={1} Doubtful={2}", base_own1, base_requested1, base_doubtful1);
WriteLog("Starting parallel creation of {0} grains", numGrains);
// Create grains on both clusters, using clients round-robin.
Parallel.For(0, numGrains, paralleloptions, i =>
{
int val = clients[i % clients.Count()].CallGrain(offset + i);
Assert.Equal(1, val);
});
// We expect all requests to resolve, and all created activations are in state OWNED
int own0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Owned).Count;
int own1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Owned).Count;
int doubtful0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Doubtful).Count;
int doubtful1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Doubtful).Count;
int requested0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.RequestedOwnership).Count;
int requested1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.RequestedOwnership).Count;
WriteLog("Counts: Cluster 0 => Owned={0} Requested={1} Doubtful={2}", own0, requested0, doubtful0);
WriteLog("Counts: Cluster 1 => Owned={0} Requested={1} Doubtful={2}", own1, requested1, doubtful1);
// Assert that all grains are in owned state
Assert.Equal(numGrains / 2, own0 - base_own0);
Assert.Equal(numGrains / 2, own1 - base_own1);
Assert.Equal(doubtful0, base_doubtful0);
Assert.Equal(doubtful1, base_doubtful1);
Assert.Equal(requested0, base_requested0);
Assert.Equal(requested1, base_requested1);
return Task.CompletedTask;
}
// This test is for the case where two different clusters are racing,
// trying to activate the same grain.
// This function takes two arguments, a list of client configurations, and an integer. The list of client configurations is used to
// create multiple clients that concurrently call the grains in range [0, numGrains). We run the experiment in a series of barriers.
// The clients all invoke grain "g", in parallel, and then wait on a signal by the main thread (this function). The main thread, then
// wakes up the clients, after which they invoke "g+1", and so on.
private Task CreationRace()
{
WriteLog("Starting ConcurrentCreation");
var offset = random.Next();
// take inventory now so we can exclude pre-existing entries from the validation
var baseline = GetGrainActivations();
// We use two objects to coordinate client threads and the main thread. coordWakeup is an object that is used to signal the coordinator
// thread. toWait is used to signal client threads.
var coordWakeup = new object();
var toWait = new object();
// We keep a list of client threads.
var clientThreads = new List<Tuple<Thread, ClientThreadArgs>>();
var rand = new Random();
var results = new List<Tuple<int, int>>[clients.Length];
threadsDone = results.Length;
int index = 0;
// Create a client thread corresponding to each client
// The client thread will execute ThreadFunc function.
foreach (var client in clients)
{
// A client thread takes a list of tupes<int, int> as argument. The list is an ordered sequence of grains to invoke. tuple.item2
// is the grainId. tuple.item1 is never used (this should probably be cleaned up, but I don't want to break anything :).
var args = new List<Tuple<int, int>>();
for (int j = 0; j < numGrains; ++j)
{
var waitTime = rand.Next(16, 100);
args.Add(Tuple.Create(waitTime, j));
}
// Given a config file, create client starts a client in a new appdomain. We also create a thread on which the client will run.
// The thread takes a "ClientThreadArgs" as argument.
var thread = new Thread(ThreadFunc)
{
IsBackground = true,
Name = $"{this.GetType()}.{nameof(CreationRace)}"
};
var threadFuncArgs = new ClientThreadArgs
{
client = client,
args = args,
resultIndex = index,
numThreads = clients.Length,
coordWakeup = coordWakeup,
toWait = toWait,
results = results,
offset = offset
};
clientThreads.Add(Tuple.Create(thread, threadFuncArgs));
index += 1;
}
// Go through the list of client threads, and start each of the threads with the appropriate arguments.
foreach (var threadNArg in clientThreads)
{
var thread = threadNArg.Item1;
var arg = threadNArg.Item2;
thread.Start(arg);
}
// We run numGrains iterations of the experiment. The coordinator thread calls the function "WaitForWorkers" in order to wait
// for the client threads to finish concurrent calls to a single grain.
for (int i = 0; i < numGrains; ++i)
{
WaitForWorkers(clients.Length, coordWakeup, toWait);
}
// Once the clients threads have finished calling the grain the appropriate number of times, we wait for them to write out their results.
foreach (var threadNArg in clientThreads)
{
var thread = threadNArg.Item1;
thread.Join();
}
var grains = GetGrainActivations(baseline);
ValidateClusterRaceResults(results, grains);
return Task.CompletedTask;
}
private volatile int threadsDone;
private void ValidateClusterRaceResults(List<Tuple<int, int>>[] results, Dictionary<GrainId, List<IActivationInfo>> grains)
{
WriteLog("Validating cluster race results");
// there should be the right number of grains
AssertEqual(numGrains, grains.Count, "number of grains in directory does not match");
// each grain should have one activation per cluster
foreach (var kvp in grains)
{
GrainId key = kvp.Key;
List<IActivationInfo> activations = kvp.Value;
Action error = () =>
{
Assert.True(false, string.Format("grain {0} has wrong activations {1}",
key, string.Join(",", activations.Select(x =>
string.Format("{0}={1}", x.SiloAddress, x.RegistrationStatus)))));
};
// each grain has one activation per cluster
if (activations.Count != 2)
error();
// one should be owned and the other cached
switch (activations[0].RegistrationStatus)
{
case GrainDirectoryEntryStatus.Owned:
if (activations[1].RegistrationStatus != GrainDirectoryEntryStatus.Cached)
error();
break;
case GrainDirectoryEntryStatus.Cached:
if (activations[1].RegistrationStatus != GrainDirectoryEntryStatus.Owned)
error();
break;
default:
error();
break;
}
}
// For each of the results that get, ensure that we see a sequence of values.
foreach (var list in results)
Assert.Equal(numGrains, list.Count);
for (int i = 0; i < numGrains; ++i)
{
var vals = new List<int>();
foreach (var list in results)
vals.Add(list[i].Item2);
vals.Sort();
for (int x = 0; x < results.Length; x++)
AssertEqual(x + 1, vals[x], "expect sequence of results, but got " + string.Join(",", vals));
}
}
// This test is used to test the case where two different clusters are racing,
// trying to activate the same grain, but inter-cluster communication is blocked
// so they both activate an instance
// and one of them deactivated once communication is unblocked
private async Task ConflictResolution()
{
int offset = random.Next();
int base_own0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Owned).Count;
int base_own1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Owned).Count;
int base_requested0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.RequestedOwnership).Count;
int base_requested1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.RequestedOwnership).Count;
int base_doubtful0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Doubtful).Count;
int base_doubtful1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Doubtful).Count;
int base_cached0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Cached).Count;
int base_cached1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Cached).Count;
WriteLog("Counts: Cluster 0 => Owned={0} Requested={1} Doubtful={2} Cached={3}", base_own0, base_requested0, base_doubtful0, base_cached0);
WriteLog("Counts: Cluster 1 => Owned={0} Requested={1} Doubtful={2} Cached={3}", base_own1, base_requested1, base_doubtful1, base_cached1);
// take inventory now so we can exclude pre-existing entries from the validation
var baseline = GetGrainActivations();
// Turn off intercluster messaging to simulate a partition.
BlockAllClusterCommunication(cluster0, cluster1);
BlockAllClusterCommunication(cluster1, cluster0);
WriteLog("Starting creation of {0} grains on isolated clusters", numGrains);
Parallel.For(0, numGrains, paralleloptions, i =>
{
int res0, res1, res2, res3;
if (i % 2 == 1)
{
res0 = clients[0].CallGrain(offset + i);
res1 = clients[1].CallGrain(offset + i);
res2 = clients[2 % clients.Length].CallGrain(offset + i);
res3 = clients[3 % clients.Length].CallGrain(offset + i);
}
else
{
res0 = clients[1].CallGrain(offset + i);
res1 = clients[0].CallGrain(offset + i);
res2 = clients[0].CallGrain(offset + i);
res3 = clients[1].CallGrain(offset + i);
}
Assert.Equal(1, res0);
Assert.Equal(1, res1);
Assert.Equal(2, res2);
Assert.Equal(2, res3);
});
// Validate that all the created grains are in DOUBTFUL, one activation in each cluster.
Assert.True(GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Doubtful).Count == numGrains);
Assert.True(GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Doubtful).Count == numGrains);
WriteLog("Restoring inter-cluster communication");
// Turn on intercluster messaging and wait for the resolution to kick in.
UnblockAllClusterCommunication(cluster0);
UnblockAllClusterCommunication(cluster1);
// Wait for anti-entropy to kick in.
// One of the DOUBTFUL activations must be killed, and the other must be converted to OWNED.
await Task.Delay(TimeSpan.FromSeconds(7));
WriteLog("Validation of conflict resolution");
int own0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Owned).Count;
int own1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Owned).Count;
int doubtful0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Doubtful).Count;
int doubtful1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Doubtful).Count;
int requested0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.RequestedOwnership).Count;
int requested1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.RequestedOwnership).Count;
int cached0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Cached).Count;
int cached1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Cached).Count;
WriteLog("Counts: Cluster 0 => Owned={0} Requested={1} Doubtful={2} Cached={3}", own0, requested0, doubtful0, cached0);
WriteLog("Counts: Cluster 1 => Owned={0} Requested={1} Doubtful={2} Cached={3}", own1, requested1, doubtful1, cached1);
AssertEqual(numGrains + base_own0 + base_own1, own0 + own1, "Expecting All are now Owned");
AssertEqual(numGrains, cached0 + cached1 - base_cached0 - base_cached1, "Expecting All Owned have a cached in the other cluster");
AssertEqual(0, doubtful0 + doubtful1 - base_doubtful0 - base_doubtful1, "Expecting No Doubtful");
Assert.Equal(requested0, base_requested0);
Assert.Equal(requested1, base_requested1);
// each grain should have one activation per cluster
var grains = GetGrainActivations(baseline);
foreach (var kvp in grains)
{
GrainId key = kvp.Key;
List<IActivationInfo> activations = kvp.Value;
Action error = () =>
{
Assert.True(false, string.Format("grain {0} has wrong activations {1}",
key, string.Join(",", activations.Select(x =>
string.Format("{0}={1}", x.SiloAddress, x.RegistrationStatus)))));
};
// each grain has one activation per cluster
if (activations.Count != 2)
error();
// one should be owned and the other cached
switch (activations[0].RegistrationStatus)
{
case GrainDirectoryEntryStatus.Owned:
if (activations[1].RegistrationStatus != GrainDirectoryEntryStatus.Cached)
error();
break;
case GrainDirectoryEntryStatus.Cached:
if (activations[1].RegistrationStatus != GrainDirectoryEntryStatus.Owned)
error();
break;
default:
error();
break;
}
}
// ensure that the grain whose DOUBTFUL activation was killed,
// now refers to the 'real' remote OWNED activation.
for (int i = 0; i < numGrains; i++)
{
int res0, res1, res2, res3;
if (i % 2 == 1)
{
res0 = clients[0].CallGrain(offset + i);
res1 = clients[1].CallGrain(offset + i);
res2 = clients[2 % clients.Length].CallGrain(offset + i);
res3 = clients[3 % clients.Length].CallGrain(offset + i);
}
else
{
res0 = clients[1].CallGrain(offset + i);
res1 = clients[0].CallGrain(offset + i);
res2 = clients[0].CallGrain(offset + i);
res3 = clients[1].CallGrain(offset + i);
}
//From the previous grain calls, the last value of the counter in each grain was 2.
//So here should be sequenced from 3.
Assert.Equal(3, res0);
Assert.Equal(4, res1);
Assert.Equal(5, res2);
Assert.Equal(6, res3);
}
}
private List<GrainId> GetGrainsInClusterWithStatus(string clusterId, GrainDirectoryEntryStatus? status = null)
{
List<GrainId> grains = new List<GrainId>();
var silos = Clusters[clusterId].Cluster.GetActiveSilos();
int totalSoFar = 0;
foreach (var silo in silos)
{
var hooks = ((AppDomainSiloHandle)silo).AppDomainTestHook;
var dir = hooks.GetDirectoryForTypeNamesContaining("ClusterTestGrain");
foreach (var grainKeyValue in dir)
{
GrainId grainId = grainKeyValue.Key;
IGrainInfo grainInfo = grainKeyValue.Value;
ActivationId actId = grainInfo.Instances.First().Key;
IActivationInfo actInfo = grainInfo.Instances[actId];
if (grainId.IsSystemTarget || grainId.IsClient || !grainId.IsGrain)
{
// Skip system grains, system targets and clients
// which never go through cluster-single-instance registration process
continue;
}
if (!status.HasValue || actInfo.RegistrationStatus == status)
{
grains.Add(grainId);
}
}
WriteLog("Returning: Silo {0} State = {1} Count = {2}", silo.SiloAddress, status.HasValue ? status.Value.ToString() : "ANY", (grains.Count - totalSoFar));
totalSoFar = grains.Count;
}
WriteLog("Returning: Cluster {0} State = {1} Count = {2}", clusterId, status.HasValue ? status.Value.ToString() : "ANY", grains.Count);
return grains;
}
private Dictionary<GrainId, List<IActivationInfo>> GetGrainActivations(Dictionary<GrainId, List<IActivationInfo>> exclude = null)
{
var grains = new Dictionary<GrainId, List<IActivationInfo>>();
int instanceCount = 0;
foreach (var kvp in Clusters)
{
foreach (var silo in kvp.Value.Silos)
{
var hooks = ((AppDomainSiloHandle) silo).AppDomainTestHook;
var dir = hooks.GetDirectoryForTypeNamesContaining("ClusterTestGrain");
foreach (var grainKeyValue in dir)
{
GrainId grainId = grainKeyValue.Key;
IGrainInfo grainInfo = grainKeyValue.Value;
if (exclude != null && exclude.ContainsKey(grainId))
continue;
if (!grains.TryGetValue(grainId, out var activations))
grains[grainId] = activations = new List<IActivationInfo>();
foreach (var instanceInfo in grainInfo.Instances)
{
activations.Add(instanceInfo.Value);
instanceCount++;
}
}
}
}
WriteLog("Returning: {0} instances for {1} grains", instanceCount, grains.Count());
return grains;
}
// This is a helper function which is used to run the race condition tests. This function waits for all client threads trying to create the
// same activation to finish. The last client thread to finish will wakeup the coordinator thread.
private void WaitForCoordinator(int numThreads, object coordWakeup, object toWait)
{
Monitor.Enter(coordWakeup);
Monitor.Enter(toWait);
threadsDone -= 1;
if (threadsDone == 0)
{
Monitor.Pulse(coordWakeup);
}
Monitor.Exit(coordWakeup);
Monitor.Wait(toWait);
Monitor.Exit(toWait);
}
// This is a helper function which is used to signal the worker client threads to run another iteration of our concurrent experiment.
private void WaitForWorkers(int numThreads, object coordWakeup, object toWait)
{
Monitor.Enter(coordWakeup);
while (threadsDone != 0)
{
Monitor.Wait(coordWakeup);
}
threadsDone = numThreads;
Monitor.Exit(coordWakeup);
Monitor.Enter(toWait);
Monitor.PulseAll(toWait);
Monitor.Exit(toWait);
}
// ClientThreadArgs is a set of arguments which is used by a client thread which is concurrently running with other client threads. We
// use client threads in order to simulate race conditions.
private class ClientThreadArgs
{
public ClientWrapper client;
public IEnumerable<Tuple<int, int>> args;
public int resultIndex;
public int numThreads;
public object coordWakeup;
public object toWait;
public List<Tuple<int, int>>[] results;
public int offset;
}
// Each client thread which is concurrently trying to create a sequence of grains with other clients runs this function.
private void ThreadFunc(object obj)
{
var threadArg = (ClientThreadArgs)obj;
var resultList = new List<Tuple<int, int>>();
// Go through the sequence of arguments one by one.
foreach (var arg in threadArg.args)
{
try
{
// Call the appropriate grain.
var grainId = arg.Item2;
int ret = threadArg.client.CallGrain(threadArg.offset + grainId);
Debug.WriteLine("*** Result = {0}", ret);
// Keep the result in resultList.
resultList.Add(Tuple.Create(grainId, ret));
}
catch (Exception e)
{
WriteLog("Caught exception: {0}", e);
}
// Finally, wait for the coordinator to kick-off another round of the test.
WaitForCoordinator(threadArg.numThreads, threadArg.coordWakeup, threadArg.toWait);
}
// Track the results for validation.
lock (threadArg.results)
{
threadArg.results[threadArg.resultIndex] = resultList;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class ElementAttributeTest : DriverTestFixture
{
[Test]
public void ShouldReturnNullWhenGettingTheValueOfAnAttributeThatIsNotListed()
{
driver.Url = simpleTestPage;
IWebElement head = driver.FindElement(By.XPath("/html"));
string attribute = head.GetAttribute("cheese");
Assert.IsNull(attribute);
}
[Test]
public void ShouldReturnNullWhenGettingSrcAttributeOfInvalidImgTag()
{
driver.Url = simpleTestPage;
IWebElement img = driver.FindElement(By.Id("invalidImgTag"));
string attribute = img.GetAttribute("src");
Assert.IsNull(attribute);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldReturnAnAbsoluteUrlWhenGettingSrcAttributeOfAValidImgTag()
{
driver.Url = simpleTestPage;
IWebElement img = driver.FindElement(By.Id("validImgTag"));
string attribute = img.GetAttribute("src");
Assert.AreEqual(EnvironmentManager.Instance.UrlBuilder.WhereIs("icon.gif"), attribute);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldReturnAnAbsoluteUrlWhenGettingHrefAttributeOfAValidAnchorTag()
{
driver.Url = simpleTestPage;
IWebElement img = driver.FindElement(By.Id("validAnchorTag"));
string attribute = img.GetAttribute("href");
Assert.AreEqual(EnvironmentManager.Instance.UrlBuilder.WhereIs("icon.gif"), attribute);
}
[Test]
public void ShouldReturnEmptyAttributeValuesWhenPresentAndTheValueIsActuallyEmpty()
{
driver.Url = simpleTestPage;
IWebElement body = driver.FindElement(By.XPath("//body"));
Assert.AreEqual(string.Empty, body.GetAttribute("style"));
}
[Test]
public void ShouldReturnTheValueOfTheDisabledAttributeAsNullIfNotSet()
{
driver.Url = formsPage;
IWebElement inputElement = driver.FindElement(By.XPath("//input[@id='working']"));
Assert.IsNull(inputElement.GetAttribute("disabled"));
Assert.IsTrue(inputElement.Enabled);
IWebElement pElement = driver.FindElement(By.Id("peas"));
Assert.IsNull(inputElement.GetAttribute("disabled"));
Assert.IsTrue(inputElement.Enabled);
}
[Test]
public void ShouldReturnTheValueOfTheIndexAttrbuteEvenIfItIsMissing()
{
driver.Url = formsPage;
IWebElement multiSelect = driver.FindElement(By.Id("multi"));
ReadOnlyCollection<IWebElement> options = multiSelect.FindElements(By.TagName("option"));
Assert.AreEqual("1", options[1].GetAttribute("index"));
}
[Test]
public void ShouldIndicateTheElementsThatAreDisabledAreNotEnabled()
{
driver.Url = formsPage;
IWebElement inputElement = driver.FindElement(By.XPath("//input[@id='notWorking']"));
Assert.IsFalse(inputElement.Enabled);
inputElement = driver.FindElement(By.XPath("//input[@id='working']"));
Assert.IsTrue(inputElement.Enabled);
}
[Test]
public void ElementsShouldBeDisabledIfTheyAreDisabledUsingRandomDisabledStrings()
{
driver.Url = formsPage;
IWebElement disabledTextElement1 = driver.FindElement(By.Id("disabledTextElement1"));
Assert.IsFalse(disabledTextElement1.Enabled);
IWebElement disabledTextElement2 = driver.FindElement(By.Id("disabledTextElement2"));
Assert.IsFalse(disabledTextElement2.Enabled);
IWebElement disabledSubmitElement = driver.FindElement(By.Id("disabledSubmitElement"));
Assert.IsFalse(disabledSubmitElement.Enabled);
}
[Test]
public void ShouldThrowExceptionIfSendingKeysToElementDisabledUsingRandomDisabledStrings()
{
driver.Url = formsPage;
IWebElement disabledTextElement1 = driver.FindElement(By.Id("disabledTextElement1"));
try
{
disabledTextElement1.SendKeys("foo");
Assert.Fail("Should have thrown exception");
}
catch (InvalidElementStateException)
{
//Expected
}
Assert.AreEqual(string.Empty, disabledTextElement1.Text);
IWebElement disabledTextElement2 = driver.FindElement(By.Id("disabledTextElement2"));
try
{
disabledTextElement2.SendKeys("bar");
Assert.Fail("Should have thrown exception");
}
catch (InvalidElementStateException)
{
//Expected
}
Assert.AreEqual(string.Empty, disabledTextElement2.Text);
}
[Test]
public void ShouldIndicateWhenATextAreaIsDisabled()
{
driver.Url = formsPage;
IWebElement textArea = driver.FindElement(By.XPath("//textarea[@id='notWorkingArea']"));
Assert.IsFalse(textArea.Enabled);
}
[Test]
public void ShouldIndicateWhenASelectIsDisabled()
{
driver.Url = formsPage;
IWebElement enabled = driver.FindElement(By.Name("selectomatic"));
IWebElement disabled = driver.FindElement(By.Name("no-select"));
Assert.IsTrue(enabled.Enabled);
Assert.IsFalse(disabled.Enabled);
}
[Test]
public void ShouldReturnTheValueOfCheckedForACheckboxOnlyIfItIsChecked()
{
driver.Url = formsPage;
IWebElement checkbox = driver.FindElement(By.XPath("//input[@id='checky']"));
Assert.AreEqual(null, checkbox.GetAttribute("checked"));
checkbox.Click();
Assert.AreEqual("true", checkbox.GetAttribute("checked"));
}
[Test]
public void ShouldOnlyReturnTheValueOfSelectedForRadioButtonsIfItIsSet()
{
driver.Url = formsPage;
IWebElement neverSelected = driver.FindElement(By.Id("cheese"));
IWebElement initiallyNotSelected = driver.FindElement(By.Id("peas"));
IWebElement initiallySelected = driver.FindElement(By.Id("cheese_and_peas"));
Assert.AreEqual(null, neverSelected.GetAttribute("selected"), "false");
Assert.AreEqual(null, initiallyNotSelected.GetAttribute("selected"), "false");
Assert.AreEqual("true", initiallySelected.GetAttribute("selected"), "true");
initiallyNotSelected.Click();
Assert.AreEqual(null, neverSelected.GetAttribute("selected"));
Assert.AreEqual("true", initiallyNotSelected.GetAttribute("selected"));
Assert.AreEqual(null, initiallySelected.GetAttribute("selected"));
}
[Test]
public void ShouldReturnTheValueOfSelectedForOptionsOnlyIfTheyAreSelected()
{
driver.Url = formsPage;
IWebElement selectBox = driver.FindElement(By.XPath("//select[@name='selectomatic']"));
ReadOnlyCollection<IWebElement> options = selectBox.FindElements(By.TagName("option"));
IWebElement one = options[0];
IWebElement two = options[1];
Assert.IsTrue(one.Selected);
Assert.IsFalse(two.Selected);
Assert.AreEqual("true", one.GetAttribute("selected"));
Assert.AreEqual(null, two.GetAttribute("selected"));
}
[Test]
public void ShouldReturnValueOfClassAttributeOfAnElement()
{
driver.Url = xhtmlTestPage;
IWebElement heading = driver.FindElement(By.XPath("//h1"));
String className = heading.GetAttribute("class");
Assert.AreEqual("header", className);
}
[Test]
public void ShouldReturnTheContentsOfATextAreaAsItsValue()
{
driver.Url = formsPage;
String value = driver.FindElement(By.Id("withText")).GetAttribute("value");
Assert.AreEqual("Example text", value);
}
[Test]
public void ShouldReturnInnerHtml()
{
driver.Url = simpleTestPage;
string html = driver.FindElement(By.Id("wrappingtext")).GetAttribute("innerHTML");
Assert.IsTrue(html.Contains("<tbody>"), "text should contain '<tbody>', but does not - " + html);
}
[Test]
public void ShouldTreatReadonlyAsAValue()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("readonly"));
string readOnlyAttribute = element.GetAttribute("readonly");
Assert.IsNotNull(readOnlyAttribute);
IWebElement textInput = driver.FindElement(By.Name("x"));
string notReadOnly = textInput.GetAttribute("readonly");
Assert.IsNull(notReadOnly);
Assert.IsFalse(readOnlyAttribute.Equals(notReadOnly));
}
[Test]
public void ShouldReturnHiddenTextForTextContentAttribute()
{
if (TestUtilities.IsOldIE(driver))
{
Assert.Ignore("IE 8 or below does not handle textContent attribute");
}
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.Id("hiddenline"));
string textContent = element.GetAttribute("textContent");
Assert.AreEqual("A hidden line of text", textContent);
}
[Test]
public void ShouldGetNumericAtribute()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("withText"));
Assert.AreEqual("5", element.GetAttribute("rows"));
}
[Test]
public void CanReturnATextApproximationOfTheStyleAttribute()
{
driver.Url = javascriptPage;
string style = driver.FindElement(By.Id("red-item")).GetAttribute("style");
Assert.IsTrue(style.ToLower().Contains("background-color"));
}
public void ShouldCorrectlyReportValueOfColspan()
{
driver.Url = tables;
System.Threading.Thread.Sleep(1000);
IWebElement th1 = driver.FindElement(By.Id("th1"));
IWebElement td2 = driver.FindElement(By.Id("td2"));
Assert.AreEqual("th1", th1.GetAttribute("id"), "th1 id");
Assert.AreEqual("3", th1.GetAttribute("colspan"), "th1 colspan should be 3");
Assert.AreEqual("td2", td2.GetAttribute("id"), "td2 id");
Assert.AreEqual("2", td2.GetAttribute("colspan"), "td2 colspan should be 2");
}
// This is a test-case re-creating issue 900.
[Test]
public void ShouldReturnValueOfOnClickAttribute()
{
driver.Url = javascriptPage;
IWebElement mouseclickDiv = driver.FindElement(By.Id("mouseclick"));
string onClickValue = mouseclickDiv.GetAttribute("onclick");
string expectedOnClickValue = "displayMessage('mouse click');";
List<string> acceptableOnClickValues = new List<string>();
acceptableOnClickValues.Add("javascript:" + expectedOnClickValue);
acceptableOnClickValues.Add("function anonymous()\n{\n" + expectedOnClickValue + "\n}");
acceptableOnClickValues.Add("function onclick()\n{\n" + expectedOnClickValue + "\n}");
Assert.IsTrue(acceptableOnClickValues.Contains(onClickValue));
IWebElement mousedownDiv = driver.FindElement(By.Id("mousedown"));
Assert.IsNull(mousedownDiv.GetAttribute("onclick"));
}
[Test]
[IgnoreBrowser(Browser.IPhone, "SVG elements crash the iWebDriver app (issue 1134)")]
public void GetAttributeDoesNotReturnAnObjectForSvgProperties()
{
if (TestUtilities.IsOldIE(driver))
{
Assert.Ignore("IE8 and below do not support SVG");
}
driver.Url = svgPage;
IWebElement svgElement = driver.FindElement(By.Id("rotate"));
Assert.AreEqual("rotate(30)", svgElement.GetAttribute("transform"));
}
[Test]
public void CanRetrieveTheCurrentValueOfATextFormField_textInput()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("working"));
Assert.AreEqual(string.Empty, element.GetAttribute("value"));
element.SendKeys("hello world");
Assert.AreEqual("hello world", element.GetAttribute("value"));
}
[Test]
public void CanRetrieveTheCurrentValueOfATextFormField_emailInput()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("email"));
Assert.AreEqual(string.Empty, element.GetAttribute("value"));
element.SendKeys("hello world");
Assert.AreEqual("hello world", element.GetAttribute("value"));
}
[Test]
public void CanRetrieveTheCurrentValueOfATextFormField_textArea()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("emptyTextArea"));
Assert.AreEqual(string.Empty, element.GetAttribute("value"));
element.SendKeys("hello world");
Assert.AreEqual("hello world", element.GetAttribute("value"));
}
[Test]
public void ShouldReturnValueOfClassAttributeOfAnElementAfterSwitchingIFrame()
{
driver.Url = iframePage;
driver.SwitchTo().Frame("iframe1");
IWebElement wallace = driver.FindElement(By.XPath("//div[@id='wallace']"));
String className = wallace.GetAttribute("class");
Assert.AreEqual("gromit", className);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
public void ShouldReturnNullForNonPresentBooleanAttributes()
{
driver.Url = booleanAttributes;
IWebElement element1 = driver.FindElement(By.Id("working"));
Assert.IsNull(element1.GetAttribute("required"));
IWebElement element2 = driver.FindElement(By.Id("wallace"));
Assert.IsNull(element2.GetAttribute("nowrap"));
}
[Test]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Android)]
public void ShouldReturnTrueForPresentBooleanAttributes()
{
driver.Url = booleanAttributes;
IWebElement element1 = driver.FindElement(By.Id("emailRequired"));
Assert.AreEqual("true", element1.GetAttribute("required"));
IWebElement element2 = driver.FindElement(By.Id("emptyTextAreaRequired"));
Assert.AreEqual("true", element2.GetAttribute("required"));
IWebElement element3 = driver.FindElement(By.Id("inputRequired"));
Assert.AreEqual("true", element3.GetAttribute("required"));
IWebElement element4 = driver.FindElement(By.Id("textAreaRequired"));
Assert.AreEqual("true", element4.GetAttribute("required"));
IWebElement element5 = driver.FindElement(By.Id("unwrappable"));
Assert.AreEqual("true", element5.GetAttribute("nowrap"));
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Networking.VLANGroupBinding", Namespace="urn:iControl")]
public partial class NetworkingVLANGroup : iControlInterface {
public NetworkingVLANGroup() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_global_proxy_exclusion
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void add_global_proxy_exclusion(
string [] addresses
) {
this.Invoke("add_global_proxy_exclusion", new object [] {
addresses});
}
public System.IAsyncResult Beginadd_global_proxy_exclusion(string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_global_proxy_exclusion", new object[] {
addresses}, callback, asyncState);
}
public void Endadd_global_proxy_exclusion(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_member
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void add_member(
string [] vlan_groups,
string [] [] member_vlans
) {
this.Invoke("add_member", new object [] {
vlan_groups,
member_vlans});
}
public System.IAsyncResult Beginadd_member(string [] vlan_groups,string [] [] member_vlans, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_member", new object[] {
vlan_groups,
member_vlans}, callback, asyncState);
}
public void Endadd_member(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_proxy_exclusion
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void add_proxy_exclusion(
string [] vlan_groups,
string [] [] addresses
) {
this.Invoke("add_proxy_exclusion", new object [] {
vlan_groups,
addresses});
}
public System.IAsyncResult Beginadd_proxy_exclusion(string [] vlan_groups,string [] [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_proxy_exclusion", new object[] {
vlan_groups,
addresses}, callback, asyncState);
}
public void Endadd_proxy_exclusion(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void create(
string [] vlan_groups,
long [] vlan_ids,
string [] [] member_vlans
) {
this.Invoke("create", new object [] {
vlan_groups,
vlan_ids,
member_vlans});
}
public System.IAsyncResult Begincreate(string [] vlan_groups,long [] vlan_ids,string [] [] member_vlans, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
vlan_groups,
vlan_ids,
member_vlans}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void create_v2(
string [] vlan_groups,
string [] [] member_vlans
) {
this.Invoke("create_v2", new object [] {
vlan_groups,
member_vlans});
}
public System.IAsyncResult Begincreate_v2(string [] vlan_groups,string [] [] member_vlans, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create_v2", new object[] {
vlan_groups,
member_vlans}, callback, asyncState);
}
public void Endcreate_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_vlan_groups
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void delete_all_vlan_groups(
) {
this.Invoke("delete_all_vlan_groups", new object [0]);
}
public System.IAsyncResult Begindelete_all_vlan_groups(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_vlan_groups", new object[0], callback, asyncState);
}
public void Enddelete_all_vlan_groups(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_vlan_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void delete_vlan_group(
string [] vlan_groups
) {
this.Invoke("delete_vlan_group", new object [] {
vlan_groups});
}
public System.IAsyncResult Begindelete_vlan_group(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_vlan_group", new object[] {
vlan_groups}, callback, asyncState);
}
public void Enddelete_vlan_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_auto_lasthop
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonAutoLasthop [] get_auto_lasthop(
string [] vlan_groups
) {
object [] results = this.Invoke("get_auto_lasthop", new object [] {
vlan_groups});
return ((CommonAutoLasthop [])(results[0]));
}
public System.IAsyncResult Beginget_auto_lasthop(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_auto_lasthop", new object[] {
vlan_groups}, callback, asyncState);
}
public CommonAutoLasthop [] Endget_auto_lasthop(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonAutoLasthop [])(results[0]));
}
//-----------------------------------------------------------------------
// get_bridge_all_traffic_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_bridge_all_traffic_state(
string [] vlan_groups
) {
object [] results = this.Invoke("get_bridge_all_traffic_state", new object [] {
vlan_groups});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_bridge_all_traffic_state(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_bridge_all_traffic_state", new object[] {
vlan_groups}, callback, asyncState);
}
public CommonEnabledState [] Endget_bridge_all_traffic_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_bridge_in_standby_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_bridge_in_standby_state(
string [] vlan_groups
) {
object [] results = this.Invoke("get_bridge_in_standby_state", new object [] {
vlan_groups});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_bridge_in_standby_state(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_bridge_in_standby_state", new object[] {
vlan_groups}, callback, asyncState);
}
public CommonEnabledState [] Endget_bridge_in_standby_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_bridge_multicast_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_bridge_multicast_state(
string [] vlan_groups
) {
object [] results = this.Invoke("get_bridge_multicast_state", new object [] {
vlan_groups});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_bridge_multicast_state(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_bridge_multicast_state", new object[] {
vlan_groups}, callback, asyncState);
}
public CommonEnabledState [] Endget_bridge_multicast_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] vlan_groups
) {
object [] results = this.Invoke("get_description", new object [] {
vlan_groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
vlan_groups}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_global_proxy_exclusion
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_global_proxy_exclusion(
) {
object [] results = this.Invoke("get_global_proxy_exclusion", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_global_proxy_exclusion(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_global_proxy_exclusion", new object[0], callback, asyncState);
}
public string [] Endget_global_proxy_exclusion(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_if_index
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_if_index(
string [] vlan_groups
) {
object [] results = this.Invoke("get_if_index", new object [] {
vlan_groups});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_if_index(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_if_index", new object[] {
vlan_groups}, callback, asyncState);
}
public long [] Endget_if_index(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_mac_masquerade_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_mac_masquerade_address(
string [] vlan_groups
) {
object [] results = this.Invoke("get_mac_masquerade_address", new object [] {
vlan_groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_mac_masquerade_address(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_mac_masquerade_address", new object[] {
vlan_groups}, callback, asyncState);
}
public string [] Endget_mac_masquerade_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_member
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_member(
string [] vlan_groups
) {
object [] results = this.Invoke("get_member", new object [] {
vlan_groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_member(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_member", new object[] {
vlan_groups}, callback, asyncState);
}
public string [] [] Endget_member(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_proxy_exclusion
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_proxy_exclusion(
string [] vlan_groups
) {
object [] results = this.Invoke("get_proxy_exclusion", new object [] {
vlan_groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_proxy_exclusion(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_proxy_exclusion", new object[] {
vlan_groups}, callback, asyncState);
}
public string [] [] Endget_proxy_exclusion(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_transparency_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingVLANGroupVLANGroupTransparency [] get_transparency_mode(
string [] vlan_groups
) {
object [] results = this.Invoke("get_transparency_mode", new object [] {
vlan_groups});
return ((NetworkingVLANGroupVLANGroupTransparency [])(results[0]));
}
public System.IAsyncResult Beginget_transparency_mode(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_transparency_mode", new object[] {
vlan_groups}, callback, asyncState);
}
public NetworkingVLANGroupVLANGroupTransparency [] Endget_transparency_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingVLANGroupVLANGroupTransparency [])(results[0]));
}
//-----------------------------------------------------------------------
// get_true_mac_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_true_mac_address(
string [] vlan_groups
) {
object [] results = this.Invoke("get_true_mac_address", new object [] {
vlan_groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_true_mac_address(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_true_mac_address", new object[] {
vlan_groups}, callback, asyncState);
}
public string [] Endget_true_mac_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_vlan_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_vlan_id(
string [] vlan_groups
) {
object [] results = this.Invoke("get_vlan_id", new object [] {
vlan_groups});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_vlan_id(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_vlan_id", new object[] {
vlan_groups}, callback, asyncState);
}
public long [] Endget_vlan_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_global_proxy_exclusions
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void remove_all_global_proxy_exclusions(
) {
this.Invoke("remove_all_global_proxy_exclusions", new object [0]);
}
public System.IAsyncResult Beginremove_all_global_proxy_exclusions(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_global_proxy_exclusions", new object[0], callback, asyncState);
}
public void Endremove_all_global_proxy_exclusions(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_members
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void remove_all_members(
string [] vlan_groups
) {
this.Invoke("remove_all_members", new object [] {
vlan_groups});
}
public System.IAsyncResult Beginremove_all_members(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_members", new object[] {
vlan_groups}, callback, asyncState);
}
public void Endremove_all_members(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_proxy_exclusions
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void remove_all_proxy_exclusions(
string [] vlan_groups
) {
this.Invoke("remove_all_proxy_exclusions", new object [] {
vlan_groups});
}
public System.IAsyncResult Beginremove_all_proxy_exclusions(string [] vlan_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_proxy_exclusions", new object[] {
vlan_groups}, callback, asyncState);
}
public void Endremove_all_proxy_exclusions(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_global_proxy_exclusion
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void remove_global_proxy_exclusion(
string [] addresses
) {
this.Invoke("remove_global_proxy_exclusion", new object [] {
addresses});
}
public System.IAsyncResult Beginremove_global_proxy_exclusion(string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_global_proxy_exclusion", new object[] {
addresses}, callback, asyncState);
}
public void Endremove_global_proxy_exclusion(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_member
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void remove_member(
string [] vlan_groups,
string [] [] member_vlans
) {
this.Invoke("remove_member", new object [] {
vlan_groups,
member_vlans});
}
public System.IAsyncResult Beginremove_member(string [] vlan_groups,string [] [] member_vlans, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_member", new object[] {
vlan_groups,
member_vlans}, callback, asyncState);
}
public void Endremove_member(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_proxy_exclusion
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void remove_proxy_exclusion(
string [] vlan_groups,
string [] [] addresses
) {
this.Invoke("remove_proxy_exclusion", new object [] {
vlan_groups,
addresses});
}
public System.IAsyncResult Beginremove_proxy_exclusion(string [] vlan_groups,string [] [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_proxy_exclusion", new object[] {
vlan_groups,
addresses}, callback, asyncState);
}
public void Endremove_proxy_exclusion(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_auto_lasthop
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void set_auto_lasthop(
string [] vlan_groups,
CommonAutoLasthop [] values
) {
this.Invoke("set_auto_lasthop", new object [] {
vlan_groups,
values});
}
public System.IAsyncResult Beginset_auto_lasthop(string [] vlan_groups,CommonAutoLasthop [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_auto_lasthop", new object[] {
vlan_groups,
values}, callback, asyncState);
}
public void Endset_auto_lasthop(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_bridge_all_traffic_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void set_bridge_all_traffic_state(
string [] vlan_groups,
CommonEnabledState [] states
) {
this.Invoke("set_bridge_all_traffic_state", new object [] {
vlan_groups,
states});
}
public System.IAsyncResult Beginset_bridge_all_traffic_state(string [] vlan_groups,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_bridge_all_traffic_state", new object[] {
vlan_groups,
states}, callback, asyncState);
}
public void Endset_bridge_all_traffic_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_bridge_in_standby_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void set_bridge_in_standby_state(
string [] vlan_groups,
CommonEnabledState [] states
) {
this.Invoke("set_bridge_in_standby_state", new object [] {
vlan_groups,
states});
}
public System.IAsyncResult Beginset_bridge_in_standby_state(string [] vlan_groups,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_bridge_in_standby_state", new object[] {
vlan_groups,
states}, callback, asyncState);
}
public void Endset_bridge_in_standby_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_bridge_multicast_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void set_bridge_multicast_state(
string [] vlan_groups,
CommonEnabledState [] states
) {
this.Invoke("set_bridge_multicast_state", new object [] {
vlan_groups,
states});
}
public System.IAsyncResult Beginset_bridge_multicast_state(string [] vlan_groups,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_bridge_multicast_state", new object[] {
vlan_groups,
states}, callback, asyncState);
}
public void Endset_bridge_multicast_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void set_description(
string [] vlan_groups,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
vlan_groups,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] vlan_groups,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
vlan_groups,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_mac_masquerade_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void set_mac_masquerade_address(
string [] vlan_groups,
string [] mac_masquerade_addresses
) {
this.Invoke("set_mac_masquerade_address", new object [] {
vlan_groups,
mac_masquerade_addresses});
}
public System.IAsyncResult Beginset_mac_masquerade_address(string [] vlan_groups,string [] mac_masquerade_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_mac_masquerade_address", new object[] {
vlan_groups,
mac_masquerade_addresses}, callback, asyncState);
}
public void Endset_mac_masquerade_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_transparency_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void set_transparency_mode(
string [] vlan_groups,
NetworkingVLANGroupVLANGroupTransparency [] modes
) {
this.Invoke("set_transparency_mode", new object [] {
vlan_groups,
modes});
}
public System.IAsyncResult Beginset_transparency_mode(string [] vlan_groups,NetworkingVLANGroupVLANGroupTransparency [] modes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_transparency_mode", new object[] {
vlan_groups,
modes}, callback, asyncState);
}
public void Endset_transparency_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_vlan_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/VLANGroup",
RequestNamespace="urn:iControl:Networking/VLANGroup", ResponseNamespace="urn:iControl:Networking/VLANGroup")]
public void set_vlan_id(
string [] vlan_groups,
long [] vlan_ids
) {
this.Invoke("set_vlan_id", new object [] {
vlan_groups,
vlan_ids});
}
public System.IAsyncResult Beginset_vlan_id(string [] vlan_groups,long [] vlan_ids, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_vlan_id", new object[] {
vlan_groups,
vlan_ids}, callback, asyncState);
}
public void Endset_vlan_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.VLANGroup.VLANGroupTransparency", Namespace = "urn:iControl")]
public enum NetworkingVLANGroupVLANGroupTransparency
{
VLANGROUP_TRANSPARENT,
VLANGROUP_OPAQUE,
VLANGROUP_TRANSLUCENT,
}
//=======================================================================
// Structs
//=======================================================================
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
namespace System.Runtime.Versioning
{
public sealed class FrameworkName : IEquatable<FrameworkName>
{
// ---- SECTION: members supporting exposed properties -------------*
#region members supporting exposed properties
private readonly String _identifier = null;
private readonly Version _version = null;
private readonly String _profile = null;
private String _fullName = null;
private const Char c_componentSeparator = ',';
private const Char c_keyValueSeparator = '=';
private const Char c_versionValuePrefix = 'v';
private const String c_versionKey = "Version";
private const String c_profileKey = "Profile";
#endregion members supporting exposed properties
// ---- SECTION: public properties --------------*
#region public properties
public String Identifier
{
get
{
Debug.Assert(_identifier != null);
return _identifier;
}
}
public Version Version
{
get
{
Debug.Assert(_version != null);
return _version;
}
}
public String Profile
{
get
{
Debug.Assert(_profile != null);
return _profile;
}
}
public String FullName
{
get
{
if (_fullName == null)
{
StringBuilder sb = new StringBuilder();
sb.Append(Identifier);
sb.Append(c_componentSeparator);
sb.Append(c_versionKey).Append(c_keyValueSeparator);
sb.Append(c_versionValuePrefix);
sb.Append(Version);
if (!String.IsNullOrEmpty(Profile))
{
sb.Append(c_componentSeparator);
sb.Append(c_profileKey).Append(c_keyValueSeparator);
sb.Append(Profile);
}
_fullName = sb.ToString();
}
Debug.Assert(_fullName != null);
return _fullName;
}
}
#endregion public properties
// ---- SECTION: public instance methods --------------*
#region public instance methods
public override Boolean Equals(Object obj)
{
return Equals(obj as FrameworkName);
}
public Boolean Equals(FrameworkName other)
{
if (Object.ReferenceEquals(other, null))
{
return false;
}
return Identifier == other.Identifier &&
Version == other.Version &&
Profile == other.Profile;
}
public override Int32 GetHashCode()
{
return Identifier.GetHashCode() ^ Version.GetHashCode() ^ Profile.GetHashCode();
}
public override String ToString()
{
return FullName;
}
#endregion public instance methods
// -------- SECTION: constructors -----------------*
#region constructors
public FrameworkName(String identifier, Version version)
: this(identifier, version, null)
{ }
public FrameworkName(String identifier, Version version, String profile)
{
if (identifier == null)
{
throw new ArgumentNullException(nameof(identifier));
}
identifier = identifier.Trim();
if (identifier.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, "identifier"), nameof(identifier));
}
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
_identifier = identifier;
// Ensure we call the correct Version constructor to clone the Version
if (version.Revision < 0)
{
if (version.Build < 0)
{
_version = new Version(version.Major, version.Minor);
}
else
{
_version = new Version(version.Major, version.Minor, version.Build);
}
}
else
{
_version = new Version(version.Major, version.Minor, version.Build, version.Revision);
}
_profile = (profile == null) ? String.Empty : profile.Trim();
}
// Parses strings in the following format: "<identifier>, Version=[v|V]<version>, Profile=<profile>"
// - The identifier and version is required, profile is optional
// - Only three components are allowed.
// - The version string must be in the System.Version format; an optional "v" or "V" prefix is allowed
public FrameworkName(String frameworkName)
{
if (frameworkName == null)
{
throw new ArgumentNullException(nameof(frameworkName));
}
if (frameworkName.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, "frameworkName"), nameof(frameworkName));
}
string[] components = frameworkName.Split(c_componentSeparator);
// Identifer and Version are required, Profile is optional.
if (components.Length < 2 || components.Length > 3)
{
throw new ArgumentException(SR.Argument_FrameworkNameTooShort, nameof(frameworkName));
}
//
// 1) Parse the "Identifier", which must come first. Trim any whitespace
//
_identifier = components[0].Trim();
if (_identifier.Length == 0)
{
throw new ArgumentException(SR.Argument_FrameworkNameInvalid, nameof(frameworkName));
}
bool versionFound = false;
_profile = String.Empty;
//
// The required "Version" and optional "Profile" component can be in any order
//
for (int i = 1; i < components.Length; i++)
{
// Get the key/value pair separated by '='
string[] keyValuePair = components[i].Split(c_keyValueSeparator);
if (keyValuePair.Length != 2)
{
throw new ArgumentException(SR.Argument_FrameworkNameInvalid, nameof(frameworkName));
}
// Get the key and value, trimming any whitespace
string key = keyValuePair[0].Trim();
string value = keyValuePair[1].Trim();
//
// 2) Parse the required "Version" key value
//
if (key.Equals(c_versionKey, StringComparison.OrdinalIgnoreCase))
{
versionFound = true;
// Allow the version to include a 'v' or 'V' prefix...
if (value.Length > 0 && (value[0] == c_versionValuePrefix || value[0] == 'V'))
{
value = value.Substring(1);
}
try
{
_version = new Version(value);
}
catch (Exception e)
{
throw new ArgumentException(SR.Argument_FrameworkNameInvalidVersion, nameof(frameworkName), e);
}
}
//
// 3) Parse the optional "Profile" key value
//
else if (key.Equals(c_profileKey, StringComparison.OrdinalIgnoreCase))
{
if (!String.IsNullOrEmpty(value))
{
_profile = value;
}
}
else
{
throw new ArgumentException(SR.Argument_FrameworkNameInvalid, nameof(frameworkName));
}
}
if (!versionFound)
{
throw new ArgumentException(SR.Argument_FrameworkNameMissingVersion, nameof(frameworkName));
}
}
#endregion constructors
// -------- SECTION: public static methods -----------------*
#region public static methods
public static Boolean operator ==(FrameworkName left, FrameworkName right)
{
if (Object.ReferenceEquals(left, null))
{
return Object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
public static Boolean operator !=(FrameworkName left, FrameworkName right)
{
return !(left == right);
}
#endregion public static methods
}
}
| |
namespace ghostshockey.it.app.Droid
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Support.V7.Widget;
using AdMaiora.AppKit.UI;
using model.Poco;
public class SpacesItemDecoration : RecyclerView.ItemDecoration
{
private int mSpace;
public SpacesItemDecoration(int space)
{
this.mSpace = space;
}
public override void GetItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
{
outRect.Left = mSpace;
outRect.Right = mSpace;
outRect.Bottom = mSpace;
// Add top margin only for the first item to avoid double space between items
if (parent.GetChildAdapterPosition(view) == 0)
outRect.Top = mSpace;
}
}
#pragma warning disable CS4014
public class TournamentsFragment : AdMaiora.AppKit.UI.App.Fragment
{
#region Inner Classes
class TournamentAdapter : ItemRecyclerAdapter<TournamentAdapter.TournamentViewHolder, Tournament>
{
#region Inner Classes
public class TournamentViewHolder : ItemViewHolder
{
[Widget]
public TextView TitleLabel;
public TournamentViewHolder(View itemView)
: base(itemView)
{
}
}
#endregion
#region Costants and Fields
private Random _rnd;
private List<string> _palette;
private Dictionary<string, string> _colors;
#endregion
#region Constructors
public TournamentAdapter(AdMaiora.AppKit.UI.App.Fragment context, IEnumerable<Tournament> source)
: base(context, Resource.Layout.CellTournament, source)
{
}
#endregion
#region Public Methods
public override void GetView(int postion, TournamentViewHolder holder, View view, Tournament item)
{
Color taskColor = ViewBuilder.ColorFromARGB(AppController.Colors.AshGray);
holder.TitleLabel.Text = item.Name;
holder.TitleLabel.SetTextColor(taskColor);
}
public void Clear()
{
this.SourceItems.Clear();
}
public void Refresh(IEnumerable<Tournament> items)
{
this.SourceItems.Clear();
this.SourceItems.AddRange(items);
}
#endregion
#region Methods
protected override void GetViewCreated(RecyclerView.ViewHolder holder, View view, ViewGroup parent)
{
var cell = holder as TournamentViewHolder;
}
#endregion
}
class YearAdapter : ItemRecyclerAdapter<YearAdapter.YearViewHolder, Year>
{
#region Inner Classes
public class YearViewHolder : ItemViewHolder
{
[Widget]
public TextView TitleLabel;
public YearViewHolder(View itemView)
: base(itemView)
{
}
}
#endregion
#region Costants and Fields
private Random _rnd;
private List<string> _palette;
private Dictionary<string, string> _colors;
#endregion
#region Constructors
public YearAdapter(AdMaiora.AppKit.UI.App.Fragment context, IEnumerable<Year> source)
: base(context, Resource.Layout.CellYear, source)
{
}
#endregion
#region Public Methods
public override void GetView(int postion, YearViewHolder holder, View view, Year item)
{
Color taskColor = ViewBuilder.ColorFromARGB(AppController.Colors.AshGray);
holder.TitleLabel.Text = item.Name;
holder.TitleLabel.SetTextColor(taskColor);
}
public void Clear()
{
this.SourceItems.Clear();
}
public void Refresh(IEnumerable<Year> items)
{
this.SourceItems.Clear();
this.SourceItems.AddRange(items);
}
public void SetAsCompleted(int itemId, bool isComplete, DateTime? completionDate = null)
{
Year item = this.SourceItems.SingleOrDefault(x => x.YearID == itemId);
}
#endregion
#region Methods
protected override void GetViewCreated(RecyclerView.ViewHolder holder, View view, ViewGroup parent)
{
var cell = holder as YearViewHolder;
}
#endregion
}
#endregion
#region Constants and Fields
private int _userId;
private TournamentAdapter _tournamentAdapter;
private YearAdapter _yearAdapter;
private Year _currentYear;
// This flag check if we are already calling the login REST service
private bool _isRefreshingTournaments;
private bool _isRefreshingYears;
// This cancellation token is used to cancel the rest send message request
private CancellationTokenSource _cts0;
#endregion
#region Widgets
[Widget]
private ItemRecyclerView TournamentList;
[Widget]
private ItemRecyclerView YearList;
#endregion
#region Constructors
public TournamentsFragment()
{
}
#endregion
#region Properties
#endregion
#region Fragment Methods
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
_userId = 1; // this.Arguments.GetInt("UserId");
}
public override void OnCreateView(LayoutInflater inflater, ViewGroup container)
{
base.OnCreateView(inflater, container);
#region Desinger Stuff
SetContentView(Resource.Layout.FragmentTournaments, inflater, container);
//this.HasOptionsMenu = false;
#endregion
//this.Title = "Campionati";
this.ActionBar.Hide();
_tournamentAdapter = new TournamentAdapter(this, new Tournament[0]);
this.TournamentList.SetAdapter(_tournamentAdapter);
this.TournamentList.ItemSelected += TournamentList_ItemSelected;
//this.TournamentList.ItemLongPress += TaskList_ItemLongPress;
//this.TournamentList.ItemCommand += TaskList_ItemCommand;
//RecyclerView.ItemDecoration itemDecoration = new SpacesItemDecoration(10);
//this.TournamentList.AddItemDecoration(itemDecoration);
_yearAdapter = new YearAdapter(this, new Year[0]);
this.YearList.SetAdapter(_yearAdapter);
this.YearList.ItemSelected += YearList_ItemSelected;
LinearLayoutManager layoutManager = new LinearLayoutManager(this.Context, LinearLayoutManager.Horizontal, false);
//// Optionally customize the position you want to default scroll to
layoutManager.ScrollToPosition(0);
// Attach layout manager to the RecyclerView
this.YearList.SetLayoutManager(layoutManager);
//this.YearList.ItemLongPress += TaskList_ItemLongPress;
//this.YearList.ItemCommand += TaskList_ItemCommand;
RefreshYears();
}
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
base.OnCreateOptionsMenu(menu, inflater);
menu.Clear();
menu.Add(0, 1, 0, "Add New").SetShowAsAction(ShowAsAction.Always);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch(item.ItemId)
{
case Android.Resource.Id.Home:
QuitAgenda();
return true;
case 1:
//var f = new TaskFragment();
//f.Arguments = new Bundle();
//f.Arguments.PutInt("UserId", _userId);
//this.FragmentManager.BeginTransaction()
// .AddToBackStack("BeforeTaskFragment")
// .Replace(Resource.Id.ContentLayout, f, "TaskFragment")
// .Commit();
return true;
default:
return base.OnOptionsItemSelected(item); ;
}
}
public override bool OnBackButton()
{
QuitAgenda();
return true;
}
public override void OnDestroyView()
{
base.OnDestroyView();
this.YearList.ItemSelected -= YearList_ItemSelected;
this.TournamentList.ItemSelected -= TournamentList_ItemSelected;
}
#endregion
#region Public Methods
#endregion
#region Methods
private void RefreshTournaments()
{
if (_isRefreshingTournaments)
return;
this.TournamentList.Visibility = ViewStates.Gone;
_isRefreshingTournaments = true;
((MainActivity)this.Activity).BlockUI();
_cts0 = new CancellationTokenSource();
AppController.GetTournaments(_currentYear,
(items) =>
{
items = items
.OrderByDescending(x => x.DateStart)
.ToArray();
_tournamentAdapter.Refresh(items);
this.TournamentList.ReloadData();
},
(error) =>
{
Toast.MakeText(this.Activity.ApplicationContext, error, ToastLength.Long).Show();
},
() =>
{
this.TournamentList.Visibility = ViewStates.Visible;
_isRefreshingTournaments = false;
((MainActivity)this.Activity).UnblockUI();
});
}
private void RefreshYears()
{
if (_isRefreshingYears)
return;
this.YearList.Visibility = ViewStates.Gone;
_isRefreshingYears = true;
((MainActivity)this.Activity).BlockUI();
_cts0 = new CancellationTokenSource();
AppController.GetYears(
(items) =>
{
items = items
.OrderByDescending(x => x.DateStart)
.ToArray();
_currentYear = items.FirstOrDefault(y => y.IsCurrent.Value);
RefreshTournaments();
_yearAdapter.Refresh(items);
this.YearList.ReloadData();
},
(error) =>
{
Toast.MakeText(this.Activity.ApplicationContext, error, ToastLength.Long).Show();
},
() =>
{
this.YearList.Visibility = ViewStates.Visible;
_isRefreshingYears = false;
((MainActivity)this.Activity).UnblockUI();
});
}
private void QuitAgenda()
{
//(new AlertDialog.Builder(this.Activity))
// .SetTitle("Leave the agenda?")
// .SetMessage("Press ok to leave the agenda now!")
// .SetPositiveButton("Ok",
// (s, ea) =>
// {
// AppController.Settings.AuthAccessToken = null;
// AppController.Settings.AuthExpirationDate = null;
// this.DismissKeyboard();
// this.FragmentManager.PopBackStack();
// })
// .SetNegativeButton("Take me back",
// (s, ea) =>
// {
// })
// .Show();
}
#endregion
#region Event Handlers
private void YearList_ItemSelected(object sender, ItemListSelectEventArgs e)
{
Year item = e.Item as Year;
_currentYear = item;
RefreshTournaments();
}
private void TournamentList_ItemSelected(object sender, ItemListSelectEventArgs e)
{
Tournament item = e.Item as Tournament;
var f = new MatchesFragment();
f.Arguments = new Bundle();
f.Arguments.PutObject("Item", item);
this.FragmentManager.BeginTransaction()
.AddToBackStack("BeforeTaskFragment")
.Replace(Resource.Id.ContentLayout, f, "MatchesFragment")
.Commit();
}
//private void TaskList_ItemCommand(object sender, ItemListCommandEventArgs e)
//{
// TodoItem item = e.UserData as TodoItem;
// switch (e.Command)
// {
// case "SetAsDone":
// CompleteTodoItem(item, true);
// break;
// case "SetAsNotDone":
// CompleteTodoItem(item, false);
// break;
// }
// this.TaskList.ReloadData();
//}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using TestSupport.Common_TestSupport;
namespace TestSupport
{
/// <summary>
/// The expected range an enumerator will enumerate.
/// </summary>
[Flags]
public enum ExpectedEnumeratorRange { None = 0, Start = 1, End = 2 };
/// <summary>
/// The methods to use for verification
/// </summary>
[Flags]
public enum VerificationMethod { None = 0, Item = 1, Contains = 2, IndexOf = 4, ICollection = 8 };
/// <summary>
/// The verification level
/// </summary>
public enum VerificationLevel { None, Normal, Extensive };
/// <summary>
/// This specifies how the collection is ordered.
/// Sequential specifies that Add places items at the end of the collection and Remove will remove the first item found.
/// Reverse specifies that Add places items at the begining of the collection and Remove will remove the first item found.
/// Unspecified specifies that Add and Remove do not specify where items are added or removed.
/// </summary>
public enum CollectionOrder { Sequential, Unspecified };// TODO: Support ordeered collections
namespace Common_TestSupport
{ /// <summary>
/// Modifies the given collection
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection">The collection to modify</param>
/// <param name="expectedItems">The current items in the collection</param>
/// <returns>The items in the collection after it has been modified.</returns>
public delegate T[] ModifyUnderlyingCollection_T<T>(System.Collections.Generic.IEnumerable<T> collection, T[] expectedItems);
/// <summary>
/// Modifies the given collection
/// </summary>
/// <param name="collection">The collection to modify</param>
/// <param name="expectedItems">The current items in the collection</param>
/// <returns>The items in the collection after it has been modified.</returns>
public delegate Object[] ModifyUnderlyingCollection(IEnumerable collection, Object[] expectedItems);
/// <summary>
/// Creates a new ICollection
/// </summary>
/// <returns></returns>
public delegate ICollection CreateNewICollection();
/// <summary>
/// Generates a new unique item
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>A new unique item.</returns>
public delegate T GenerateItem<T>();
/// <summary>
/// Compares x and y
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>true if x and y are equal else false.</returns>
public delegate bool ItemEquals_T<T>(T x, T y);
/// <summary>
/// Compares x and y
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>true if x and y are equal else false.</returns>
public delegate bool ItemEquals(Object x, Object y);
/// <summary>
/// An action to perform on a Multidimentional array
/// </summary>
/// <param name="array">The array to perform the action on</param>
/// <param name="indicies">The current indicies of the array</param>
public delegate void MultiDimArrayAction(Array array, int[] indicies);
public delegate void ModifyCollection();
/// <summary>
/// Geneartes an exception
/// </summary>
public delegate void ExceptionGenerator();
/// <summary>
/// Test Scenario to run
/// </summary>
/// <returns>true if the test scenario passed else false</returns>
public delegate bool TestScenario();
public class Test
{
/// <summary>
/// The default exit code to use if the test failed
/// </summary>
public const int DEFAULT_FAIL_EXITCODE = 50;
/// <summary>
/// The default exit code to use if the test passed
/// </summary>
public const int PASS_EXITCODE = 100;
private int m_numErrors = 0;
private int m_numTestcaseFailures = 0;
private int m_numTestcases = 0;
private int m_failExitCode = DEFAULT_FAIL_EXITCODE;
private bool m_failExitCodeSet = false;
private bool m_suppressStackOutput = false;
private bool m_outputExceptionMessages = false;
private List<Scenario> m_scenarioDescriptions = new List<Scenario>();
private System.IO.TextWriter m_outputWriter = Console.Out;
private class Scenario
{
public String Description;
public bool DescriptionPrinted;
public Scenario(string description)
{
Description = description;
DescriptionPrinted = false;
}
}
public void InitScenario(string scenarioDescription)
{
m_scenarioDescriptions.Clear();
m_scenarioDescriptions.Add(new Scenario(scenarioDescription));
}
public void PushScenario(string scenarioDescription)
{
m_scenarioDescriptions.Add(new Scenario(scenarioDescription));
}
public void PushScenario(string scenarioDescription, int maxScenarioDepth)
{
while (maxScenarioDepth < m_scenarioDescriptions.Count)
{
m_scenarioDescriptions.RemoveAt(m_scenarioDescriptions.Count - 1);
}
m_scenarioDescriptions.Add(new Scenario(scenarioDescription));
}
public int ScenarioDepth
{
get
{
return m_scenarioDescriptions.Count;
}
}
public void PopScenario()
{
if (0 < m_scenarioDescriptions.Count)
{
m_scenarioDescriptions.RemoveAt(m_scenarioDescriptions.Count - 1);
}
}
public void OutputDebugInfo(string debugInfo)
{
OutputMessage(debugInfo);
}
public void OutputDebugInfo(string format, params object[] args)
{
OutputDebugInfo(String.Format(format, args));
}
private void OutputMessage(string message)
{
if (0 < m_scenarioDescriptions.Count)
{
Scenario currentScenario = m_scenarioDescriptions[m_scenarioDescriptions.Count - 1];
if (!currentScenario.DescriptionPrinted)
{
m_outputWriter.WriteLine();
m_outputWriter.WriteLine();
m_outputWriter.WriteLine("**********************************************************************");
m_outputWriter.WriteLine("** {0,-64} **", "SCENARIO:");
for (int i = 0; i < m_scenarioDescriptions.Count; ++i)
{
m_outputWriter.WriteLine(m_scenarioDescriptions[i].Description);
}
m_outputWriter.WriteLine("**********************************************************************");
currentScenario.DescriptionPrinted = true;
}
}
m_outputWriter.WriteLine(message);
}
/// <summary>
/// If the expression is false writes the message to the console and increments the error count.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="message">The message to print to the console if the expression is false.</param>
/// <returns>true if expression is true else false.</returns>
public bool Eval(bool expression, string message)
{
if (!expression)
{
OutputMessage(message);
++m_numErrors;
Xunit.Assert.True(false, message);
//if(!_suppressStackOutput) {
// System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
// _outputWriter.WriteLine(stackTrace);
//}
m_outputWriter.WriteLine();
}
return expression;
}
/// <summary>
/// If the expression is false outputs the formatted message(String.Format(format, args)
/// and increments the error count.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if expression is true else false.</returns>
public bool Eval(bool expression, String format, params object[] args)
{
if (!expression)
{
return Eval(expression, String.Format(format, args));
}
return true;
}
/// <summary>
/// Compares expected and actual if expected and actual are differnet outputs
/// and increments the error count.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="errorMsg">The message to output.
/// Uses String.Format(errorMsg, expected, actual)</param>
/// <returns>true if expected and actual are equal else false.</returns>
public bool EvalFormatted<T>(T expected, T actual, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, String.Format(errorMsg, expected, actual));
return true;
}
/// <summary>
/// Compares expected and actual if expected and actual are differnet outputs the
/// error message and increments the error count.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="errorMsg">The message to output.</param>
/// <returns>true if expected and actual are equal else false.</returns>
public bool Eval<T>(T expected, T actual, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
public bool Eval<T>(IEqualityComparer<T> comparer, T expected, T actual, String errorMsg)
{
bool retValue = comparer.Equals(expected, actual);
if (!retValue)
return Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
public bool Eval<T>(IComparer<T> comparer, T expected, T actual, String errorMsg)
{
bool retValue = 0 == comparer.Compare(expected, actual);
if (!retValue)
return Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
/// <summary>
/// Compares expected and actual if expected and actual are differnet outputs the
/// error message and increments the error count.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if expected and actual are equal else false.</returns>
public bool Eval<T>(T expected, T actual, String format, params object[] args)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, String.Format(format, args) +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
/// <summary>
/// Runs a test scenario.
/// </summary>
/// <param name="test">The test testscenario to run.</param>
/// <returns>true if the test passed else false.</returns>
public bool RunTestScenario(TestScenario test)
{
bool retValue;
if (test())
{
m_numTestcases++;
retValue = true;
}
else
{
m_numTestcaseFailures++;
retValue = false;
}
m_outputWriter.WriteLine("");
return retValue;
}
/// <summary>
/// The number of failed test cases.
/// </summary>
/// <value>The number of failed test cases.</value>
public int NumberOfFailedTestcases
{
get
{
return m_numTestcaseFailures;
}
}
/// <summary>
/// The number of test cases.
/// </summary>
/// <value>The number of test cases.</value>
public int NumberOfTestcases
{
get
{
return m_numTestcases;
}
}
/// <summary>
/// The number of errors.
/// </summary>
/// <value>The number of errors.</value>
public int NumberOfErrors
{
get
{
return m_numErrors;
}
}
/// <summary>
/// The exit code to use if the test failed.
/// </summary>
/// <value>The exit code to use if the test failed.</value>
public int FailExitCode
{
get
{
return m_failExitCode;
}
set
{
m_failExitCodeSet = true;
m_failExitCode = value;
}
}
/// <summary>
/// The exit code to use.
/// </summary>
/// <value></value>
public int ExitCode
{
get
{
if (Pass)
return PASS_EXITCODE;
return m_failExitCode;
}
}
/// <summary>
/// If the fail exit code was set.
/// </summary>
/// <value>If the fail exit code was set.</value>
public bool IsFailExitCodeSet
{
get
{
return m_failExitCodeSet;
}
}
/// <summary>
/// Returns true if all test cases passed else false.
/// </summary>
/// <value>If all test cases passed else false.</value>
public bool Pass
{
get
{
return 0 == m_numErrors && 0 == m_numTestcaseFailures;
}
}
/// <summary>
/// Determines if the stack is inlcluded with the output
/// </summary>
/// <value>False to output the stack with every failure else true to suppress the stack output</value>
public bool SuppressStackOutput
{
get
{
return m_suppressStackOutput;
}
set
{
m_suppressStackOutput = value;
}
}
public bool OutputExceptionMessages
{
get
{
return m_outputExceptionMessages;
}
set
{
m_outputExceptionMessages = value;
}
}
public System.IO.TextWriter OutputWriter
{
get
{
return m_outputWriter;
}
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
m_outputWriter = value;
}
}
/// <summary>
/// Resets all of the counters.
/// </summary>
public void Reset()
{
m_numErrors = 0;
m_numTestcaseFailures = 0;
m_numTestcases = 0;
m_failExitCodeSet = false;
m_failExitCode = DEFAULT_FAIL_EXITCODE;
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type T.
/// </summary>
/// <typeparam name="T">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <returns>true if exceptionGenerator through an exception of type T else false.</returns>
public bool VerifyException<T>(ExceptionGenerator exceptionGenerator) where T : Exception
{
return VerifyException(typeof(T), exceptionGenerator);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type T.
/// </summary>
/// <typeparam name="T">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <param name="message">The message to output if the verification fails.</param>
/// <returns>true if exceptionGenerator through an exception of type T else false.</returns>
public bool VerifyException<T>(ExceptionGenerator exceptionGenerator, string message) where T : Exception
{
return VerifyException(typeof(T), exceptionGenerator, message);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type T.
/// </summary>
/// <typeparam name="T">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if exceptionGenerator through an exception of type T else false.</returns>
public bool VerifyException<T>(ExceptionGenerator exceptionGenerator, String format, params object[] args) where T : Exception
{
return VerifyException(typeof(T), exceptionGenerator, String.Format(format, args));
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType.
/// </summary>
/// <param name="expectedExceptionType"></param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of
/// type expectedExceptionType.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType else false.</returns>
public bool VerifyException(Type expectedExceptionType, ExceptionGenerator exceptionGenerator)
{
return VerifyException(expectedExceptionType, exceptionGenerator, String.Empty);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType.
/// </summary>
/// <param name="expectedExceptionType">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType else false.</returns>
public bool VerifyException(Type expectedExceptionType, ExceptionGenerator exceptionGenerator, String format, params object[] args)
{
return VerifyException(expectedExceptionType, exceptionGenerator, String.Format(format, args));
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType.
/// </summary>
/// <param name="expectedExceptionType"></param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of
/// type expectedExceptionType.</param>
/// <param name="message">The message to output if the verification fails.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType else false.</returns>
public bool VerifyException(Type expectedExceptionType, ExceptionGenerator exceptionGenerator, string message)
{
bool retValue = true;
try
{
exceptionGenerator();
retValue &= Eval(false, (String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_05940iedz Expected exception of the type {0} to be thrown and nothing was thrown",
expectedExceptionType);
}
catch (Exception exception)
{
retValue &= Eval<Type>(expectedExceptionType, exception.GetType(),
(String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_38223oipwj Expected exception and actual exception differ. Expected {0}, got \n{1}", expectedExceptionType, exception);
if (retValue && m_outputExceptionMessages)
{
OutputDebugInfo("{0} message: {1}" + Environment.NewLine, expectedExceptionType, exception.Message);
}
}
return retValue;
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType1
/// or expectedExceptionType2.
/// </summary>
/// <param name="expectedExceptionType1">The first exception type exceptionGenerator may throw.</param>
/// <param name="expectedExceptionType2">The second exception type exceptionGenerator may throw.</param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type
/// expectedExceptionType1 or expectedExceptionType2.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType1
/// of expectedExceptionType2 else false.</returns>
public bool VerifyException(Type expectedExceptionType1, Type expectedExceptionType2, ExceptionGenerator exceptionGenerator)
{
return VerifyException(new Type[] { expectedExceptionType1, expectedExceptionType2 }, exceptionGenerator);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType1
/// or expectedExceptionType2 or expectedExceptionType3.
/// </summary>
/// <param name="expectedExceptionType1">The first exception type exceptionGenerator may throw.</param>
/// <param name="expectedExceptionType2">The second exception type exceptionGenerator may throw.</param>
/// <param name="expectedExceptionType3">The third exception type exceptionGenerator may throw.</param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type
/// expectedExceptionType1 or expectedExceptionType2 or expectedExceptionType3.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType1
/// or expectedExceptionType2 or expectedExceptionType3 else false.</returns>
public bool VerifyException(Type expectedExceptionType1, Type expectedExceptionType2,
Type expectedExceptionType3, ExceptionGenerator exceptionGenerator)
{
return VerifyException(new Type[] { expectedExceptionType1, expectedExceptionType2, expectedExceptionType3 }, exceptionGenerator);
}
public bool VerifyException(Type[] expectedExceptionTypes, ExceptionGenerator exceptionGenerator)
{
return VerifyException(expectedExceptionTypes, exceptionGenerator, string.Empty);
}
public bool VerifyException(Type[] expectedExceptionTypes, ExceptionGenerator exceptionGenerator, String format, params object[] args)
{
return VerifyException(expectedExceptionTypes, exceptionGenerator, String.Format(format, args));
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of one of types in expectedExceptionTypes.
/// </summary>
/// <param name="expectedExceptionTypes">An array of the expected exception type that exceptionGenerator may throw.</param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of
/// one of the types in expectedExceptionTypes.</param>
/// <returns>true if exceptionGenerator through an exception of one of types in
/// expectedExceptionTypes else false.</returns>
public bool VerifyException(Type[] expectedExceptionTypes, ExceptionGenerator exceptionGenerator, string message)
{
bool retValue = true;
bool exceptionNotThrown = false;
bool exceptionTypeInvalid = true;
Type exceptionType = null;
Exception exceptionInstance = null;
try
{
exceptionGenerator();
exceptionNotThrown = true;
}
catch (Exception exception)
{
exceptionType = exception.GetType();
exceptionInstance = exception;
for (int i = 0; i < expectedExceptionTypes.Length; ++i)
{
if (null != expectedExceptionTypes[i] && exceptionType == expectedExceptionTypes[i]) //null is not a valid exception type
exceptionTypeInvalid = false;
}
}
if (exceptionNotThrown || exceptionTypeInvalid)
{
System.Text.StringBuilder exceptionTypeNames = new System.Text.StringBuilder();
for (int i = 0; i < expectedExceptionTypes.Length; ++i)
{
if (null != expectedExceptionTypes[i])
{
exceptionTypeNames.Append(expectedExceptionTypes[i].ToString());
exceptionTypeNames.Append(" ");
}
}
if (exceptionNotThrown)
{
retValue &= Eval(false, (String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_51584ajied Expected exception of one of the following types to be thrown: {0} and nothing was thrown",
exceptionTypeNames.ToString());
}
else if (exceptionTypeInvalid)
{
retValue &= Eval(false, (String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_51584ajied Expected exception of one of the following types to be thrown: {0} and the following was thrown:\n {1}",
exceptionTypeNames.ToString(), exceptionInstance.ToString());
}
}
return retValue;
}
[Obsolete]
public bool VerifyException(ExceptionGenerator exceptionGenerator, Type expectedExceptionType)
{
bool retValue = true;
try
{
exceptionGenerator();
retValue &= Eval(false, "Err_05940iedz Expected exception of the type {0} to be thrown and nothing was thrown",
expectedExceptionType);
}
catch (Exception exception)
{
retValue &= Eval<Type>(expectedExceptionType, exception.GetType(), "Err_38223oipwj Expected exception and actual exception differ");
}
return retValue;
}
}
public class ArrayUtils
{
/// <summary>
/// Creates array of the parameters.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array">The paramaters to create array from.</param>
/// <returns>An array of the parameters.</returns>
public static T[] Create<T>(params T[] array)
{
return array;
}
/// <summary>
/// Creates and sub array from array
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to create the sub array from.</param>
/// <param name="length">The length of the sub array.</param>
/// <returns>A sub array from array starting at 0 with a length of length.</returns>
public static V[] SubArray<V>(V[] array, int length)
{
return SubArray(array, 0, length);
}
/// <summary>
/// Creates and sub array from array
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to create the sub array from.</param>
/// <param name="startIndex">The start index of the sub array.</param>
/// <param name="length">The length of the sub array.</param>
/// <returns></returns>
public static V[] SubArray<V>(V[] array, int startIndex, int length)
{
V[] tempArray = new V[length];
Array.Copy(array, startIndex, tempArray, 0, length);
return tempArray;
}
/// <summary>
/// Remove item from array.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to remove the item from.</param>
/// <param name="item">The item to remove from the array.</param>
/// <returns>The array with the item removed.</returns>
public static V[] RemoveItem<V>(V[] array, V item)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i].Equals(item))
{
return RemoveAt(array, i);
}
}
return array;
}
/// <summary>
/// Remove item at index from array.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to remove the item from.</param>
/// <param name="index">The index of the item to remove from the array.</param>
/// <returns></returns>
public static V[] RemoveAt<V>(V[] array, int index)
{
V[] tempArray = new V[array.Length - 1];
Array.Copy(array, 0, tempArray, 0, index);
Array.Copy(array, index + 1, tempArray, index, array.Length - index - 1);
return tempArray;
}
public static V[] RemoveRange<V>(V[] array, int startIndex, int count)
{
V[] tempArray = new V[array.Length - count];
Array.Copy(array, 0, tempArray, 0, startIndex);
Array.Copy(array, startIndex + count, tempArray, startIndex, tempArray.Length - startIndex);
return tempArray;
}
public static V[] CopyRanges<V>(V[] array, int startIndex1, int count1, int startIndex2, int count2)
{
V[] tempArray = new V[count1 + count2];
Array.Copy(array, startIndex1, tempArray, 0, count1);
Array.Copy(array, startIndex2, tempArray, count1, count2);
return tempArray;
}
/// <summary>
/// Concatenates of of the items to the end of array1.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array1">The array to concatenate.</param>
/// <param name="array2">The items to concatonate to the end of array1.</param>
/// <returns>An array with all of the items from array1 followed by all of
/// the items from array2.</returns>
public static V[] Concat<V>(V[] array1, params V[] array2)
{
if (array1.Length == 0)
return array2;
if (array2.Length == 0)
return array1;
V[] tempArray = new V[array1.Length + array2.Length];
Array.Copy(array1, 0, tempArray, 0, array1.Length);
Array.Copy(array2, 0, tempArray, array1.Length, array2.Length);
return tempArray;
}
/// <summary>
/// Concatenates of of the items to the begining of array1.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array1">The array to concatenate.</param>
/// <param name="array2">The items to concatonate to the begining of array1.</param>
/// <returns>An array with all of the items from array2 followed by all of
/// the items from array1.</returns>
public static V[] Prepend<V>(V[] array1, params V[] array2)
{
if (array1.Length == 0)
return array2;
if (array2.Length == 0)
return array1;
V[] tempArray = new V[array1.Length + array2.Length];
Array.Copy(array2, 0, tempArray, 0, array2.Length);
Array.Copy(array1, 0, tempArray, array2.Length, array1.Length);
return tempArray;
}
/// <summary>
/// Rverses array.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to revers.</param>
/// <returns>A copy of array with the items reversed.</returns>
public static V[] Reverse<V>(V[] array)
{
return Reverse(array, 0, array.Length);
}
/// <summary>
/// Rverses length items in array starting at index.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to reverse.</param>
/// <param name="index">The index to start reversing items at.</param>
/// <param name="length">The number of items to revers</param>
/// <returns>A copy of array with length items reversed starting at index.</returns>
public static V[] Reverse<V>(V[] array, int index, int length)
{
if (array.Length < 2)
return array;
V[] tempArray = new V[array.Length];
Array.Copy(array, 0, tempArray, 0, array.Length);
Array.Reverse(tempArray, index, length);
return tempArray;
}
/// <summary>
/// Creates an array with a length of size and fills it with the items
/// returned from generatedItem.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="size">The size of the array to create and fill.</param>
/// <param name="generateItem">Returns the items to place into the array.</param>
/// <returns>An array of length size with items returned from generateItem</returns>
public static T[] CreateAndFillArray<T>(int size, GenerateItem<T> generateItem)
{
return FillArray<T>(new T[size], generateItem);
}
/// <summary>
/// Fills array with items returned from generateItem.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array">The array to to place the items in.</param>
/// <param name="generateItem">Returns the items to place into the array.</param>
/// <returns>The array with the items in it returned from generateItem.</returns>
public static T[] FillArray<T>(T[] array, GenerateItem<T> generateItem)
{
int arrayLength = array.Length;
for (int i = 0; i < arrayLength; ++i)
array[i] = generateItem();
return array;
}
}
}
}
| |
// Copyright 2017, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.LongRunning.Snippets
{
public class GeneratedOperationsClientSnippets
{
public async Task GetOperationAsync()
{
// Snippet: GetOperationAsync(string,CallSettings)
// Additional: GetOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
Operation response = await operationsClient.GetOperationAsync(name);
// End snippet
}
public void GetOperation()
{
// Snippet: GetOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
Operation response = operationsClient.GetOperation(name);
// End snippet
}
public async Task GetOperationAsync_RequestObject()
{
// Snippet: GetOperationAsync(GetOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
GetOperationRequest request = new GetOperationRequest
{
Name = "",
};
// Make the request
Operation response = await operationsClient.GetOperationAsync(request);
// End snippet
}
public void GetOperation_RequestObject()
{
// Snippet: GetOperation(GetOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
GetOperationRequest request = new GetOperationRequest
{
Name = "",
};
// Make the request
Operation response = operationsClient.GetOperation(request);
// End snippet
}
public async Task ListOperationsAsync()
{
// Snippet: ListOperationsAsync(string,string,string,int?,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
string filter = "";
// Make the request
PagedAsyncEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperationsAsync(name, filter);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Operation item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListOperationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListOperations()
{
// Snippet: ListOperations(string,string,string,int?,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
string filter = "";
// Make the request
PagedEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperations(name, filter);
// Iterate over all response items, lazily performing RPCs as required
foreach (Operation item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListOperationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task ListOperationsAsync_RequestObject()
{
// Snippet: ListOperationsAsync(ListOperationsRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
ListOperationsRequest request = new ListOperationsRequest
{
Name = "",
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperationsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Operation item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListOperationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListOperations_RequestObject()
{
// Snippet: ListOperations(ListOperationsRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
ListOperationsRequest request = new ListOperationsRequest
{
Name = "",
Filter = "",
};
// Make the request
PagedEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperations(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Operation item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListOperationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task CancelOperationAsync()
{
// Snippet: CancelOperationAsync(string,CallSettings)
// Additional: CancelOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
await operationsClient.CancelOperationAsync(name);
// End snippet
}
public void CancelOperation()
{
// Snippet: CancelOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
operationsClient.CancelOperation(name);
// End snippet
}
public async Task CancelOperationAsync_RequestObject()
{
// Snippet: CancelOperationAsync(CancelOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
CancelOperationRequest request = new CancelOperationRequest
{
Name = "",
};
// Make the request
await operationsClient.CancelOperationAsync(request);
// End snippet
}
public void CancelOperation_RequestObject()
{
// Snippet: CancelOperation(CancelOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
CancelOperationRequest request = new CancelOperationRequest
{
Name = "",
};
// Make the request
operationsClient.CancelOperation(request);
// End snippet
}
public async Task DeleteOperationAsync()
{
// Snippet: DeleteOperationAsync(string,CallSettings)
// Additional: DeleteOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
await operationsClient.DeleteOperationAsync(name);
// End snippet
}
public void DeleteOperation()
{
// Snippet: DeleteOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
operationsClient.DeleteOperation(name);
// End snippet
}
public async Task DeleteOperationAsync_RequestObject()
{
// Snippet: DeleteOperationAsync(DeleteOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
DeleteOperationRequest request = new DeleteOperationRequest
{
Name = "",
};
// Make the request
await operationsClient.DeleteOperationAsync(request);
// End snippet
}
public void DeleteOperation_RequestObject()
{
// Snippet: DeleteOperation(DeleteOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
DeleteOperationRequest request = new DeleteOperationRequest
{
Name = "",
};
// Make the request
operationsClient.DeleteOperation(request);
// End snippet
}
}
}
| |
// <copyright file="TFQMR.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// 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.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra.Solvers;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.LinearAlgebra.Double.Solvers
{
/// <summary>
/// A Transpose Free Quasi-Minimal Residual (TFQMR) iterative matrix solver.
/// </summary>
/// <remarks>
/// <para>
/// The TFQMR algorithm was taken from: <br/>
/// Iterative methods for sparse linear systems.
/// <br/>
/// Yousef Saad
/// <br/>
/// Algorithm is described in Chapter 7, section 7.4.3, page 219
/// </para>
/// <para>
/// The example code below provides an indication of the possible use of the
/// solver.
/// </para>
/// </remarks>
public sealed class TFQMR : IIterativeSolver<double>
{
/// <summary>
/// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax
/// </summary>
/// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param>
/// <param name="residual">Residual values in <see cref="Vector"/>.</param>
/// <param name="x">Instance of the <see cref="Vector"/> x.</param>
/// <param name="b">Instance of the <see cref="Vector"/> b.</param>
static void CalculateTrueResidual(Matrix<double> matrix, Vector<double> residual, Vector<double> x, Vector<double> b)
{
// -Ax = residual
matrix.Multiply(x, residual);
residual.Multiply(-1, residual);
// residual + b
residual.Add(b, residual);
}
/// <summary>
/// Is <paramref name="number"/> even?
/// </summary>
/// <param name="number">Number to check</param>
/// <returns><c>true</c> if <paramref name="number"/> even, otherwise <c>false</c></returns>
static bool IsEven(int number)
{
return number % 2 == 0;
}
/// <summary>
/// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the
/// solution vector and x is the unknown vector.
/// </summary>
/// <param name="matrix">The coefficient matrix, <c>A</c>.</param>
/// <param name="input">The solution vector, <c>b</c></param>
/// <param name="result">The result vector, <c>x</c></param>
/// <param name="iterator">The iterator to use to control when to stop iterating.</param>
/// <param name="preconditioner">The preconditioner to use for approximations.</param>
public void Solve(Matrix<double> matrix, Vector<double> input, Vector<double> result, Iterator<double> iterator, IPreconditioner<double> preconditioner)
{
if (matrix.RowCount != matrix.ColumnCount)
{
throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
}
if (result.Count != input.Count)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (input.Count != matrix.RowCount)
{
throw Matrix.DimensionsDontMatch<ArgumentException>(input, matrix);
}
if (iterator == null)
{
iterator = new Iterator<double>();
}
if (preconditioner == null)
{
preconditioner = new UnitPreconditioner<double>();
}
preconditioner.Initialize(matrix);
var d = new DenseVector(input.Count);
var r = DenseVector.OfVector(input);
var uodd = new DenseVector(input.Count);
var ueven = new DenseVector(input.Count);
var v = new DenseVector(input.Count);
var pseudoResiduals = DenseVector.OfVector(input);
var x = new DenseVector(input.Count);
var yodd = new DenseVector(input.Count);
var yeven = DenseVector.OfVector(input);
// Temp vectors
var temp = new DenseVector(input.Count);
var temp1 = new DenseVector(input.Count);
var temp2 = new DenseVector(input.Count);
// Define the scalars
double alpha = 0;
double eta = 0;
double theta = 0;
// Initialize
var tau = input.L2Norm();
var rho = tau*tau;
// Calculate the initial values for v
// M temp = yEven
preconditioner.Approximate(yeven, temp);
// v = A temp
matrix.Multiply(temp, v);
// Set uOdd
v.CopyTo(ueven);
// Start the iteration
var iterationNumber = 0;
while (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) == IterationStatus.Continue)
{
// First part of the step, the even bit
if (IsEven(iterationNumber))
{
// sigma = (v, r)
var sigma = v.DotProduct(r);
if (sigma.AlmostEqualNumbersBetween(0, 1))
{
// FAIL HERE
iterator.Cancel();
break;
}
// alpha = rho / sigma
alpha = rho/sigma;
// yOdd = yEven - alpha * v
v.Multiply(-alpha, temp1);
yeven.Add(temp1, yodd);
// Solve M temp = yOdd
preconditioner.Approximate(yodd, temp);
// uOdd = A temp
matrix.Multiply(temp, uodd);
}
// The intermediate step which is equal for both even and
// odd iteration steps.
// Select the correct vector
var uinternal = IsEven(iterationNumber) ? ueven : uodd;
var yinternal = IsEven(iterationNumber) ? yeven : yodd;
// pseudoResiduals = pseudoResiduals - alpha * uOdd
uinternal.Multiply(-alpha, temp1);
pseudoResiduals.Add(temp1, temp2);
temp2.CopyTo(pseudoResiduals);
// d = yOdd + theta * theta * eta / alpha * d
d.Multiply(theta*theta*eta/alpha, temp);
yinternal.Add(temp, d);
// theta = ||pseudoResiduals||_2 / tau
theta = pseudoResiduals.L2Norm()/tau;
var c = 1/Math.Sqrt(1 + (theta*theta));
// tau = tau * theta * c
tau *= theta*c;
// eta = c^2 * alpha
eta = c*c*alpha;
// x = x + eta * d
d.Multiply(eta, temp1);
x.Add(temp1, temp2);
temp2.CopyTo(x);
// Check convergence and see if we can bail
if (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) != IterationStatus.Continue)
{
// Calculate the real values
preconditioner.Approximate(x, result);
// Calculate the true residual. Use the temp vector for that
// so that we don't pollute the pseudoResidual vector for no
// good reason.
CalculateTrueResidual(matrix, temp, result, input);
// Now recheck the convergence
if (iterator.DetermineStatus(iterationNumber, result, input, temp) != IterationStatus.Continue)
{
// We're all good now.
return;
}
}
// The odd step
if (!IsEven(iterationNumber))
{
if (rho.AlmostEqualNumbersBetween(0, 1))
{
// FAIL HERE
iterator.Cancel();
break;
}
var rhoNew = pseudoResiduals.DotProduct(r);
var beta = rhoNew/rho;
// Update rho for the next loop
rho = rhoNew;
// yOdd = pseudoResiduals + beta * yOdd
yodd.Multiply(beta, temp1);
pseudoResiduals.Add(temp1, yeven);
// Solve M temp = yOdd
preconditioner.Approximate(yeven, temp);
// uOdd = A temp
matrix.Multiply(temp, ueven);
// v = uEven + beta * (uOdd + beta * v)
v.Multiply(beta, temp1);
uodd.Add(temp1, temp);
temp.Multiply(beta, temp1);
ueven.Add(temp1, v);
}
// Calculate the real values
preconditioner.Approximate(x, result);
iterationNumber++;
}
}
}
}
| |
//#define ASTARDEBUG //Some debugging
//#define ASTAR_NO_JSON
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding.Serialization.JsonFx;
using Pathfinding.Serialization;
using Pathfinding;
namespace Pathfinding {
public interface INavmesh {
//TriangleMeshNode[] TriNodes {get;}
void GetNodes(GraphNodeDelegateCancelable del);
//Int3[] originalVertices {
// get;
// set;
//}
}
[System.Serializable]
[JsonOptIn]
/** Generates graphs based on navmeshes.
\ingroup graphs
Navmeshes are meshes where each polygon define a walkable area.
These are great because the AI can get so much more information on how it can walk.
Polygons instead of points mean that the funnel smoother can produce really nice looking paths and the graphs are also really fast to search
and have a low memory footprint because of their smaller size to describe the same area (compared to grid graphs).
\see Pathfinding.RecastGraph
\shadowimage{navmeshgraph_graph.png}
\shadowimage{navmeshgraph_inspector.png}
*/
public class NavMeshGraph : NavGraph, INavmesh, IUpdatableGraph, IFunnelGraph, INavmeshHolder
{
public override void CreateNodes (int number) {
TriangleMeshNode[] tmp = new TriangleMeshNode[number];
for (int i=0;i<number;i++) {
tmp[i] = new TriangleMeshNode (active);
tmp[i].Penalty = initialPenalty;
}
}
[JsonMember]
public Mesh sourceMesh; /**< Mesh to construct navmesh from */
[JsonMember]
public Vector3 offset; /**< Offset in world space */
[JsonMember]
public Vector3 rotation; /**< Rotation in degrees */
[JsonMember]
public float scale = 1; /**< Scale of the graph */
[JsonMember]
/** More accurate nearest node queries.
* When on, looks for the closest point on every triangle instead of if point is inside the node triangle in XZ space.
* This is slower, but a lot better if your mesh contains overlaps (e.g bridges over other areas of the mesh).
* Note that for maximum effect the Full Get Nearest Node Search setting should be toggled in A* Inspector Settings.
*/
public bool accurateNearestNode = true;
public TriangleMeshNode[] nodes;
public TriangleMeshNode[] TriNodes {
get { return nodes; }
}
public override void GetNodes (GraphNodeDelegateCancelable del) {
if (nodes == null) return;
for (int i=0;i<nodes.Length && del (nodes[i]);i++) {}
}
public override void OnDestroy () {
base.OnDestroy ();
// Cleanup
TriangleMeshNode.SetNavmeshHolder (active.astarData.GetGraphIndex(this), null);
}
public Int3 GetVertex (int index) {
return vertices[index];
}
public int GetVertexArrayIndex (int index) {
return index;
}
public void GetTileCoordinates (int tileIndex, out int x, out int z) {
//Tiles not supported
x = z = 0;
}
/** Bounding Box Tree. Enables really fast lookups of nodes. \astarpro */
BBTree _bbTree;
public BBTree bbTree {
get { return _bbTree; }
set { _bbTree = value;}
}
[System.NonSerialized]
Int3[] _vertices;
public Int3[] vertices {
get {
return _vertices;
}
set {
_vertices = value;
}
}
[System.NonSerialized]
Vector3[] originalVertices;
/*public Int3[] originalVertices {
get { return _originalVertices; }
set { _originalVertices = value; }
}*/
[System.NonSerialized]
public int[] triangles;
public void GenerateMatrix () {
SetMatrix (Matrix4x4.TRS (offset,Quaternion.Euler (rotation),new Vector3 (scale,scale,scale)));
}
/** Relocates the nodes to match the newMatrix.
* The "oldMatrix" variable can be left out in this function call (only for this graph generator) since it is not used */
public override void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix) {
//base.RelocateNodes (oldMatrix,newMatrix);
if (vertices == null || vertices.Length == 0 || originalVertices == null || originalVertices.Length != vertices.Length) {
return;
}
for (int i=0;i<_vertices.Length;i++) {
//Vector3 tmp = inv.MultiplyPoint3x4 (vertices[i]);
//vertices[i] = (Int3)newMatrix.MultiplyPoint3x4 (tmp);
_vertices[i] = (Int3)newMatrix.MultiplyPoint3x4 ((Vector3)originalVertices[i]);
}
for (int i=0;i<nodes.Length;i++) {
TriangleMeshNode node = (TriangleMeshNode)nodes[i];
node.UpdatePositionFromVertices();
if (node.connections != null) {
for (int q=0;q<node.connections.Length;q++) {
node.connectionCosts[q] = (uint)(node.position-node.connections[q].position).costMagnitude;
}
}
}
SetMatrix (newMatrix);
}
public static NNInfo GetNearest (NavMeshGraph graph, GraphNode[] nodes, Vector3 position, NNConstraint constraint, bool accurateNearestNode) {
if (nodes == null || nodes.Length == 0) {
Debug.LogError ("NavGraph hasn't been generated yet or does not contain any nodes");
return new NNInfo ();
}
if (constraint == null) constraint = NNConstraint.None;
return GetNearestForceBoth (graph,graph, position, NNConstraint.None, accurateNearestNode);
}
public override NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
return GetNearest (this, nodes,position, constraint, accurateNearestNode);
}
/** This performs a linear search through all polygons returning the closest one.
* This is usually only called in the Free version of the A* Pathfinding Project since the Pro one supports BBTrees and will do another query
*/
public override NNInfo GetNearestForce (Vector3 position, NNConstraint constraint) {
return GetNearestForce (this, this,position,constraint, accurateNearestNode);
//Debug.LogWarning ("This function shouldn't be called since constrained nodes are sent back in the GetNearest call");
//return new NNInfo ();
}
/** This performs a linear search through all polygons returning the closest one */
public static NNInfo GetNearestForce (NavGraph graph, INavmeshHolder navmesh, Vector3 position, NNConstraint constraint, bool accurateNearestNode) {
NNInfo nn = GetNearestForceBoth (graph, navmesh,position,constraint,accurateNearestNode);
nn.node = nn.constrainedNode;
nn.clampedPosition = nn.constClampedPosition;
return nn;
}
/** This performs a linear search through all polygons returning the closest one.
* This will fill the NNInfo with .node for the closest node not necessarily complying with the NNConstraint, and .constrainedNode with the closest node
* complying with the NNConstraint.
* \see GetNearestForce(Node[],Int3[],Vector3,NNConstraint,bool)
*/
public static NNInfo GetNearestForceBoth (NavGraph graph, INavmeshHolder navmesh, Vector3 position, NNConstraint constraint, bool accurateNearestNode) {
Int3 pos = (Int3)position;
float minDist = -1;
GraphNode minNode = null;
float minConstDist = -1;
GraphNode minConstNode = null;
float maxDistSqr = constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
GraphNodeDelegateCancelable del = delegate (GraphNode _node) {
TriangleMeshNode node = _node as TriangleMeshNode;
if (accurateNearestNode) {
Vector3 closest = node.ClosestPointOnNode (position);
float dist = ((Vector3)pos-closest).sqrMagnitude;
if (minNode == null || dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < maxDistSqr && constraint.Suitable (node)) {
if (minConstNode == null || dist < minConstDist) {
minConstDist = dist;
minConstNode = node;
}
}
} else {
if (!node.ContainsPoint ((Int3)position)) {
float dist = (node.position-pos).sqrMagnitude;
if (minNode == null || dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < maxDistSqr && constraint.Suitable (node)) {
if (minConstNode == null || dist < minConstDist) {
minConstDist = dist;
minConstNode = node;
}
}
} else {
int dist = AstarMath.Abs (node.position.y-pos.y);
if (minNode == null || dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < maxDistSqr && constraint.Suitable (node)) {
if (minConstNode == null || dist < minConstDist) {
minConstDist = dist;
minConstNode = node;
}
}
}
}
return true;
};
graph.GetNodes (del);
NNInfo nninfo = new NNInfo (minNode);
//Find the point closest to the nearest triangle
if (nninfo.node != null) {
TriangleMeshNode node = nninfo.node as TriangleMeshNode;//minNode2 as MeshNode;
Vector3 clP = node.ClosestPointOnNode (position);
nninfo.clampedPosition = clP;
}
nninfo.constrainedNode = minConstNode;
if (nninfo.constrainedNode != null) {
TriangleMeshNode node = nninfo.constrainedNode as TriangleMeshNode;//minNode2 as MeshNode;
Vector3 clP = node.ClosestPointOnNode (position);
nninfo.constClampedPosition = clP;
}
return nninfo;
}
public void BuildFunnelCorridor (List<GraphNode> path, int startIndex, int endIndex, List<Vector3> left, List<Vector3> right) {
BuildFunnelCorridor (this,path,startIndex,endIndex,left,right);
}
public static void BuildFunnelCorridor (INavmesh graph, List<GraphNode> path, int startIndex, int endIndex, List<Vector3> left, List<Vector3> right) {
if (graph == null) {
Debug.LogError ("Couldn't cast graph to the appropriate type (graph isn't a Navmesh type graph, it doesn't implement the INavmesh interface)");
return;
}
for (int i=startIndex;i<endIndex;i++) {
//Find the connection between the nodes
TriangleMeshNode n1 = path[i] as TriangleMeshNode;
TriangleMeshNode n2 = path[i+1] as TriangleMeshNode;
int a;
bool search = true;
for (a=0;a<3;a++) {
for (int b=0;b<3;b++) {
if (n1.GetVertexIndex(a) == n2.GetVertexIndex((b+1)%3) && n1.GetVertexIndex((a+1)%3) == n2.GetVertexIndex(b)) {
search = false;
break;
}
}
if (!search) break;
}
if (a == 3) {
left.Add ((Vector3)n1.position);
right.Add ((Vector3)n1.position);
left.Add ((Vector3)n2.position);
right.Add ((Vector3)n2.position);
} else {
left.Add ((Vector3)n1.GetVertex(a));
right.Add ((Vector3)n1.GetVertex((a+1)%3));
}
}
}
public void AddPortal (GraphNode n1, GraphNode n2, List<Vector3> left, List<Vector3> right) {
}
public GraphUpdateThreading CanUpdateAsync (GraphUpdateObject o) {
return GraphUpdateThreading.UnityThread;
}
public void UpdateAreaInit (GraphUpdateObject o) {}
public void UpdateArea (GraphUpdateObject o) {
}
public static void UpdateArea (GraphUpdateObject o, INavmesh graph) {
//System.DateTime startTime = System.DateTime.UtcNow;
Bounds bounds = o.bounds;
Rect r = Rect.MinMaxRect (bounds.min.x,bounds.min.z,bounds.max.x,bounds.max.z);
IntRect r2 = new IntRect(
Mathf.FloorToInt(bounds.min.x*Int3.Precision),
Mathf.FloorToInt(bounds.min.z*Int3.Precision),
Mathf.FloorToInt(bounds.max.x*Int3.Precision),
Mathf.FloorToInt(bounds.max.z*Int3.Precision)
);
/*Vector3 a = new Vector3 (r.xMin,0,r.yMin);// -1 -1
Vector3 b = new Vector3 (r.xMin,0,r.yMax);// -1 1
Vector3 c = new Vector3 (r.xMax,0,r.yMin);// 1 -1
Vector3 d = new Vector3 (r.xMax,0,r.yMax);// 1 1
*/
Int3 a = new Int3(r2.xmin,0,r2.ymin);
Int3 b = new Int3(r2.xmin,0,r2.ymax);
Int3 c = new Int3(r2.xmax,0,r2.ymin);
Int3 d = new Int3(r2.xmax,0,r2.ymax);
Int3 ia = (Int3)a;
Int3 ib = (Int3)b;
Int3 ic = (Int3)c;
Int3 id = (Int3)d;
//for (int i=0;i<nodes.Length;i++) {
graph.GetNodes (delegate (GraphNode _node) {
TriangleMeshNode node = _node as TriangleMeshNode;
bool inside = false;
int allLeft = 0;
int allRight = 0;
int allTop = 0;
int allBottom = 0;
for (int v=0;v<3;v++) {
Int3 p = node.GetVertex(v);
Vector3 vert = (Vector3)p;
//Vector2 vert2D = new Vector2 (vert.x,vert.z);
if (r2.Contains (p.x,p.z)) {
//Debug.DrawRay (vert,Vector3.up*10,Color.yellow);
inside = true;
break;
}
if (vert.x < r.xMin) allLeft++;
if (vert.x > r.xMax) allRight++;
if (vert.z < r.yMin) allTop++;
if (vert.z > r.yMax) allBottom++;
//if (!bounds.Contains (node[v]) {
// inside = false;
// break;
//}
}
if (!inside) {
if (allLeft == 3 || allRight == 3 || allTop == 3 || allBottom == 3) {
return true;
}
}
//Debug.DrawLine ((Vector3)node.GetVertex(0),(Vector3)node.GetVertex(1),Color.yellow);
//Debug.DrawLine ((Vector3)node.GetVertex(1),(Vector3)node.GetVertex(2),Color.yellow);
//Debug.DrawLine ((Vector3)node.GetVertex(2),(Vector3)node.GetVertex(0),Color.yellow);
for (int v=0;v<3;v++) {
int v2 = v > 1 ? 0 : v+1;
Int3 vert1 = node.GetVertex(v);
Int3 vert2 = node.GetVertex(v2);
if (Polygon.Intersects (a,b,vert1,vert2)) { inside = true; break; }
if (Polygon.Intersects (a,c,vert1,vert2)) { inside = true; break; }
if (Polygon.Intersects (c,d,vert1,vert2)) { inside = true; break; }
if (Polygon.Intersects (d,b,vert1,vert2)) { inside = true; break; }
}
if (node.ContainsPoint (ia) || node.ContainsPoint (ib) || node.ContainsPoint (ic) || node.ContainsPoint (id)) {
inside = true;
}
if (!inside) {
return true;
}
o.WillUpdateNode(node);
o.Apply (node);
/*Debug.DrawLine ((Vector3)node.GetVertex(0),(Vector3)node.GetVertex(1),Color.blue);
Debug.DrawLine ((Vector3)node.GetVertex(1),(Vector3)node.GetVertex(2),Color.blue);
Debug.DrawLine ((Vector3)node.GetVertex(2),(Vector3)node.GetVertex(0),Color.blue);
Debug.Break ();*/
return true;
});
//System.DateTime endTime = System.DateTime.UtcNow;
//float theTime = (endTime-startTime).Ticks*0.0001F;
//Debug.Log ("Intersecting bounds with navmesh took "+theTime.ToString ("0.000")+" ms");
}
/** Returns the closest point of the node */
public static Vector3 ClosestPointOnNode (TriangleMeshNode node, Int3[] vertices, Vector3 pos) {
return Polygon.ClosestPointOnTriangle ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1],(Vector3)vertices[node.v2],pos);
}
/** Returns if the point is inside the node in XZ space */
public bool ContainsPoint (TriangleMeshNode node, Vector3 pos) {
if ( Polygon.IsClockwise ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1], pos)
&& Polygon.IsClockwise ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2], pos)
&& Polygon.IsClockwise ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0], pos)) {
return true;
}
return false;
}
/** Returns if the point is inside the node in XZ space */
public static bool ContainsPoint (TriangleMeshNode node, Vector3 pos, Int3[] vertices) {
if (!Polygon.IsClockwiseMargin ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1], (Vector3)vertices[node.v2])) {
Debug.LogError ("Noes!");
}
if ( Polygon.IsClockwiseMargin ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1], pos)
&& Polygon.IsClockwiseMargin ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2], pos)
&& Polygon.IsClockwiseMargin ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0], pos)) {
return true;
}
return false;
}
/** Scans the graph using the path to an .obj mesh */
public void ScanInternal (string objMeshPath) {
Mesh mesh = ObjImporter.ImportFile (objMeshPath);
if (mesh == null) {
Debug.LogError ("Couldn't read .obj file at '"+objMeshPath+"'");
return;
}
sourceMesh = mesh;
ScanInternal ();
}
public override void ScanInternal (OnScanStatus statusCallback) {
if (sourceMesh == null) {
return;
}
GenerateMatrix ();
//float startTime = 0;//Time.realtimeSinceStartup;
Vector3[] vectorVertices = sourceMesh.vertices;
triangles = sourceMesh.triangles;
TriangleMeshNode.SetNavmeshHolder (active.astarData.GetGraphIndex(this),this);
GenerateNodes (vectorVertices,triangles, out originalVertices, out _vertices);
}
/** Generates a navmesh. Based on the supplied vertices and triangles. Memory usage is about O(n) */
public void GenerateNodes (Vector3[] vectorVertices, int[] triangles, out Vector3[] originalVertices, out Int3[] vertices) {
Profiler.BeginSample ("Init");
if (vectorVertices.Length == 0 || triangles.Length == 0) {
originalVertices = vectorVertices;
vertices = new Int3[0];
//graph.CreateNodes (0);
nodes = new TriangleMeshNode[0];
return;
}
vertices = new Int3[vectorVertices.Length];
//Backup the original vertices
//for (int i=0;i<vectorVertices.Length;i++) {
// vectorVertices[i] = graph.matrix.MultiplyPoint (vectorVertices[i]);
//}
int c = 0;
for (int i=0;i<vertices.Length;i++) {
vertices[i] = (Int3)matrix.MultiplyPoint3x4 (vectorVertices[i]);
}
Dictionary<Int3,int> hashedVerts = new Dictionary<Int3,int> ();
int[] newVertices = new int[vertices.Length];
Profiler.EndSample ();
Profiler.BeginSample ("Hashing");
for (int i=0;i<vertices.Length;i++) {
if (!hashedVerts.ContainsKey (vertices[i])) {
newVertices[c] = i;
hashedVerts.Add (vertices[i], c);
c++;
}// else {
//Debug.Log ("Hash Duplicate "+hash+" "+vertices[i].ToString ());
//}
}
/*newVertices[c] = vertices.Length-1;
if (!hashedVerts.ContainsKey (vertices[newVertices[c]])) {
hashedVerts.Add (vertices[newVertices[c]], c);
c++;
}*/
for (int x=0;x<triangles.Length;x++) {
Int3 vertex = vertices[triangles[x]];
triangles[x] = hashedVerts[vertex];
}
/*for (int i=0;i<triangles.Length;i += 3) {
Vector3 offset = Vector3.forward*i*0.01F;
Debug.DrawLine (newVertices[triangles[i]]+offset,newVertices[triangles[i+1]]+offset,Color.blue);
Debug.DrawLine (newVertices[triangles[i+1]]+offset,newVertices[triangles[i+2]]+offset,Color.blue);
Debug.DrawLine (newVertices[triangles[i+2]]+offset,newVertices[triangles[i]]+offset,Color.blue);
}*/
Int3[] totalIntVertices = vertices;
vertices = new Int3[c];
originalVertices = new Vector3[c];
for (int i=0;i<c;i++) {
vertices[i] = totalIntVertices[newVertices[i]];//(Int3)graph.matrix.MultiplyPoint (vectorVertices[i]);
originalVertices[i] = (Vector3)vectorVertices[newVertices[i]];//vectorVertices[newVertices[i]];
}
Profiler.EndSample ();
Profiler.BeginSample ("Constructing Nodes");
//graph.CreateNodes (triangles.Length/3);//new Node[triangles.Length/3];
nodes = new TriangleMeshNode[triangles.Length/3];
for (int i=0;i<nodes.Length;i++) {
nodes[i] = new TriangleMeshNode(active);
TriangleMeshNode node = nodes[i];//new MeshNode ();
node.Penalty = initialPenalty;
node.Walkable = true;
node.v0 = triangles[i*3];
node.v1 = triangles[i*3+1];
node.v2 = triangles[i*3+2];
if (!Polygon.IsClockwise (vertices[node.v0],vertices[node.v1],vertices[node.v2])) {
//Debug.DrawLine (vertices[node.v0],vertices[node.v1],Color.red);
//Debug.DrawLine (vertices[node.v1],vertices[node.v2],Color.red);
//Debug.DrawLine (vertices[node.v2],vertices[node.v0],Color.red);
int tmp = node.v0;
node.v0 = node.v2;
node.v2 = tmp;
}
if (Polygon.IsColinear (vertices[node.v0],vertices[node.v1],vertices[node.v2])) {
Debug.DrawLine ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1],Color.red);
Debug.DrawLine ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2],Color.red);
Debug.DrawLine ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0],Color.red);
}
// Make sure position is correctly set
node.UpdatePositionFromVertices();
}
Profiler.EndSample ();
Dictionary<Int2,TriangleMeshNode> sides = new Dictionary<Int2, TriangleMeshNode>();
for (int i=0, j=0;i<triangles.Length; j+=1, i+=3) {
sides[new Int2(triangles[i+0],triangles[i+1])] = nodes[j];
sides[new Int2(triangles[i+1],triangles[i+2])] = nodes[j];
sides[new Int2(triangles[i+2],triangles[i+0])] = nodes[j];
}
Profiler.BeginSample ("Connecting Nodes");
List<MeshNode> connections = new List<MeshNode> ();
List<uint> connectionCosts = new List<uint> ();
int identicalError = 0;
for (int i=0, j=0;i<triangles.Length; j+=1, i+=3) {
connections.Clear ();
connectionCosts.Clear ();
//Int3 indices = new Int3(triangles[i],triangles[i+1],triangles[i+2]);
TriangleMeshNode node = nodes[j];
for ( int q = 0; q < 3; q++ ) {
TriangleMeshNode other;
if (sides.TryGetValue ( new Int2 (triangles[i+((q+1)%3)], triangles[i+q]), out other ) ) {
connections.Add (other);
connectionCosts.Add ((uint)(node.position-other.position).costMagnitude);
}
}
node.connections = connections.ToArray ();
node.connectionCosts = connectionCosts.ToArray ();
}
if (identicalError > 0) {
Debug.LogError ("One or more triangles are identical to other triangles, this is not a good thing to have in a navmesh\nIncreasing the scale of the mesh might help\nNumber of triangles with error: "+identicalError+"\n");
}
Profiler.EndSample ();
Profiler.BeginSample ("Rebuilding BBTree");
RebuildBBTree (this);
Profiler.EndSample ();
//Debug.Log ("Graph Generation - NavMesh - Time to compute graph "+((Time.realtimeSinceStartup-startTime)*1000F).ToString ("0")+"ms");
}
/** Rebuilds the BBTree on a NavGraph.
* \astarpro
* \see NavMeshGraph.bbTree */
public static void RebuildBBTree (NavMeshGraph graph) {
//BBTrees is a A* Pathfinding Project Pro only feature - The Pro version can be bought in the Unity Asset Store or on arongranberg.com
}
public void PostProcess () {
}
public void Sort (Vector3[] a) {
bool changed = true;
while (changed) {
changed = false;
for (int i=0;i<a.Length-1;i++) {
if (a[i].x > a[i+1].x || (a[i].x == a[i+1].x && (a[i].y > a[i+1].y || (a[i].y == a[i+1].y && a[i].z > a[i+1].z)))) {
Vector3 tmp = a[i];
a[i] = a[i+1];
a[i+1] = tmp;
changed = true;
}
}
}
}
public override void OnDrawGizmos (bool drawNodes) {
if (!drawNodes) {
return;
}
Matrix4x4 preMatrix = matrix;
GenerateMatrix ();
if (nodes == null) {
//Scan ();
}
if (nodes == null) {
return;
}
if ( bbTree != null ) {
bbTree.OnDrawGizmos ();
}
if (preMatrix != matrix) {
//Debug.Log ("Relocating Nodes");
RelocateNodes (preMatrix, matrix);
}
PathHandler debugData = AstarPath.active.debugPathData;
for (int i=0;i<nodes.Length;i++) {
TriangleMeshNode node = (TriangleMeshNode)nodes[i];
Gizmos.color = NodeColor (node,AstarPath.active.debugPathData);
if (node.Walkable ) {
if (AstarPath.active.showSearchTree && debugData != null && debugData.GetPathNode(node).parent != null) {
Gizmos.DrawLine ((Vector3)node.position,(Vector3)debugData.GetPathNode(node).parent.node.position);
} else {
for (int q=0;q<node.connections.Length;q++) {
Gizmos.DrawLine ((Vector3)node.position,Vector3.Lerp ((Vector3)node.position, (Vector3)node.connections[q].position, 0.45f));
}
}
Gizmos.color = AstarColor.MeshEdgeColor;
} else {
Gizmos.color = Color.red;
}
Gizmos.DrawLine ((Vector3)vertices[node.v0],(Vector3)vertices[node.v1]);
Gizmos.DrawLine ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2]);
Gizmos.DrawLine ((Vector3)vertices[node.v2],(Vector3)vertices[node.v0]);
}
}
public override void DeserializeExtraInfo (GraphSerializationContext ctx)
{
uint graphIndex = (uint)active.astarData.GetGraphIndex(this);
TriangleMeshNode.SetNavmeshHolder ((int)graphIndex,this);
int c1 = ctx.reader.ReadInt32();
int c2 = ctx.reader.ReadInt32();
if (c1 == -1) {
nodes = new TriangleMeshNode[0];
_vertices = new Int3[0];
originalVertices = new Vector3[0];
}
nodes = new TriangleMeshNode[c1];
_vertices = new Int3[c2];
originalVertices = new Vector3[c2];
for (int i=0;i<c2;i++) {
_vertices[i] = new Int3(ctx.reader.ReadInt32(), ctx.reader.ReadInt32(), ctx.reader.ReadInt32());
originalVertices[i] = new Vector3(ctx.reader.ReadSingle(), ctx.reader.ReadSingle(), ctx.reader.ReadSingle());
}
for (int i=0;i<c1;i++) {
nodes[i] = new TriangleMeshNode(active);
TriangleMeshNode node = nodes[i];
node.DeserializeNode(ctx);
node.GraphIndex = graphIndex;
node.UpdatePositionFromVertices();
}
}
public override void SerializeExtraInfo (GraphSerializationContext ctx)
{
if (nodes == null || originalVertices == null || _vertices == null || originalVertices.Length != _vertices.Length) {
ctx.writer.Write (-1);
ctx.writer.Write (-1);
return;
}
ctx.writer.Write(nodes.Length);
ctx.writer.Write(_vertices.Length);
for (int i=0;i<_vertices.Length;i++) {
ctx.writer.Write (_vertices[i].x);
ctx.writer.Write (_vertices[i].y);
ctx.writer.Write (_vertices[i].z);
ctx.writer.Write (originalVertices[i].x);
ctx.writer.Write (originalVertices[i].y);
ctx.writer.Write (originalVertices[i].z);
}
for (int i=0;i<nodes.Length;i++) {
nodes[i].SerializeNode (ctx);
}
}
public static void DeserializeMeshNodes (NavMeshGraph graph, GraphNode[] nodes, byte[] bytes) {
System.IO.MemoryStream mem = new System.IO.MemoryStream(bytes);
System.IO.BinaryReader stream = new System.IO.BinaryReader(mem);
for (int i=0;i<nodes.Length;i++) {
TriangleMeshNode node = nodes[i] as TriangleMeshNode;
if (node == null) {
Debug.LogError ("Serialization Error : Couldn't cast the node to the appropriate type - NavMeshGenerator");
return;
}
node.v0 = stream.ReadInt32 ();
node.v1 = stream.ReadInt32 ();
node.v2 = stream.ReadInt32 ();
}
int numVertices = stream.ReadInt32 ();
graph.vertices = new Int3[numVertices];
for (int i=0;i<numVertices;i++) {
int x = stream.ReadInt32 ();
int y = stream.ReadInt32 ();
int z = stream.ReadInt32 ();
graph.vertices[i] = new Int3 (x,y,z);
}
RebuildBBTree (graph);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
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.
*/
/// <summary>
/// .NET's built-in <see cref="ThreadLocal{T}"/> has a serious flaw:
/// internally, it creates an array with an internal lattice structure
/// which in turn causes the garbage collector to cause long blocking pauses
/// when tearing the structure down. See
/// <a href="https://ayende.com/blog/189761-A/production-postmortem-the-slow-slowdown-of-large-systems">
/// https://ayende.com/blog/189761-A/production-postmortem-the-slow-slowdown-of-large-systems</a>
/// for a more detailed explanation.
/// <para/>
/// This is a completely different problem than in Java which the ClosableThreadLocal<T> class is
/// meant to solve, so <see cref="DisposableThreadLocal{T}"/> is specific to Lucene.NET and can be used
/// as a direct replacement for ClosableThreadLocal<T>.
/// <para/>
/// This class works around the issue by using an alternative approach than using <see cref="ThreadLocal{T}"/>.
/// It keeps track of each thread's local and global state in order to later optimize garbage collection.
/// A complete explanation can be found at
/// <a href="https://ayende.com/blog/189793-A/the-design-and-implementation-of-a-better-threadlocal-t">
/// https://ayende.com/blog/189793-A/the-design-and-implementation-of-a-better-threadlocal-t</a>.
/// <para/>
/// @lucene.internal
/// </summary>
/// <typeparam name="T">Specifies the type of data stored per-thread.</typeparam>
public sealed class DisposableThreadLocal<T> : IDisposable
{
[ThreadStatic]
private static CurrentThreadState _state;
private readonly WeakReferenceCompareValue<DisposableThreadLocal<T>> selfReference;
private ConcurrentDictionary<WeakReferenceCompareValue<CurrentThreadState>, T> _values = new ConcurrentDictionary<WeakReferenceCompareValue<CurrentThreadState>, T>();
private readonly Func<T> _valueFactory;
private bool _disposed;
private static int globalVersion;
/// <summary>
/// Initializes the <see cref="DisposableThreadLocal{T}"/> instance.
/// </summary>
/// <remarks>
/// The default value of <typeparamref name="T"/> is used to initialize
/// the instance when <see cref="Value"/> is accessed for the first time.
/// </remarks>
public DisposableThreadLocal()
{
selfReference = new WeakReferenceCompareValue<DisposableThreadLocal<T>>(this);
}
/// <summary>
/// Initializes the <see cref="DisposableThreadLocal{T}"/> instance with the
/// specified <paramref name="valueFactory"/> function.
/// </summary>
/// <param name="valueFactory">The <see cref="Func{T, TResult}"/> 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="ArgumentNullException"><paramref name="valueFactory"/> is <c>null</c>.</exception>
public DisposableThreadLocal(Func<T> valueFactory)
{
_valueFactory = valueFactory ?? throw new ArgumentNullException(nameof(valueFactory));
selfReference = new WeakReferenceCompareValue<DisposableThreadLocal<T>>(this);
}
/// <summary>
/// Gets a collection for all of the values currently stored by all of the threads that have accessed this instance.
/// </summary>
/// <exception cref="ObjectDisposedException">The <see cref="DisposableThreadLocal{T}"/> instance has been disposed.</exception>
public ICollection<T> Values
{
get
{
if (_disposed)
throw new ObjectDisposedException(nameof(DisposableThreadLocal<T>));
return _values.Values;
}
}
/// <summary>
/// Gets whether Value is initialized on the current thread.
/// </summary>
/// <exception cref="ObjectDisposedException">The <see cref="DisposableThreadLocal{T}"/> instance has been disposed.</exception>
public bool IsValueCreated
{
get
{
if (_disposed)
throw new ObjectDisposedException(nameof(DisposableThreadLocal<T>));
return _state != null && _values.ContainsKey(_state.selfReference);
}
}
[Obsolete("Use Value instead. This method will be removed in 4.8.0 release candidate.")]
public T Get() => Value;
[Obsolete("Use Value instead. This method will be removed in 4.8.0 release candidate.")]
public void Set(T value) => Value = value;
/// <summary>
/// Gets or sets the value of this instance for the current thread.
/// </summary>
/// <exception cref="ObjectDisposedException">The <see cref="DisposableThreadLocal{T}"/> instance has been disposed.</exception>
/// <remarks>
/// If this instance was not previously initialized for the current thread, accessing 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>
public T Value
{
get
{
if (_disposed)
throw new ObjectDisposedException(nameof(DisposableThreadLocal<T>));
(_state ??= new CurrentThreadState()).Register(this);
if (_values.TryGetValue(_state.selfReference, out var v) == false &&
_valueFactory != null)
{
v = _valueFactory();
_values[_state.selfReference] = v;
}
return v;
}
set
{
if (_disposed)
throw new ObjectDisposedException(nameof(DisposableThreadLocal<T>));
(_state ??= new CurrentThreadState()).Register(this);
_values[_state.selfReference] = value;
}
}
/// <summary>
/// Releases the resources used by this <see cref="DisposableThreadLocal{T}"/> instance.
/// </summary>
public void Dispose()
{
var copy = _values;
if (copy == null)
return;
copy = Interlocked.CompareExchange(ref _values, null, copy);
if (copy == null)
return;
Interlocked.Increment(ref globalVersion);
_disposed = true;
_values = null;
}
private sealed class CurrentThreadState
{
private readonly HashSet<WeakReferenceCompareValue<DisposableThreadLocal<T>>> _parents
= new HashSet<WeakReferenceCompareValue<DisposableThreadLocal<T>>>();
public readonly WeakReferenceCompareValue<CurrentThreadState> selfReference;
private readonly LocalState _localState = new LocalState();
public CurrentThreadState()
{
selfReference = new WeakReferenceCompareValue<CurrentThreadState>(this);
}
public void Register(DisposableThreadLocal<T> parent)
{
_parents.Add(parent.selfReference);
int localVersion = _localState.localVersion;
var globalVersion = DisposableThreadLocal<T>.globalVersion;
if (localVersion != globalVersion)
{
// a thread local instance was disposed, let's check
// if we need to do cleanup here
RemoveDisposedParents();
_localState.localVersion = globalVersion;
}
}
private void RemoveDisposedParents()
{
var toRemove = new List<WeakReferenceCompareValue<DisposableThreadLocal<T>>>();
foreach (var local in _parents)
{
if (local.TryGetTarget(out var target) == false || target._disposed)
{
toRemove.Add(local);
}
}
foreach (var remove in toRemove)
{
_parents.Remove(remove);
}
}
~CurrentThreadState()
{
foreach (var parent in _parents)
{
if (parent.TryGetTarget(out var liveParent) == false)
continue;
var copy = liveParent._values;
if (copy == null)
continue;
copy.TryRemove(selfReference, out _);
}
}
}
private sealed class WeakReferenceCompareValue<TK> : IEquatable<WeakReferenceCompareValue<TK>>
where TK : class
{
private readonly WeakReference<TK> _weak;
private readonly int _hashCode;
public bool TryGetTarget(out TK target)
{
return _weak.TryGetTarget(out target);
}
public WeakReferenceCompareValue(TK instance)
{
_hashCode = instance.GetHashCode();
_weak = new WeakReference<TK>(instance);
}
public bool Equals(WeakReferenceCompareValue<TK> other)
{
if (other is null)
return false;
if (ReferenceEquals(this, other))
return true;
if (_hashCode != other._hashCode)
return false;
if (_weak.TryGetTarget(out var x) == false ||
other._weak.TryGetTarget(out var y) == false)
return false;
return ReferenceEquals(x, y);
}
public override bool Equals(object obj)
{
if (obj is null)
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() == typeof(TK))
{
int hashCode = obj.GetHashCode();
if (hashCode != _hashCode)
return false;
if (_weak.TryGetTarget(out var other) == false)
return false;
return ReferenceEquals(other, obj);
}
if (obj.GetType() != GetType())
return false;
return Equals((WeakReferenceCompareValue<TK>)obj);
}
public override int GetHashCode()
{
return _hashCode;
}
}
private sealed class LocalState
{
public int localVersion;
}
}
}
| |
using Codecov.Factories;
using Codecov.Services.ContinuousIntegrationServers;
using FluentAssertions;
using Moq;
using Xunit;
namespace Codecov.Tests.Factories
{
public class ContinuousIntegrationServerFactoryTests
{
#region AppVeyor Detection
[Fact]
public void Create_ShouldDetectAppVeyorWhenCiAndAppVeyorIsTrue()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("APPVEYOR")).Returns("True");
ev.Setup(s => s.GetEnvironmentVariable("CI")).Returns("True");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().BeOfType<AppVeyor>();
}
[Fact]
public void Create_ShouldNotDetectAppVeyorWhenAppveyorIsFalse()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("APPVEYOR")).Returns("False");
ev.Setup(s => s.GetEnvironmentVariable("CI")).Returns("True");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<AppVeyor>().And.BeOfType<ContinuousIntegrationServer>();
}
[Fact]
public void Create_ShouldNotDetectAppVeyorWhenAppveyorIsNull()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("CI")).Returns("True");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<AppVeyor>().And.BeOfType<ContinuousIntegrationServer>();
}
[Fact]
public void Create_ShouldNotDetectAppVeyorWhenCiIsFalse()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("APPVEYOR")).Returns("True");
ev.Setup(s => s.GetEnvironmentVariable("CI")).Returns("False");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<AppVeyor>().And.BeOfType<ContinuousIntegrationServer>();
}
[Fact]
public void Create_ShouldNotDetectAppVeyorWhenCiIsNull()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("APPVEYOR")).Returns("True");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<AppVeyor>().And.BeOfType<ContinuousIntegrationServer>();
}
#endregion AppVeyor Detection
#region Azure Pipelines Detection
[Fact]
public void Create_ShouldDetectAzurePipelinesWhenTfBuildIsTrue()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TF_BUILD")).Returns("True");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().BeOfType<AzurePipelines>();
}
[Fact]
public void Create_ShouldNotDetectAzurePipelinesWhenTfBuildIsFalse()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TF_BUILD")).Returns("False");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<AzurePipelines>().And.BeOfType<ContinuousIntegrationServer>();
}
[Fact]
public void Create_ShouldNotDetectAzurePipelinesWhenTfBuildIsNull()
{
var ev = new Mock<IEnviornmentVariables>();
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<AzurePipelines>().And.BeOfType<ContinuousIntegrationServer>();
}
#endregion Azure Pipelines Detection
#region GitHub Action Detection
[Fact]
public void Create_ShouldDetectGitHubActionWhenGitHubActionIsNotNull()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("GITHUB_ACTION")).Returns("Some-kind-of-value");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().BeOfType<GitHubAction>();
}
[Fact]
public void Create_ShouldDetectGitHubActionWhenGitHubActionsIsTrue()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("GITHUB_ACTIONS")).Returns("True");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().BeOfType<GitHubAction>();
}
[Fact]
public void Create_ShouldNotDetectGitHubActionWhenGitHubActionsAndGitHubActionIsNull()
{
var ev = new Mock<IEnviornmentVariables>();
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<GitHubAction>().And.BeOfType<ContinuousIntegrationServer>();
}
[Fact]
public void Create_ShouldNotDetectGitHubActionWhenGitHubActionsIsFalse()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("GITHUB_ACTIONS")).Returns("False");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<GitHubAction>().And.BeOfType<ContinuousIntegrationServer>();
}
#endregion GitHub Action Detection
#region Jenkins Detection
[Fact]
public void Create_ShouldDetectJenkinsWhenJenkinsUrlIsNotNull()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("JENKINS_URL")).Returns("https://example.org");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().BeOfType<Jenkins>();
}
[Fact]
public void Create_ShouldNotDetectJenkinsWhenJenkinsUrlIsNull()
{
var ev = new Mock<IEnviornmentVariables>();
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<Jenkins>().And.BeOfType<ContinuousIntegrationServer>();
}
#endregion Jenkins Detection
#region TeamCity Detection
[Fact]
public void Create_ShouldDetectTeamcityWhenTeamcityVersionIsNotNull()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TEAMCITY_VERSION")).Returns("1.0.0");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().BeOfType<TeamCity>();
}
[Fact]
public void Create_ShouldNotDetectTeamcityWhenTeamcityVersionIsNull()
{
var ev = new Mock<IEnviornmentVariables>();
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<TeamCity>().And.BeOfType<ContinuousIntegrationServer>();
}
#endregion TeamCity Detection
#region Travis Detection
[Fact]
public void Create_ShouldDetectTravisWhenCiAndTravisIsTrue()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS")).Returns("True");
ev.Setup(s => s.GetEnvironmentVariable("CI")).Returns("True");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().BeOfType<Travis>();
}
[Fact]
public void Create_ShouldNotDetectTravisWhenCiIsFalse()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS")).Returns("True");
ev.Setup(s => s.GetEnvironmentVariable("CI")).Returns("False");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<Travis>().And.BeOfType<ContinuousIntegrationServer>();
}
[Fact]
public void Create_ShouldNotDetectTravisWhenCiIsNull()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS")).Returns("True");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<Travis>().And.BeOfType<ContinuousIntegrationServer>();
}
[Fact]
public void Create_ShouldNotDetectTravisWhenTravisIsFalse()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS")).Returns("False");
ev.Setup(s => s.GetEnvironmentVariable("CI")).Returns("True");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<Travis>().And.BeOfType<ContinuousIntegrationServer>();
}
[Fact]
public void Create_ShouldNotDetectTravisWhenTravisIsNull()
{
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("CI")).Returns("True");
var ci = ContinuousIntegrationServerFactory.Create(ev.Object);
ci.Should().NotBeOfType<Travis>().And.BeOfType<ContinuousIntegrationServer>();
}
#endregion Travis Detection
}
}
| |
// Copyright (c) 2009-2015 Pwnt & Co. All Right Reserved.
//
// Filename: GeneratorOptions.cs
// Author: Stephen C. Austin (stephen.austin)
// Modified: 03/04/2015 11:08 PM
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using EnvDTE;
using ConfigurationManager = System.Configuration.ConfigurationManager;
namespace Supersonic
{
/// <summary>
/// This class holds all of the data and options for creating an instance of the Generator class.
/// </summary>
public class GeneratorOptions
{
// Connection Information
private GeneratorOptions(string @namespace)
{
this.IncludeViews = true;
this.ConfigurationClassSuffix = "Configuration";
this.CollectionType = "List";
this.CollectionTypeNamespace = "";
this.ElementsToGenerate = Elements.Poco | Elements.Context | Elements.UnitOfWork | Elements.PocoConfiguration;
this.SchemaName = "dbo";
this.Namespace = @namespace;
}
/// <summary>
/// Default constructor for building a new Generator from the given database name and connection string.
/// </summary>
/// <param name="namespace">The namespace for the generated code</param>
/// <param name="connectionString">The standard ADO.NET database connection string.</param>
public GeneratorOptions(string @namespace, string connectionString)
: this(@namespace)
{
var builder = new SqlConnectionStringBuilder(connectionString);
this.DatabaseName = builder.InitialCatalog;
this.ConnectionStringName = builder.InitialCatalog;
this.ConnectionString = connectionString;
}
/// <summary>
/// Constructor overload for building the connection from project configuration files and transforms.
/// </summary>
/// <param name="namespace">The namespace for the generated code</param>
/// <param name="connectionStringName">The name of the connection string.</param>
/// <param name="serviceProvider">An instance of the Visual Studio Host from the text template.</param>
public GeneratorOptions(string @namespace, string connectionStringName, IServiceProvider serviceProvider)
: this(@namespace)
{
this.ConnectionStringName = connectionStringName;
this.Host = serviceProvider;
var dte = (DTE)this.Host.GetService(typeof(DTE));
var currentConfigurationName = dte.Solution.SolutionBuild.ActiveConfiguration.Name;
var transformName = currentConfigurationName + ".config";
var root = Path.GetDirectoryName(dte.Solution.FullName);
this.FindConnectionString(root, transformName);
}
/// <summary>
/// Constructor overload for building the connection from project configuration files and transforms.
/// </summary>
/// <param name="namespace">The namespace for the generated code</param>
/// <param name="connectionStringName">The name of the connection string.</param>
/// <param name="root">The solution directory root</param>
/// <param name="transformName">The config transform name suffix.</param>
public GeneratorOptions(string @namespace, string connectionStringName, string root, string transformName)
: this(@namespace)
{
this.ConnectionStringName = connectionStringName;
this.FindConnectionString(root, transformName);
}
/// <summary>
/// The namespace for the generated code
/// </summary>
public string Namespace { get; set; }
/// <summary>
/// The name of the connection string.
/// </summary>
public string ConnectionStringName { get; private set; }
/// <summary>
/// The name of the database from the connection string.
/// </summary>
public string DatabaseName { get; private set; }
/// <summary>
/// The connection string used by the generator.
/// </summary>
public string ConnectionString { get; private set; }
/// <summary>
/// The Visual Studio instance containing the text templates being transformed.
/// </summary>
public IServiceProvider Host { get; private set; }
// Code Generation Options
/// <summary>
/// The code elements to generate.
/// </summary>
public Elements ElementsToGenerate { get; set; }
/// <summary>
/// The type of collection to use to contain the entities on the many side of a navigational property.
/// </summary>
public string CollectionType { get; set; }
/// <summary>
/// The namespace of the collection type.
/// </summary>
public string CollectionTypeNamespace { get; set; }
/// <summary>
/// True (default) to include views in the generation strategy.
/// </summary>
public bool IncludeViews { get; set; }
/// <summary>
/// The SQL schema name to target.
/// </summary>
public string SchemaName { get; set; }
/// <summary>
/// Gets the name of the context class.
/// </summary>
public string ContextClassName
{
get { return this.ConnectionStringName + "Context"; }
}
/// <summary>
/// Gets the name of the interface that defines the context (unit of work).
/// </summary>
public string ContextInterfaceName
{
get { return "I" + this.ContextClassName; }
}
/// <summary>
/// The name of the configuration class
/// </summary>
public string ConfigurationClassSuffix { get; set; }
/// <summary>
/// Gets/sets the namespace of the context class.
/// </summary>
public string ContextNamespace { get; set; }
/// <summary>
/// The POCO namespace
/// </summary>
public string PocoNamespace { get; set; }
/// <summary>
/// The unit of work namespace.
/// </summary>
public string UnitOfWorkNamespace { get; set; }
/// <summary>
/// The configuration namespace.
/// </summary>
public string ConfigurationNamespace { get; set; }
private void FindConnectionString(string root, string transformName)
{
if (root == null)
return;
var directories = Directory.EnumerateDirectories(root);
foreach (var files in directories.Select(directory => Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).OrderBy(x => x.Length).ToList()))
if (files.Any(x => x.EndsWith(transformName, StringComparison.InvariantCultureIgnoreCase)))
try
{
using (var transformed = ConfigTransform.ApplyTransformation(files.First(x => x.EndsWith(".config", StringComparison.InvariantCultureIgnoreCase) && !x.EndsWith("es.config", StringComparison.InvariantCultureIgnoreCase)),
files.First(x => x.EndsWith(transformName, StringComparison.InvariantCultureIgnoreCase))))
if (this.TrySetConnectionString(transformed.Filename))
return;
}
catch
{
}
else if (files.Where(x => x.EndsWith(".config", StringComparison.InvariantCultureIgnoreCase) && !x.EndsWith("es.config", StringComparison.InvariantCultureIgnoreCase)).Any(this.TrySetConnectionString))
return;
}
private bool TrySetConnectionString(string path)
{
var configFile = new ExeConfigurationFileMap { ExeConfigFilename = path };
var config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
var connSection = config.ConnectionStrings;
// Get the named connection string
try
{
this.ConnectionString = connSection.ConnectionStrings[this.ConnectionStringName].ConnectionString;
var builder = new SqlConnectionStringBuilder(this.ConnectionString);
this.DatabaseName = builder.InitialCatalog;
return true;
}
catch
{
this.ConnectionString = null;
}
return false;
}
}
}
| |
using System;
using System.Threading.Tasks;
using NUnit.Framework;
using Zu.AsyncChromeDriver.Tests.Environment;
using Zu.AsyncWebDriver;
using Zu.WebBrowser.BasicTypes;
namespace Zu.AsyncChromeDriver.Tests
{
[TestFixture]
public class TypingTest : DriverTestFixture
{
[Test]
public async Task ShouldFireKeyPressEvents()
{
await driver.GoToUrl(javascriptPage);
IWebElement keyReporter = await driver.FindElement(By.Id("keyReporter"));
await keyReporter.SendKeys("a");
IWebElement result = await driver.FindElement(By.Id("result"));
string text = await result.Text();
Assert.That(text, Does.Contain("press:"));
}
[Test]
public async Task ShouldFireKeyDownEvents()
{
await driver.GoToUrl(javascriptPage);
IWebElement keyReporter = await driver.FindElement(By.Id("keyReporter"));
await keyReporter.SendKeys("I");
IWebElement result = await driver.FindElement(By.Id("result"));
string text = await result.Text();
Assert.That(text, Does.Contain("down:"));
}
[Test]
public async Task ShouldFireKeyUpEvents()
{
await driver.GoToUrl(javascriptPage);
IWebElement keyReporter = await driver.FindElement(By.Id("keyReporter"));
await keyReporter.SendKeys("a");
IWebElement result = await driver.FindElement(By.Id("result"));
string text = await result.Text();
Assert.That(text, Does.Contain("up:"));
}
[Test]
public async Task ShouldTypeLowerCaseLetters()
{
await driver.GoToUrl(javascriptPage);
IWebElement keyReporter = await driver.FindElement(By.Id("keyReporter"));
await keyReporter.SendKeys("abc def");
Assert.AreEqual("abc def", await keyReporter.GetAttribute("value"));
}
[Test]
public async Task ShouldBeAbleToTypeCapitalLetters()
{
await driver.GoToUrl(javascriptPage);
IWebElement keyReporter = await driver.FindElement(By.Id("keyReporter"));
await keyReporter.SendKeys("ABC DEF");
Assert.AreEqual("ABC DEF", await keyReporter.GetAttribute("value"));
}
[Test]
public async Task ShouldBeAbleToTypeQuoteMarks()
{
await driver.GoToUrl(javascriptPage);
IWebElement keyReporter = await driver.FindElement(By.Id("keyReporter"));
await keyReporter.SendKeys("\"");
Assert.AreEqual("\"", await keyReporter.GetAttribute("value"));
}
[Test]
public async Task ShouldBeAbleToTypeTheAtCharacter()
{
// simon: I tend to use a US/UK or AUS keyboard layout with English
// as my primary language. There are consistent reports that we're
// not handling i18nised keyboards properly. This test exposes this
// in a lightweight manner when my keyboard is set to the DE mapping
// and we're using IE.
await driver.GoToUrl(javascriptPage);
IWebElement keyReporter = await driver.FindElement(By.Id("keyReporter"));
await keyReporter.SendKeys("@");
Assert.AreEqual("@", await keyReporter.GetAttribute("value"));
}
[Test]
public async Task ShouldBeAbleToMixUpperAndLowerCaseLetters()
{
await driver.GoToUrl(javascriptPage);
IWebElement keyReporter = await driver.FindElement(By.Id("keyReporter"));
await keyReporter.SendKeys("me@eXample.com");
Assert.AreEqual("me@eXample.com", await keyReporter.GetAttribute("value"));
}
[Test]
public async Task ArrowKeysShouldNotBePrintable()
{
await driver.GoToUrl(javascriptPage);
IWebElement keyReporter = await driver.FindElement(By.Id("keyReporter"));
await keyReporter.SendKeys(Keys.ArrowLeft);
Assert.AreEqual(string.Empty, await keyReporter.GetAttribute("value"));
}
[Test]
public async Task ShouldBeAbleToUseArrowKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement keyReporter = await driver.FindElement(By.Id("keyReporter"));
await keyReporter.SendKeys("Tet" + Keys.ArrowLeft + "s");
Assert.AreEqual("Test", await keyReporter.GetAttribute("value"));
}
[Test]
public async Task WillSimulateAKeyUpWhenEnteringTextIntoInputElements()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyUp"));
await element.SendKeys("I like cheese");
IWebElement result = await driver.FindElement(By.Id("result"));
Assert.AreEqual("I like cheese", await result.Text());
}
[Test]
public async Task WillSimulateAKeyDownWhenEnteringTextIntoInputElements()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyDown"));
await element.SendKeys("I like cheese");
IWebElement result = await driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual("I like chees", await result.Text());
}
[Test]
public async Task WillSimulateAKeyPressWhenEnteringTextIntoInputElements()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyPress"));
await element.SendKeys("I like cheese");
IWebElement result = await driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual("I like chees", await result.Text());
}
[Test]
public async Task WillSimulateAKeyUpWhenEnteringTextIntoTextAreas()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyUpArea"));
await element.SendKeys("I like cheese");
IWebElement result = await driver.FindElement(By.Id("result"));
Assert.AreEqual("I like cheese", await result.Text());
}
[Test]
public async Task WillSimulateAKeyDownWhenEnteringTextIntoTextAreas()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyDownArea"));
await element.SendKeys("I like cheese");
IWebElement result = await driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual("I like chees", await result.Text());
}
[Test]
public async Task WillSimulateAKeyPressWhenEnteringTextIntoTextAreas()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyPressArea"));
await element.SendKeys("I like cheese");
IWebElement result = await driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual("I like chees", await result.Text());
}
[Test]
public async Task ShouldFireFocusKeyEventsInTheRightOrder()
{
await driver.GoToUrl(javascriptPage);
IWebElement result = await driver.FindElement(By.Id("result"));
IWebElement element = await driver.FindElement(By.Id("theworks"));
await element.SendKeys("a");
Assert.AreEqual("focus keydown keypress keyup", await result.Text().Trim());
}
[Test]
public async Task ShouldReportKeyCodeOfArrowKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement result = await driver.FindElement(By.Id("result"));
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys(Keys.ArrowDown);
await CheckRecordedKeySequence(result, 40);
await element.SendKeys(Keys.ArrowUp);
await CheckRecordedKeySequence(result, 38);
await element.SendKeys(Keys.ArrowLeft);
await CheckRecordedKeySequence(result, 37);
await element.SendKeys(Keys.ArrowRight);
await CheckRecordedKeySequence(result, 39);
// And leave no rubbish/printable keys in the "keyReporter"
Assert.AreEqual(string.Empty, await element.GetAttribute("value"));
}
[Test]
public async Task ShouldReportKeyCodeOfArrowKeysUpDownEvents()
{
await driver.GoToUrl(javascriptPage);
IWebElement result = await driver.FindElement(By.Id("result"));
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys(Keys.ArrowDown);
string text = await result.Text().Trim();
Assert.That(text, Does.Contain("down: 40"));
Assert.That(text, Does.Contain("up: 40"));
await element.SendKeys(Keys.ArrowUp);
text = await result.Text().Trim();
Assert.That(text, Does.Contain("down: 38"));
Assert.That(text, Does.Contain("up: 38"));
await element.SendKeys(Keys.ArrowLeft);
text = await result.Text().Trim();
Assert.That(text, Does.Contain("down: 37"));
Assert.That(text, Does.Contain("up: 37"));
await element.SendKeys(Keys.ArrowRight);
text = await result.Text().Trim();
Assert.That(text, Does.Contain("down: 39"));
Assert.That(text, Does.Contain("up: 39"));
// And leave no rubbish/printable keys in the "keyReporter"
Assert.AreEqual(string.Empty, await element.GetAttribute("value"));
}
[Test]
public async Task NumericNonShiftKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
string numericLineCharsNonShifted = "`1234567890-=[]\\;,.'/42";
await element.SendKeys(numericLineCharsNonShifted);
Assert.AreEqual(numericLineCharsNonShifted, await element.GetAttribute("value"));
}
[Test]
public async Task NumericShiftKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement result = await driver.FindElement(By.Id("result"));
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
string numericShiftsEtc = "~!@#$%^&*()_+{}:\"<>?|END~";
await element.SendKeys(numericShiftsEtc);
Assert.AreEqual(numericShiftsEtc, await element.GetAttribute("value"));
string text = await result.Text().Trim();
Assert.That(text, Does.Contain(" up: 16"));
}
[Test]
public async Task LowerCaseAlphaKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
String lowerAlphas = "abcdefghijklmnopqrstuvwxyz";
await element.SendKeys(lowerAlphas);
Assert.AreEqual(lowerAlphas, await element.GetAttribute("value"));
}
[Test]
public async Task UppercaseAlphaKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement result = await driver.FindElement(By.Id("result"));
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
String upperAlphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
await element.SendKeys(upperAlphas);
Assert.AreEqual(upperAlphas, await element.GetAttribute("value"));
string text = await result.Text().Trim();
Assert.That(text, Does.Contain(" up: 16"));
}
[Test]
public async Task AllPrintableKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement result = await driver.FindElement(By.Id("result"));
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
String allPrintable =
"!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFGHIJKLMNO" +
"PQRSTUVWXYZ [\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
await element.SendKeys(allPrintable);
Assert.AreEqual(allPrintable, element.GetAttribute("value"));
string text = await result.Text().Trim();
Assert.That(text, Does.Contain(" up: 16"));
}
[Test]
public async Task ArrowKeysAndPageUpAndDown()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys("a" + Keys.Left + "b" + Keys.Right +
Keys.Up + Keys.Down + Keys.PageUp + Keys.PageDown + "1");
Assert.AreEqual("ba1", await element.GetAttribute("value"));
}
[Test]
public async Task HomeAndEndAndPageUpAndPageDownKeys()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) {
return;
}
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys("abc" + Keys.Home + "0" + Keys.Left + Keys.Right +
Keys.PageUp + Keys.PageDown + Keys.End + "1" + Keys.Home +
"0" + Keys.PageUp + Keys.End + "111" + Keys.Home + "00");
Assert.AreEqual("0000abc1111", await element.GetAttribute("value"));
}
[Test]
public async Task DeleteAndBackspaceKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys("abcdefghi");
Assert.AreEqual("abcdefghi", await element.GetAttribute("value"));
await element.SendKeys(Keys.Left + Keys.Left + Keys.Delete);
Assert.AreEqual("abcdefgi", await element.GetAttribute("value"));
await element.SendKeys(Keys.Left + Keys.Left + Keys.Backspace);
Assert.AreEqual("abcdfgi", await element.GetAttribute("value"));
}
[Test]
public async Task SpecialSpaceKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys("abcd" + Keys.Space + "fgh" + Keys.Space + "ij");
Assert.AreEqual("abcd fgh ij", await element.GetAttribute("value"));
}
[Test]
public async Task NumberpadKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys("abcd" + Keys.Multiply + Keys.Subtract + Keys.Add +
Keys.Decimal + Keys.Separator + Keys.NumberPad0 + Keys.NumberPad9 +
Keys.Add + Keys.Semicolon + Keys.Equal + Keys.Divide +
Keys.NumberPad3 + "abcd");
Assert.AreEqual("abcd*-+.,09+;=/3abcd", await element.GetAttribute("value"));
}
[Test]
public async Task FunctionKeys()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys("FUNCTION" + Keys.F8 + "-KEYS" + Keys.F8);
await element.SendKeys("" + Keys.F8 + "-TOO" + Keys.F8);
Assert.AreEqual("FUNCTION-KEYS-TOO", await element.GetAttribute("value"));
}
[Test]
public async Task ShiftSelectionDeletes()
{
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys("abcd efgh");
Assert.AreEqual(await element.GetAttribute("value"), "abcd efgh");
await //Could be chord problem
element.SendKeys(Keys.Shift + Keys.Left + Keys.Left + Keys.Left);
await element.SendKeys(Keys.Delete);
Assert.AreEqual("abcd e", await element.GetAttribute("value"));
}
[Test]
public async Task ChordControlHomeShiftEndDelete()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) {
return;
}
await driver.GoToUrl(javascriptPage);
IWebElement result = await driver.FindElement(By.Id("result"));
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys("!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG");
await element.SendKeys(Keys.Home);
await element.SendKeys("" + Keys.Shift + Keys.End + Keys.Delete);
Assert.AreEqual(string.Empty, await element.GetAttribute("value"));
string text = await result.Text().Trim();
Assert.That(text, Does.Contain(" up: 16"));
}
[Test]
public async Task ChordReveseShiftHomeSelectionDeletes()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) {
return;
}
await driver.GoToUrl(javascriptPage);
IWebElement result = await driver.FindElement(By.Id("result"));
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
await element.SendKeys("done" + Keys.Home);
Assert.AreEqual("done", await element.GetAttribute("value"));
await //Sending chords
element.SendKeys("" + Keys.Shift + "ALL " + Keys.Home);
Assert.AreEqual("ALL done", await element.GetAttribute("value"));
await element.SendKeys(Keys.Delete);
Assert.AreEqual("done", await element.GetAttribute("value"), "done");
await element.SendKeys("" + Keys.End + Keys.Shift + Keys.Home);
Assert.AreEqual("done", await element.GetAttribute("value"));
// Note: trailing SHIFT up here
string text = await result.Text().Trim();
Assert.That(text, Does.Contain(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text);
await element.SendKeys("" + Keys.Delete);
Assert.AreEqual(string.Empty, await element.GetAttribute("value"));
}
// control-x control-v here for cut & paste tests, these work on windows
// and linux, but not on the MAC.
[Test]
public async Task ChordControlCutAndPaste()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) {
return;
}
await driver.GoToUrl(javascriptPage);
IWebElement element = await driver.FindElement(By.Id("keyReporter"));
IWebElement result = await driver.FindElement(By.Id("result"));
String paste = "!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG";
await element.SendKeys(paste);
Assert.AreEqual(paste, await element.GetAttribute("value"));
await //Chords
element.SendKeys("" + Keys.Home + Keys.Shift + Keys.End);
string text = await result.Text().Trim();
Assert.That(text, Does.Contain(" up: 16"));
await element.SendKeys(Keys.Control + "x");
Assert.AreEqual(string.Empty, await element.GetAttribute("value"));
await element.SendKeys(Keys.Control + "v");
Assert.AreEqual(paste, await element.GetAttribute("value"));
await element.SendKeys("" + Keys.Left + Keys.Left + Keys.Left +
Keys.Shift + Keys.End);
await element.SendKeys(Keys.Control + "x" + "v");
Assert.AreEqual(paste, await element.GetAttribute("value"));
await element.SendKeys(Keys.Home);
await element.SendKeys(Keys.Control + "v");
await element.SendKeys(Keys.Control + "v" + "v");
await element.SendKeys(Keys.Control + "v" + "v" + "v");
Assert.AreEqual("EFGEFGEFGEFGEFGEFG" + paste, await element.GetAttribute("value"));
await element.SendKeys("" + Keys.End + Keys.Shift + Keys.Home +
Keys.Null + Keys.Delete);
Assert.AreEqual(await element.GetAttribute("value"), string.Empty);
}
[Test]
public async Task ShouldTypeIntoInputElementsThatHaveNoTypeAttribute()
{
await driver.GoToUrl(formsPage);
IWebElement element = await driver.FindElement(By.Id("no-type"));
await element.SendKeys("Should Say Cheese");
Assert.AreEqual("Should Say Cheese", await element.GetAttribute("value"));
}
[Test]
public async Task ShouldNotTypeIntoElementsThatPreventKeyDownEvents()
{
await driver.GoToUrl(javascriptPage);
IWebElement silent = await driver.FindElement(By.Name("suppress"));
await silent.SendKeys("s");
Assert.AreEqual(string.Empty, await silent.GetAttribute("value"));
}
[Test]
public async Task GenerateKeyPressEventEvenWhenElementPreventsDefault()
{
await driver.GoToUrl(javascriptPage);
IWebElement silent = await driver.FindElement(By.Name("suppress"));
IWebElement result = await driver.FindElement(By.Id("result"));
await silent.SendKeys("s");
string text = await result.Text();
}
[Test]
public async Task ShouldBeAbleToTypeOnAnEmailInputField()
{
await driver.GoToUrl(formsPage);
IWebElement email = await driver.FindElement(By.Id("email"));
await email.SendKeys("foobar");
Assert.AreEqual("foobar", await email.GetAttribute("value"));
}
[Test]
public async Task ShouldBeAbleToTypeOnANumberInputField()
{
await driver.GoToUrl(formsPage);
IWebElement numberElement = await driver.FindElement(By.Id("age"));
await numberElement.SendKeys("33");
Assert.AreEqual("33", await numberElement.GetAttribute("value"));
}
[Test]
public async Task ShouldThrowIllegalArgumentException()
{
await driver.GoToUrl(formsPage);
IWebElement email = await driver.FindElement(By.Id("age"));
//Assert.That(async () => await email.SendKeys(null), Throws.InstanceOf<ArgumentNullException>());
await AssertEx.ThrowsAsync<ArgumentNullException>(async () => await email.SendKeys(null));
}
[Test]
public async Task CanSafelyTypeOnElementThatIsRemovedFromTheDomOnKeyPress()
{
await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs("key_tests/remove_on_keypress.html"));
IWebElement input = await driver.FindElement(By.Id("target"));
IWebElement log = await driver.FindElement(By.Id("log"));
Assert.AreEqual("", await log.GetAttribute("value"));
await input.SendKeys("b");
string expected = "keydown (target)\nkeyup (target)\nkeyup (body)";
Assert.AreEqual(expected, await GetValueText(log));
await input.SendKeys("a");
// Some drivers (IE, Firefox) do not always generate the final keyup event since the element
// is removed from the DOM in response to the keypress (note, this is a product of how events
// are generated and does not match actual user behavior).
expected += "\nkeydown (target)\na pressed; removing";
Assert.That(await GetValueText(log), Is.EqualTo(expected).Or.EqualTo(expected + "\nkeyup (body)"));
}
[Test]
public async Task CanClearNumberInputAfterTypingInvalidInput()
{
await driver.GoToUrl(formsPage);
IWebElement input = await driver.FindElement(By.Id("age"));
await input.SendKeys("e");
await input.Clear();
await input.SendKeys("3");
Assert.AreEqual("3", await input.GetAttribute("value"));
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public async Task TypingIntoAnIFrameWithContentEditableOrDesignModeSet()
{
await driver.GoToUrl(richTextPage);
await driver.SwitchTo().Frame("editFrame");
IWebElement element = await driver.SwitchTo().ActiveElement();
await element.SendKeys("Fishy");
await driver.SwitchTo().DefaultContent();
IWebElement trusted = await driver.FindElement(By.Id("istrusted"));
IWebElement id = await driver.FindElement(By.Id("tagId"));
Assert.That(await trusted.Text(), Is.EqualTo("[true]").Or.EqualTo("[n/a]").Or.EqualTo("[]"));
Assert.That(await id.Text(), Is.EqualTo("[frameHtml]").Or.EqualTo("[theBody]"));
}
[Test]
public async Task ShouldBeAbleToTypeIntoEmptyContentEditableElement()
{
await driver.GoToUrl(readOnlyPage);
IWebElement editable = await driver.FindElement(By.Id("content-editable"));
await editable.Clear();
await editable.SendKeys("cheese"); // requires focus on OS X
Assert.AreEqual("cheese", await editable.Text());
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
public async Task ShouldBeAbleToTypeIntoTinyMCE()
{
await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs("tinymce.html"));
await driver.SwitchTo().Frame("mce_0_ifr");
IWebElement editable = await driver.FindElement(By.Id("tinymce"));
await editable.Clear();
await editable.SendKeys("cheese"); // requires focus on OS X
Assert.AreEqual("cheese", await editable.Text());
}
private async Task<string> GetValueText(IWebElement el)
{
// Standardize on \n and strip any trailing whitespace.
return await el.GetAttribute("value").Replace("\r\n", "\n").Trim();
}
private async Task CheckRecordedKeySequence(IWebElement element, int expectedKeyCode)
{
string withKeyPress = string.Format("down: {0} press: {0} up: {0}", expectedKeyCode);
string withoutKeyPress = string.Format("down: {0} up: {0}", expectedKeyCode);
Assert.That((await element.Text()).Trim(), Is.AnyOf(withKeyPress, withoutKeyPress));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Elasticsearch.Net;
using FluentAssertions;
using Tests.Framework.MockResponses;
namespace Tests.Framework
{
public class VirtualClusterConnection : InMemoryConnection
{
private static readonly object _lock = new object();
private class State { public int Pinged = 0; public int Sniffed = 0; public int Called = 0; public int Successes = 0; public int Failures = 0; }
private IDictionary<int, State> Calls = new Dictionary<int, State> { };
private VirtualCluster _cluster;
private TestableDateTimeProvider _dateTimeProvider;
public VirtualClusterConnection(VirtualCluster cluster, TestableDateTimeProvider dateTimeProvider)
{
this.UpdateCluster(cluster);
this._dateTimeProvider = dateTimeProvider;
}
public void UpdateCluster(VirtualCluster cluster)
{
if (cluster == null) return;
lock (_lock)
{
this._cluster = cluster;
this.Calls = cluster.Nodes.ToDictionary(n => n.Uri.Port, v => new State());
}
}
public bool IsSniffRequest(RequestData requestData) => requestData.Path.StartsWith("_nodes/_all/settings", StringComparison.Ordinal);
public bool IsPingRequest(RequestData requestData) => requestData.Path == "/" && requestData.Method == HttpMethod.HEAD;
public override ElasticsearchResponse<TReturn> Request<TReturn>(RequestData requestData)
{
this.Calls.Should().ContainKey(requestData.Uri.Port);
try
{
var state = this.Calls[requestData.Uri.Port];
if (IsSniffRequest(requestData))
{
var sniffed = Interlocked.Increment(ref state.Sniffed);
return HandleRules<TReturn, ISniffRule>(
requestData,
this._cluster.SniffingRules,
requestData.RequestTimeout,
(r) => this.UpdateCluster(r.NewClusterState),
(r) => SniffResponse.Create(this._cluster.Nodes, this._cluster.SniffShouldReturnFqnd)
);
}
if (IsPingRequest(requestData))
{
var pinged = Interlocked.Increment(ref state.Pinged);
return HandleRules<TReturn, IRule>(
requestData,
this._cluster.PingingRules,
requestData.PingTimeout,
(r) => { },
(r) => null //HEAD request
);
}
var called = Interlocked.Increment(ref state.Called);
return HandleRules<TReturn, IClientCallRule>(
requestData,
this._cluster.ClientCallRules,
requestData.RequestTimeout,
(r) => { },
CallResponse
);
}
#if DOTNETCORE
catch (System.Net.Http.HttpRequestException e)
#else
catch (WebException e)
#endif
{
var builder = new ResponseBuilder<TReturn>(requestData);
builder.Exception = e;
return builder.ToResponse();
}
}
private ElasticsearchResponse<TReturn> HandleRules<TReturn, TRule>(
RequestData requestData,
IEnumerable<TRule> rules,
TimeSpan timeout,
Action<TRule> beforeReturn,
Func<TRule, byte[]> successResponse
) where TReturn : class where TRule : IRule
{
//TODO Make this pluggable?
requestData.MadeItToResponse = true;
var state = this.Calls[requestData.Uri.Port];
foreach (var rule in rules.Where(s => s.OnPort.HasValue))
{
var always = rule.Times.Match(t => true, t => false);
var times = rule.Times.Match(t => -1, t => t);
if (rule.OnPort.Value == requestData.Uri.Port)
{
if (always)
return Always<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, rule);
return Sometimes<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, state, rule, times);
}
}
foreach (var rule in rules.Where(s => !s.OnPort.HasValue))
{
var always = rule.Times.Match(t => true, t => false);
var times = rule.Times.Match(t => -1, t => t);
if (always)
return Always<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, rule);
return Sometimes<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, state, rule, times);
}
return this.ReturnConnectionStatus<TReturn>(requestData, successResponse(default(TRule)));
}
private ElasticsearchResponse<TReturn> Always<TReturn, TRule>(RequestData requestData, TimeSpan timeout, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse, TRule rule)
where TReturn : class
where TRule : IRule
{
if (rule.Takes.HasValue)
{
var time = timeout < rule.Takes.Value ? timeout: rule.Takes.Value;
this._dateTimeProvider.ChangeTime(d=> d.Add(time));
if (rule.Takes.Value > requestData.RequestTimeout)
#if DOTNETCORE
throw new System.Net.Http.HttpRequestException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}");
#else
throw new WebException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}");
#endif
}
return rule.Succeeds
? Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule)
: Fail<TReturn, TRule>(requestData, rule);
}
private ElasticsearchResponse<TReturn> Sometimes<TReturn, TRule>(RequestData requestData, TimeSpan timeout, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse, State state, TRule rule, int times)
where TReturn : class
where TRule : IRule
{
if (rule.Takes.HasValue)
{
var time = timeout < rule.Takes.Value ? timeout : rule.Takes.Value;
this._dateTimeProvider.ChangeTime(d=> d.Add(time));
if (rule.Takes.Value > requestData.RequestTimeout)
#if DOTNETCORE
throw new System.Net.Http.HttpRequestException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}");
#else
throw new WebException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}");
#endif
}
if (rule.Succeeds && times >= state.Successes)
return Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule);
else if (rule.Succeeds) return Fail<TReturn, TRule>(requestData, rule);
if (!rule.Succeeds && times >= state.Failures)
return Fail<TReturn, TRule>(requestData, rule);
return Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule);
}
private ElasticsearchResponse<TReturn> Fail<TReturn, TRule>(RequestData requestData, TRule rule)
where TReturn : class
where TRule : IRule
{
var state = this.Calls[requestData.Uri.Port];
var failed = Interlocked.Increment(ref state.Failures);
if (rule.Return == null)
#if DOTNETCORE
throw new System.Net.Http.HttpRequestException();
#else
throw new WebException();
#endif
return rule.Return.Match(
(e) =>
{
throw e;
},
(statusCode) => this.ReturnConnectionStatus<TReturn>(requestData, CallResponse(rule), statusCode)
);
}
private ElasticsearchResponse<TReturn> Success<TReturn, TRule>(RequestData requestData, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse, TRule rule)
where TReturn : class
where TRule : IRule
{
var state = this.Calls[requestData.Uri.Port];
var succeeded = Interlocked.Increment(ref state.Successes);
beforeReturn?.Invoke(rule);
return this.ReturnConnectionStatus<TReturn>(requestData, successResponse(rule));
}
private byte[] CallResponse<TRule>(TRule rule)
where TRule : IRule
{
if (rule?.ReturnResponse != null)
return rule.ReturnResponse;
var response = DefaultResponse;
using (var ms = new MemoryStream())
{
new ElasticsearchDefaultSerializer().Serialize(response, ms);
return ms.ToArray();
}
}
private static object DefaultResponse
{
get
{
var response = new
{
name = "Razor Fist",
cluster_name = "elasticsearch-test-cluster",
version = new
{
number = "2.0.0",
build_hash = "af1dc6d8099487755c3143c931665b709de3c764",
build_timestamp = "2015-07-07T11:28:47Z",
build_snapshot = true,
lucene_version = "5.2.1"
},
tagline = "You Know, for Search"
};
return response;
}
}
public override Task<ElasticsearchResponse<TReturn>> RequestAsync<TReturn>(RequestData requestData, CancellationToken cancellationToken)
{
return Task.FromResult(this.Request<TReturn>(requestData));
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.PowerShell
{
/// <summary>
/// A Helper class for printing notification on PowerShell startup when there is a new update.
/// </summary>
/// <remarks>
/// For the detailed design, please take a look at the corresponding RFC.
/// </remarks>
internal static class UpdatesNotification
{
private const string UpdateCheckEnvVar = "POWERSHELL_UPDATECHECK";
private const string LTSBuildInfoURL = "https://aka.ms/pwsh-buildinfo-lts";
private const string StableBuildInfoURL = "https://aka.ms/pwsh-buildinfo-stable";
private const string PreviewBuildInfoURL = "https://aka.ms/pwsh-buildinfo-preview";
/// <summary>
/// The version of new update is persisted using a file, not as the file content, but instead baked in the file name in the following template:
/// `update{notification-type}_{version}_{publish-date}` -- held by 's_updateFileNameTemplate',
/// while 's_updateFileNamePattern' holds the pattern of this file name.
/// </summary>
private static readonly string s_updateFileNameTemplate, s_updateFileNamePattern;
/// <summary>
/// For each notification type, we need two files to achieve the synchronization for the update check:
/// `_sentinel{notification-type}_` -- held by 's_sentinelFileName';
/// `sentinel{notification-type}-{year}-{month}-{day}.done`
/// -- held by 's_doneFileNameTemplate', while 's_doneFileNamePattern' holds the pattern of this file name.
/// The {notification-type} part will be the integer value of the corresponding `NotificationType` member.
/// The {year}-{month}-{day} part will be filled with the date of current day when the update check runs.
/// </summary>
private static readonly string s_sentinelFileName, s_doneFileNameTemplate, s_doneFileNamePattern;
private static readonly string s_cacheDirectory;
private static readonly EnumerationOptions s_enumOptions;
private static readonly NotificationType s_notificationType;
/// <summary>
/// Gets a value indicating whether update notification should be done.
/// </summary>
internal static readonly bool CanNotifyUpdates;
static UpdatesNotification()
{
s_notificationType = GetNotificationType();
CanNotifyUpdates = s_notificationType != NotificationType.Off;
if (CanNotifyUpdates)
{
s_enumOptions = new EnumerationOptions();
s_cacheDirectory = Path.Combine(Platform.CacheDirectory, PSVersionInfo.GitCommitId);
// Build the template/pattern strings for the configured notification type.
string typeNum = ((int)s_notificationType).ToString();
s_sentinelFileName = $"_sentinel{typeNum}_";
s_doneFileNameTemplate = $"sentinel{typeNum}-{{0}}-{{1}}-{{2}}.done";
s_doneFileNamePattern = $"sentinel{typeNum}-*.done";
s_updateFileNameTemplate = $"update{typeNum}_{{0}}_{{1}}";
s_updateFileNamePattern = $"update{typeNum}_v*.*.*_????-??-??";
}
}
// Maybe we shouldn't do update check and show notification when it's from a mini-shell, meaning when
// 'ConsoleShell.Start' is not called by 'ManagedEntrance.Start'.
// But it seems so unusual that it's probably not worth bothering. Also, a mini-shell probably should
// just disable the update notification feature by setting the opt-out environment variable.
internal static void ShowUpdateNotification(PSHostUserInterface hostUI)
{
if (!Directory.Exists(s_cacheDirectory))
{
return;
}
if (TryParseUpdateFile(
updateFilePath: out _,
out SemanticVersion lastUpdateVersion,
lastUpdateDate: out _)
&& lastUpdateVersion != null)
{
string releaseTag = lastUpdateVersion.ToString();
string notificationMsgTemplate = s_notificationType == NotificationType.LTS
? ManagedEntranceStrings.LTSUpdateNotificationMessage
: string.IsNullOrEmpty(lastUpdateVersion.PreReleaseLabel)
? ManagedEntranceStrings.StableUpdateNotificationMessage
: ManagedEntranceStrings.PreviewUpdateNotificationMessage;
string notificationColor = string.Empty;
string resetColor = string.Empty;
string line2Padding = string.Empty;
string line3Padding = string.Empty;
// We calculate how much whitespace we need to make it look nice
if (hostUI.SupportsVirtualTerminal)
{
// Swaps foreground and background colors.
notificationColor = "\x1B[7m";
resetColor = "\x1B[0m";
// The first line is longest, if the message changes, this needs to be updated
int line1Length = notificationMsgTemplate.IndexOf('\n');
int line2Length = notificationMsgTemplate.IndexOf('\n', line1Length + 1);
int line3Length = notificationMsgTemplate.IndexOf('\n', line2Length + 1);
line3Length -= line2Length + 1;
line2Length -= line1Length + 1;
line2Padding = line2Padding.PadRight(line1Length - line2Length + releaseTag.Length);
// 3 represents the extra placeholder in the template
line3Padding = line3Padding.PadRight(line1Length - line3Length + 3);
}
string notificationMsg = string.Format(CultureInfo.CurrentCulture, notificationMsgTemplate, releaseTag, notificationColor, resetColor, line2Padding, line3Padding);
hostUI.WriteLine();
hostUI.WriteLine(notificationMsg);
}
}
internal static async Task CheckForUpdates()
{
// Delay the update check for 3 seconds so that it has the minimal impact on startup.
await Task.Delay(3000);
// A self-built pwsh for development purpose has the SHA1 commit hash baked in 'GitCommitId',
// which is 40 characters long. So we can quickly check the length of 'GitCommitId' to tell
// if this is a self-built pwsh, and skip the update check if so.
if (PSVersionInfo.GitCommitId.Length > 40)
{
return;
}
// Daily builds do not support update notifications
string preReleaseLabel = PSVersionInfo.PSCurrentVersion.PreReleaseLabel;
if (preReleaseLabel != null && preReleaseLabel.StartsWith("daily", StringComparison.OrdinalIgnoreCase))
{
return;
}
// If the host is not connect to a network, skip the rest of the check.
if (!NetworkInterface.GetIsNetworkAvailable())
{
return;
}
// Create the update cache directory if it doesn't exists
if (!Directory.Exists(s_cacheDirectory))
{
Directory.CreateDirectory(s_cacheDirectory);
}
bool parseSuccess = TryParseUpdateFile(
out string updateFilePath,
out SemanticVersion lastUpdateVersion,
out DateTime lastUpdateDate);
DateTime today = DateTime.UtcNow;
if (parseSuccess && updateFilePath != null && (today - lastUpdateDate).TotalDays < 7)
{
// There is an existing update file, and the last update was less than 1 week ago.
// It's unlikely a new version is released within 1 week, so we can skip this check.
return;
}
// Construct the sentinel file paths for today's check.
string todayDoneFileName = string.Format(
CultureInfo.InvariantCulture,
s_doneFileNameTemplate,
today.Year.ToString(),
today.Month.ToString(),
today.Day.ToString());
string todayDoneFilePath = Path.Combine(s_cacheDirectory, todayDoneFileName);
if (File.Exists(todayDoneFilePath))
{
// A successful update check has been done today.
// We can skip this update check.
return;
}
try
{
// Use 's_sentinelFileName' as the file lock.
// The update-check tasks started by every 'pwsh' process of the same version will compete on holding this file.
string sentinelFilePath = Path.Combine(s_cacheDirectory, s_sentinelFileName);
using (new FileStream(sentinelFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, bufferSize: 1, FileOptions.DeleteOnClose))
{
if (File.Exists(todayDoneFilePath))
{
// After acquiring the file lock, it turns out a successful check has already been done for today.
// Then let's skip this update check.
return;
}
// Now it's guaranteed that this is the only process that reaches here.
// Clean up the old '.done' file, there should be only one of it.
foreach (string oldFile in Directory.EnumerateFiles(s_cacheDirectory, s_doneFileNamePattern, s_enumOptions))
{
File.Delete(oldFile);
}
if (!parseSuccess)
{
// The update file is corrupted, either because more than one update files were found unexpectedly,
// or because the update file name failed to be parsed into a release version and a publish date.
// This is **very unlikely** to happen unless the file is accidentally altered manually.
// We try to recover here by cleaning up all update files for the configured notification type.
foreach (string file in Directory.EnumerateFiles(s_cacheDirectory, s_updateFileNamePattern, s_enumOptions))
{
File.Delete(file);
}
}
// Do the real update check:
// - Send HTTP request to query for the new release/pre-release;
// - If there is a valid new release that should be reported to the user,
// create the file `update<NotificationType>_<tag>_<publish-date>` when no `update` file exists,
// or rename the existing file to `update<NotificationType>_<new-version>_<new-publish-date>`.
SemanticVersion baselineVersion = lastUpdateVersion ?? PSVersionInfo.PSCurrentVersion;
Release release = await QueryNewReleaseAsync(baselineVersion);
if (release != null)
{
// The date part of the string is 'YYYY-MM-DD'.
const int dateLength = 10;
string newUpdateFileName = string.Format(
CultureInfo.InvariantCulture,
s_updateFileNameTemplate,
release.TagName,
release.PublishAt.Substring(0, dateLength));
string newUpdateFilePath = Path.Combine(s_cacheDirectory, newUpdateFileName);
if (updateFilePath == null)
{
new FileStream(newUpdateFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None).Close();
}
else
{
File.Move(updateFilePath, newUpdateFilePath);
}
}
// Finally, create the `todayDoneFilePath` file as an indicator that a successful update check has finished today.
new FileStream(todayDoneFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None).Close();
}
}
catch (Exception)
{
// There are 2 possible reason for the exception:
// 1. An update check initiated from another `pwsh` process is in progress.
// It's OK to just return and let that update check to finish the work.
// 2. The update check failed (ex. internet connectivity issue, GitHub service failure).
// It's OK to just return and let another `pwsh` do the check at later time.
}
}
/// <summary>
/// Check for the existence of the update file and parse the file name if it exists.
/// </summary>
/// <param name="updateFilePath">Get the exact update file path.</param>
/// <param name="lastUpdateVersion">Get the version of the new release.</param>
/// <param name="lastUpdateDate">Get the publish date of the new release.</param>
/// <returns>
/// False, when
/// 1. found more than one update files that matched the pattern; OR
/// 2. found only one update file, but failed to parse its name for version and publish date.
/// True, when
/// 1. no update file was found, namely no new updates yet;
/// 2. found only one update file, and succeeded to parse its name for version and publish date.
/// </returns>
private static bool TryParseUpdateFile(
out string updateFilePath,
out SemanticVersion lastUpdateVersion,
out DateTime lastUpdateDate)
{
updateFilePath = null;
lastUpdateVersion = null;
lastUpdateDate = default;
var files = Directory.EnumerateFiles(s_cacheDirectory, s_updateFileNamePattern, s_enumOptions);
var enumerator = files.GetEnumerator();
if (!enumerator.MoveNext())
{
// It's OK that an update file doesn't exist. This could happen when there is no new updates yet.
return true;
}
updateFilePath = enumerator.Current;
if (enumerator.MoveNext())
{
// More than 1 files were found that match the pattern. This is a corrupted state.
// Theoretically, there should be only one update file at any point of time.
updateFilePath = null;
return false;
}
// OK, only found one update file for the configured notification type, which is expected.
// Now let's parse the file name.
string updateFileName = Path.GetFileName(updateFilePath);
int dateStartIndex = updateFileName.LastIndexOf('_') + 1;
if (!DateTime.TryParse(
updateFileName.AsSpan(dateStartIndex),
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out lastUpdateDate))
{
updateFilePath = null;
return false;
}
int versionStartIndex = updateFileName.IndexOf('_') + 2;
int versionLength = dateStartIndex - versionStartIndex - 1;
string versionString = updateFileName.Substring(versionStartIndex, versionLength);
if (SemanticVersion.TryParse(versionString, out lastUpdateVersion))
{
return true;
}
updateFilePath = null;
lastUpdateDate = default;
return false;
}
private static async Task<Release> QueryNewReleaseAsync(SemanticVersion baselineVersion)
{
bool isStableRelease = string.IsNullOrEmpty(PSVersionInfo.PSCurrentVersion.PreReleaseLabel);
string[] queryUris = s_notificationType switch
{
NotificationType.LTS => new[] { LTSBuildInfoURL },
NotificationType.Default => isStableRelease
? new[] { StableBuildInfoURL }
: new[] { StableBuildInfoURL, PreviewBuildInfoURL },
_ => Array.Empty<string>()
};
using var client = new HttpClient();
string userAgent = string.Format(CultureInfo.InvariantCulture, "PowerShell {0}", PSVersionInfo.GitCommitId);
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Release releaseToReturn = null;
SemanticVersion highestVersion = baselineVersion;
var settings = new JsonSerializerSettings() { DateParseHandling = DateParseHandling.None };
var serializer = JsonSerializer.Create(settings);
foreach (string queryUri in queryUris)
{
// Query the GitHub Rest API and throw if the query fails.
HttpResponseMessage response = await client.GetAsync(queryUri);
response.EnsureSuccessStatusCode();
using var stream = await response.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
using var jsonReader = new JsonTextReader(reader);
JObject release = serializer.Deserialize<JObject>(jsonReader);
var tagName = release["ReleaseTag"].ToString();
var version = SemanticVersion.Parse(tagName.Substring(1));
if (version > highestVersion)
{
highestVersion = version;
var publishAt = release["ReleaseDate"].ToString();
releaseToReturn = new Release(publishAt, tagName);
}
}
return releaseToReturn;
}
/// <summary>
/// Get the notification type setting.
/// </summary>
private static NotificationType GetNotificationType()
{
string str = Environment.GetEnvironmentVariable(UpdateCheckEnvVar);
if (string.IsNullOrEmpty(str))
{
return NotificationType.Default;
}
if (Enum.TryParse(str, ignoreCase: true, out NotificationType type))
{
return type;
}
return NotificationType.Default;
}
/// <summary>
/// Notification type that can be configured.
/// </summary>
private enum NotificationType
{
/// <summary>
/// Turn off the update notification.
/// </summary>
Off = 0,
/// <summary>
/// Give you the default behaviors:
/// - the preview version 'pwsh' checks for the new preview version and the new GA version.
/// - the GA version 'pwsh' checks for the new GA version only.
/// </summary>
Default = 1,
/// <summary>
/// Both preview and GA version 'pwsh' checks for the new LTS version only.
/// </summary>
LTS = 2
}
private sealed class Release
{
internal Release(string publishAt, string tagName)
{
PublishAt = publishAt;
TagName = tagName;
}
/// <summary>
/// The datetime stamp is in UTC. For example: 2019-03-28T18:42:02Z.
/// </summary>
internal string PublishAt { get; }
/// <summary>
/// The release tag name.
/// </summary>
internal string TagName { get; }
}
}
}
| |
using System;
using System.Reflection;
using Fairweather.Service;
namespace Versioning
{
public class TransactionPost : Sage_Object
{
const int version_0 = 11;
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
/* Version Specific */
static readonly Func<object, object>[] head_dict = new Func<object, object>[7];
static readonly Type[] types = { typeof(SageDataObject110.IHeaderData),
typeof(SageDataObject120.IHeaderData),
typeof(SageDataObject130.IHeaderData),
typeof(SageDataObject140.IHeaderData),
typeof(SageDataObject150.IHeaderData),
typeof(SageDataObject160.IHeaderData),
typeof(SageDataObject170.IHeaderData),};
SageDataObject110.ITransactionPost tp11;
SageDataObject120.ITransactionPost tp12;
SageDataObject130.ITransactionPost tp13;
SageDataObject140.ITransactionPost tp14;
SageDataObject150.ITransactionPost tp15;
SageDataObject160.ITransactionPost tp16;
SageDataObject170.ITransactionPost tp17;
readonly Type items_type;
readonly Func<object> header_producer;
readonly Func<object> field_producer;
//object items_obj;Type items_type;
//
public TransactionPost(object a, int version)
: base(version) {
switch (m_version) {
case 11:
tp11 = (SageDataObject110.ITransactionPost)a;
header_producer = () => tp11.Header;
items_type = tp11.Items.GetType();
break;
case 12:
tp12 = (SageDataObject120.ITransactionPost)a;
header_producer = () => tp12.Header;
items_type = tp12.Items.GetType();
break;
case 13:
tp13 = (SageDataObject130.ITransactionPost)a;
header_producer = () => tp13.Header;
items_type = tp13.Items.GetType();
break;
case 14:
tp14 = (SageDataObject140.ITransactionPost)a;
header_producer = () => tp14.Header;
items_type = tp14.Items.GetType();
break;
case 15:
tp15 = (SageDataObject150.ITransactionPost)a;
header_producer = () => tp15.Header;
items_type = tp15.Items.GetType();
break;
case 16:
tp16 = (SageDataObject160.ITransactionPost)a;
header_producer = () => tp16.Header;
items_type = tp16.Items.GetType();
break;
case 17:
tp17 = (SageDataObject170.ITransactionPost)a;
header_producer = () => tp17.Header;
items_type = tp17.Items.GetType();
break;
}
int version_index = version - version_0;
if (head_dict[version_index] == null) {
Type header_type = types[version_index];
var pi = header_type.GetProperty("Fields", flags);
var mi = pi.GetGetMethod();
var magic1 = _Delegates.Create_Generic_Delegate1_Info;
var magic2 = magic1.MakeGenericMethod(header_type, typeof(object));
var @delegate = (Func<object, object>)magic2.Invoke(null, new object[] { mi });
head_dict[version_index] = @delegate;
}
field_producer = () =>
{
var @delegate = head_dict[version_index];
return @delegate(header_producer());
};
#region MyRegion
//MethodInfo generic_1;
//MethodInfo generic_2;
//MethodInfo instance_method;
//generic_1 = this.GetType().GetMethod("CreateGenericDelegate1", All);
//generic_2 = this.GetType().GetMethod("CreateGenericDelegate2", All);
//PropertyInfo p;
//MethodInfo m;
//p = header_data_t.GetProperty("fields", All);
//m = p.GetGetMethod();
//instance_method = generic_1.MakeGenericMethod(header_data_t, typeof(object));
//TransactionPost.Fact_Header = (Func<object, Func<object>>)
//instance_method.Invoke(null, new Object[] { m });
//items_type = items_obj.GetType();
//int version_index = version - version_0;
//if (split_dict[version_index] == null) {
// var item_type = items_obj.GetType();
// var mi = item_type.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
// var mis = item_type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreReturn | BindingFlags.NonPublic);
// var @delegate = (Func<object, object>)Delegate.CreateDelegate(typeof(Func<object, object>), mi);
// split_dict[version_index] = (items) =>
// {
// return @delegate(items);
// };
//}
#endregion
}
public bool Update() {
switch (m_version) {
case 11:
return tp11.Update();
case 12:
return tp12.Update();
case 13:
return tp13.Update();
case 14:
return tp14.Update();
case 15:
return tp15.Update();
case 16:
return tp16.Update();
case 17:
return tp17.Update();
}
return false;
}
public Fields HDGet() {
return new Fields(field_producer(), m_version);
}
public SplitData SDAdd() {
switch (m_version) {
case 11: {
Object temp = items_type.InvokeMember("Add",
BindingFlags.InvokeMethod,
null,
tp11.Items,
new Object[0]);
return new SplitData(temp, m_version);
}
case 12: {
Object temp = items_type.InvokeMember("Add",
BindingFlags.InvokeMethod,
null,
tp12.Items,
new Object[0]);
return new SplitData(temp, m_version);
}
case 13: {
Object temp = items_type.InvokeMember("Add",
BindingFlags.InvokeMethod,
null,
tp13.Items,
new Object[0]);
return new SplitData(temp, m_version);
}
case 14: {
Object temp = items_type.InvokeMember("Add",
BindingFlags.InvokeMethod,
null,
tp14.Items,
new Object[0]);
return new SplitData(temp, m_version);
}
case 15: {
Object temp = items_type.InvokeMember("Add",
BindingFlags.InvokeMethod,
null,
tp15.Items,
new Object[0]);
return new SplitData(temp, m_version);
}
case 16: {
Object temp = items_type.InvokeMember("Add",
BindingFlags.InvokeMethod,
null,
tp16.Items,
new Object[0]);
return new SplitData(temp, m_version);
}
case 17: {
Object temp = items_type.InvokeMember("Add",
BindingFlags.InvokeMethod,
null,
tp17.Items,
new Object[0]);
return new SplitData(temp, m_version);
}
}
return null;
}
public bool Allocate(int nInvoice, int nCredit, double dfAmount, DateTime dDate) {
switch (m_version) {
case 11:
return tp11.AllocatePayment(nInvoice, nCredit, dfAmount, dDate);
case 12:
return tp12.AllocatePayment(nInvoice, nCredit, dfAmount, dDate);
case 13:
return tp13.AllocatePayment(nInvoice, nCredit, dfAmount, dDate);
case 14:
return tp14.AllocatePayment(nInvoice, nCredit, dfAmount, dDate);
case 15:
return tp15.AllocatePayment(nInvoice, nCredit, dfAmount, dDate);
case 16:
return tp16.AllocatePayment(nInvoice, nCredit, dfAmount, dDate);
case 17:
return tp17.AllocatePayment(nInvoice, nCredit, dfAmount, dDate);
}
return false;
}
public int PostingNumber {
get {
switch (m_version) {
case 11:
return tp11.PostingNumber;
case 12:
return tp12.PostingNumber;
case 13:
return tp13.PostingNumber;
case 14:
return tp14.PostingNumber;
case 15:
return tp15.PostingNumber;
case 16:
return tp16.PostingNumber;
case 17:
return tp17.PostingNumber;
}
return -1;
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
using System.Text;
namespace FileSystemTest
{
public class Open_FM : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
// These tests rely on underlying file system so we need to make
// sure we can format it before we start the tests. If we can't
// format it, then we assume there is no FS to test on this platform.
// delete the directory DOTNETMF_FS_EMULATION
try
{
IOTests.IntializeVolume();
Directory.CreateDirectory(testDir);
Directory.SetCurrentDirectory(testDir);
}
catch (Exception ex)
{
Log.Comment("Skipping: Unable to initialize file system" + ex.Message);
return InitializeResult.Skip;
}
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
#region Local vars
private const string fileName = "file1.tmp";
private const string file2Name = "file2.txt";
private const string testDir = "Open_FM";
#endregion Local vars
#region Helper methods
private MFTestResults TestMethod(FileMode fm)
{
Log.Comment("Starting tests in FileMode: " + fm.ToString());
FileInfo fil2;
StreamWriter sw2;
Stream fs2 = null;
String str2;
int iCountErrors = 0;
if (File.Exists(fileName))
File.Delete(fileName);
Log.Comment("File does not exist");
//------------------------------------------------------------------
fil2 = new FileInfo(fileName);
switch (fm)
{
case FileMode.CreateNew:
case FileMode.Create:
case FileMode.OpenOrCreate:
try
{
Log.Comment( "With a null string" );
iCountErrors = 0; // ZeligBUG not resetting the value here leads to uninit iCountErrors value
fs2 = File.Open( null, fm );
if(!File.Exists( fileName ))
{
iCountErrors++;
Log.Exception( "File not created, FileMode==" + fm.ToString() );
}
}
catch (ArgumentException ex)
{
Log.Comment("Expected exception thrown :: " + ex.Message);
}
catch (Exception ex)
{
iCountErrors = 1;
Log.Exception("Unexpected exception thrown :: " + ex.ToString());
}
Log.Comment("with an empty string");
try
{
fs2 = File.Open("", fm);
if (!File.Exists(fileName))
{
iCountErrors++;
Log.Exception("File not created, FileMode==" + fm.ToString());
}
}
catch (ArgumentException ex)
{
Log.Comment("Expected exception thrown :: " + ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Log.Exception("Unexpected exception thrown :: " + ex.ToString());
}
fs2 = File.Open(fileName, fm);
if (!File.Exists(fileName))
{
iCountErrors++;
Log.Exception("File not created, FileMode==" + fm.ToString());
}
fs2.Close();
break;
case FileMode.Open:
case FileMode.Truncate:
try
{
Log.Comment( "Open or Truncate" );
iCountErrors = 0; // ZeligBUG not resetting the value here leads to uninit iCountErrors value
fs2 = File.Open( fileName, fm );
iCountErrors++;
Log.Exception("Expected exception not thrown");
fs2.Close();
}
catch (IOException fexc)
{
Log.Comment("Caught expected exception, fexc==" + fexc.Message);
iCountErrors = 0;
}
catch (Exception exc)
{
iCountErrors = 1;
Log.Exception("Incorrect exception thrown, exc==" + exc.ToString());
}
break;
case FileMode.Append:
try
{
Log.Comment( "Append" );
fs2 = File.Open(fileName, fm);
fs2.Write(new Byte[] { 54, 65, 54, 90 }, 0, 4);
if (fs2.Length != 4)
{
iCountErrors++;
Log.Exception("Unexpected file length .... " + fs2.Length);
}
fs2.Close();
iCountErrors = 0; // ZeligBUG not resetting the value here leads to uninit iCountErrors value
}
catch (Exception exc)
{
iCountErrors = 1;
Log.Exception("Incorrect exception thrown, exc==" + exc.ToString());
}
break;
default:
iCountErrors = 1;
Log.Exception("Invalid mode.");
break;
}
if (File.Exists(fileName))
File.Delete(fileName);
if(iCountErrors > 0) return MFTestResults.Fail;
//------------------------------------------------------------------
Log.Comment("File already exists");
//------------------------------------------------------------------
sw2 = new StreamWriter(fileName);
str2 = "Du er en ape";
sw2.Write(str2);
sw2.Close();
switch (fm)
{
case FileMode.CreateNew:
try
{
fs2 = File.Open( fileName, fm );
iCountErrors++;
Log.Exception("Expected exception not thrown");
fs2.Close();
}
catch (IOException aexc)
{
Log.Comment("Caught expected exception, aexc==" + aexc.Message);
}
catch (Exception exc)
{
iCountErrors++;
Log.Exception("Incorrect exception thrown, exc==" + exc.ToString());
}
break;
case FileMode.Create:
fs2 = File.Open(fileName, fm);
if (fs2.Length != 0)
{
iCountErrors++;
Log.Exception("Incorrect length of file==" + fil2.Length);
}
fs2.Close();
break;
case FileMode.OpenOrCreate:
case FileMode.Open:
fs2 = File.Open(fileName, fm);
if (fs2.Length != str2.Length)
{
iCountErrors++;
Log.Exception("Incorrect length on file==" + fil2.Length);
}
fs2.Close();
break;
case FileMode.Truncate:
fs2 = File.Open(fileName, fm);
if (fs2.Length != 0)
{
iCountErrors++;
Log.Exception("Incorrect length on file==" + fil2.Length);
}
fs2.Close();
break;
case FileMode.Append:
try
{
fs2 = File.Open(fileName, fm);
fs2.Write(new Byte[] { 54, 65, 54, 90 }, 0, 4);
if (fs2.Length != 16)
{ // already 12 characters are written to the file.
iCountErrors++;
Log.Exception("Unexpected file length .... " + fs2.Length);
}
fs2.Close();
}
catch (Exception exc)
{
iCountErrors++;
Log.Exception("Incorrect exception thrown, exc==" + exc.ToString());
}
break;
default:
iCountErrors++;
Log.Exception("Invalid mode.");
break;
}
if (File.Exists(fileName))
File.Delete(fileName);
return iCountErrors == 0 ? MFTestResults.Pass : MFTestResults.Fail;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public MFTestResults FileMode_Append()
{
return TestMethod(FileMode.Append);
}
[TestMethod]
public MFTestResults FileMode_Create()
{
return TestMethod(FileMode.Create);
}
[TestMethod]
public MFTestResults FileMode_CreateNew()
{
return TestMethod(FileMode.CreateNew);
}
[TestMethod]
public MFTestResults FileMode_Open()
{
return TestMethod(FileMode.Open);
}
[TestMethod]
public MFTestResults FileMode_OpenOrCreate()
{
return TestMethod(FileMode.OpenOrCreate);
}
[TestMethod]
public MFTestResults FileMode_Truncate()
{
return TestMethod(FileMode.Truncate);
}
[TestMethod]
public MFTestResults Invalid_FileMode()
{
MFTestResults result = MFTestResults.Pass;
try
{
// Cleanup
if (File.Exists(file2Name))
File.Delete(file2Name);
try
{
Log.Comment("-1 FileMode");
File.Open(file2Name, (FileMode)(-1));
Log.Exception( "Unexpected FileMode" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("0 FileMode");
File.Open(file2Name, 0);
Log.Exception( "Unexpected FileMode" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("7 FileMode");
File.Open(file2Name, (FileMode)7);
Log.Exception( "Unexpected FileMode" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */
Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
Log.Comment("Verify no file created");
if (File.Exists(file2Name))
{
Log.Exception( "Unexpected file found" );
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults Invalid_FileAccess()
{
MFTestResults result = MFTestResults.Pass;
try
{
// Cleanup
if (File.Exists(file2Name))
File.Delete(file2Name);
try
{
Log.Comment("-1 FileAccess");
File.Open(file2Name, FileMode.OpenOrCreate, (FileAccess)(-1));
Log.Exception( "Unexpected FileAccess" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("0 FileAccess");
File.Open(file2Name, FileMode.OpenOrCreate, (FileAccess)0);
Log.Exception( "Unexpected FileAccess" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("4 FileAccess");
File.Open(file2Name, FileMode.OpenOrCreate, (FileAccess)4);
Log.Exception( "Unexpected FileAccess" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
Log.Comment("Verify no file created");
if (File.Exists(file2Name))
{
Log.Exception( "Unexpected file found" );
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults Invalid_FileShare()
{
MFTestResults result = MFTestResults.Pass;
try
{
// Cleanup
if (File.Exists(file2Name))
File.Delete(file2Name);
try
{
Log.Comment("-1 FileShare");
File.Open(file2Name, FileMode.OpenOrCreate, FileAccess.ReadWrite, (FileShare)(-1));
Log.Exception( "Unexpected FileShare" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("74 FileShare");
File.Open(file2Name, FileMode.OpenOrCreate, FileAccess.ReadWrite, (FileShare)5);
Log.Exception( "Unexpected FileShare" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
Log.Comment("Verify no file created");
if (File.Exists(file2Name))
{
Log.Exception( "Unexpected file found" );
return MFTestResults.Fail;
}
return result;
}
#endregion Test Cases
public MFTestMethod[] Tests
{
get
{
return new MFTestMethod[]
{
new MFTestMethod( FileMode_Append, "FileMode_Append" ),
new MFTestMethod( FileMode_Create, "FileMode_Create" ),
new MFTestMethod( FileMode_CreateNew, "FileMode_CreateNew" ),
new MFTestMethod( FileMode_Open, "FileMode_Open" ),
new MFTestMethod( FileMode_OpenOrCreate, "FileMode_OpenOrCreate" ),
new MFTestMethod( FileMode_Truncate, "FileMode_Truncate" ),
new MFTestMethod( Invalid_FileMode, "Invalid_FileMode" ),
new MFTestMethod( Invalid_FileAccess, "Invalid_FileAccess" ),
new MFTestMethod( Invalid_FileShare, "Invalid_FileShare" ),
};
}
}
}
}
| |
// 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.Xml;
using System.Collections.Generic;
using System.Security;
namespace System.Runtime.Serialization
{
// NOTE: XmlReader methods that are not needed have been left un-implemented
internal class ExtensionDataReader : XmlReader
{
private enum ExtensionDataNodeType
{
None,
Element,
EndElement,
Text,
Xml,
ReferencedElement,
NullElement,
}
private ElementData[] _elements;
private ElementData _element;
private ElementData _nextElement;
private ReadState _readState = ReadState.Initial;
private ExtensionDataNodeType _internalNodeType;
private XmlNodeType _nodeType;
private int _depth;
private string _localName;
private string _ns;
private string _prefix;
private string _value;
private int _attributeCount;
private int _attributeIndex;
#pragma warning disable 0649
private XmlNodeReader _xmlNodeReader;
#pragma warning restore 0649
private Queue<IDataNode> _deserializedDataNodes;
private XmlObjectSerializerReadContext _context;
[SecurityCritical]
private static Dictionary<string, string> s_nsToPrefixTable;
[SecurityCritical]
private static Dictionary<string, string> s_prefixToNsTable;
[SecurityCritical]
static ExtensionDataReader()
{
s_nsToPrefixTable = new Dictionary<string, string>();
s_prefixToNsTable = new Dictionary<string, string>();
AddPrefix(Globals.XsiPrefix, Globals.SchemaInstanceNamespace);
AddPrefix(Globals.SerPrefix, Globals.SerializationNamespace);
AddPrefix(String.Empty, String.Empty);
}
internal ExtensionDataReader(XmlObjectSerializerReadContext context)
{
_attributeIndex = -1;
_context = context;
}
internal void SetDeserializedValue(object obj)
{
IDataNode deserializedDataNode = (_deserializedDataNodes == null || _deserializedDataNodes.Count == 0) ? null : _deserializedDataNodes.Dequeue();
if (deserializedDataNode != null && !(obj is IDataNode))
{
deserializedDataNode.Value = obj;
deserializedDataNode.IsFinalValue = true;
}
}
internal IDataNode GetCurrentNode()
{
IDataNode retVal = _element.dataNode;
Skip();
return retVal;
}
internal void SetDataNode(IDataNode dataNode, string name, string ns)
{
SetNextElement(dataNode, name, ns, null);
_element = _nextElement;
_nextElement = null;
SetElement();
}
internal void Reset()
{
_localName = null;
_ns = null;
_prefix = null;
_value = null;
_attributeCount = 0;
_attributeIndex = -1;
_depth = 0;
_element = null;
_nextElement = null;
_elements = null;
_deserializedDataNodes = null;
}
private bool IsXmlDataNode { get { return (_internalNodeType == ExtensionDataNodeType.Xml); } }
public override XmlNodeType NodeType { get { return IsXmlDataNode ? _xmlNodeReader.NodeType : _nodeType; } }
public override string LocalName { get { return IsXmlDataNode ? _xmlNodeReader.LocalName : _localName; } }
public override string NamespaceURI { get { return IsXmlDataNode ? _xmlNodeReader.NamespaceURI : _ns; } }
public override string Prefix { get { return IsXmlDataNode ? _xmlNodeReader.Prefix : _prefix; } }
public override string Value { get { return IsXmlDataNode ? _xmlNodeReader.Value : _value; } }
public override int Depth { get { return IsXmlDataNode ? _xmlNodeReader.Depth : _depth; } }
public override int AttributeCount { get { return IsXmlDataNode ? _xmlNodeReader.AttributeCount : _attributeCount; } }
public override bool EOF { get { return IsXmlDataNode ? _xmlNodeReader.EOF : (_readState == ReadState.EndOfFile); } }
public override ReadState ReadState { get { return IsXmlDataNode ? _xmlNodeReader.ReadState : _readState; } }
public override bool IsEmptyElement { get { return IsXmlDataNode ? _xmlNodeReader.IsEmptyElement : false; } }
public override bool IsDefault { get { return IsXmlDataNode ? _xmlNodeReader.IsDefault : base.IsDefault; } }
//public override char QuoteChar { get { return IsXmlDataNode ? xmlNodeReader.QuoteChar : base.QuoteChar; } }
public override XmlSpace XmlSpace { get { return IsXmlDataNode ? _xmlNodeReader.XmlSpace : base.XmlSpace; } }
public override string XmlLang { get { return IsXmlDataNode ? _xmlNodeReader.XmlLang : base.XmlLang; } }
public override string this[int i] { get { return IsXmlDataNode ? _xmlNodeReader[i] : GetAttribute(i); } }
public override string this[string name] { get { return IsXmlDataNode ? _xmlNodeReader[name] : GetAttribute(name); } }
public override string this[string name, string namespaceURI] { get { return IsXmlDataNode ? _xmlNodeReader[name, namespaceURI] : GetAttribute(name, namespaceURI); } }
public override bool MoveToFirstAttribute()
{
if (IsXmlDataNode)
return _xmlNodeReader.MoveToFirstAttribute();
if (_attributeCount == 0)
return false;
MoveToAttribute(0);
return true;
}
public override bool MoveToNextAttribute()
{
if (IsXmlDataNode)
return _xmlNodeReader.MoveToNextAttribute();
if (_attributeIndex + 1 >= _attributeCount)
return false;
MoveToAttribute(_attributeIndex + 1);
return true;
}
public override void MoveToAttribute(int index)
{
if (IsXmlDataNode)
_xmlNodeReader.MoveToAttribute(index);
else
{
if (index < 0 || index >= _attributeCount)
throw new XmlException(SR.InvalidXmlDeserializingExtensionData);
_nodeType = XmlNodeType.Attribute;
AttributeData attribute = _element.attributes[index];
_localName = attribute.localName;
_ns = attribute.ns;
_prefix = attribute.prefix;
_value = attribute.value;
_attributeIndex = index;
}
}
public override string GetAttribute(string name, string namespaceURI)
{
if (IsXmlDataNode)
return _xmlNodeReader.GetAttribute(name, namespaceURI);
for (int i = 0; i < _element.attributeCount; i++)
{
AttributeData attribute = _element.attributes[i];
if (attribute.localName == name && attribute.ns == namespaceURI)
return attribute.value;
}
return null;
}
public override bool MoveToAttribute(string name, string namespaceURI)
{
if (IsXmlDataNode)
return _xmlNodeReader.MoveToAttribute(name, _ns);
for (int i = 0; i < _element.attributeCount; i++)
{
AttributeData attribute = _element.attributes[i];
if (attribute.localName == name && attribute.ns == namespaceURI)
{
MoveToAttribute(i);
return true;
}
}
return false;
}
public override bool MoveToElement()
{
if (IsXmlDataNode)
return _xmlNodeReader.MoveToElement();
if (_nodeType != XmlNodeType.Attribute)
return false;
SetElement();
return true;
}
private void SetElement()
{
_nodeType = XmlNodeType.Element;
_localName = _element.localName;
_ns = _element.ns;
_prefix = _element.prefix;
_value = String.Empty;
_attributeCount = _element.attributeCount;
_attributeIndex = -1;
}
[SecuritySafeCritical]
public override string LookupNamespace(string prefix)
{
if (IsXmlDataNode)
return _xmlNodeReader.LookupNamespace(prefix);
string ns;
if (!s_prefixToNsTable.TryGetValue(prefix, out ns))
return null;
return ns;
}
public override void Skip()
{
if (IsXmlDataNode)
_xmlNodeReader.Skip();
else
{
if (ReadState != ReadState.Interactive)
return;
MoveToElement();
if (IsElementNode(_internalNodeType))
{
int depth = 1;
while (depth != 0)
{
if (!Read())
throw new XmlException(SR.InvalidXmlDeserializingExtensionData);
if (IsElementNode(_internalNodeType))
depth++;
else if (_internalNodeType == ExtensionDataNodeType.EndElement)
{
ReadEndElement();
depth--;
}
}
}
else
Read();
}
}
private bool IsElementNode(ExtensionDataNodeType nodeType)
{
return (nodeType == ExtensionDataNodeType.Element ||
nodeType == ExtensionDataNodeType.ReferencedElement ||
nodeType == ExtensionDataNodeType.NullElement);
}
protected override void Dispose(bool disposing)
{
if (IsXmlDataNode)
_xmlNodeReader.Dispose();
else
{
Reset();
_readState = ReadState.Closed;
}
base.Dispose(disposing);
}
public override bool Read()
{
if (_nodeType == XmlNodeType.Attribute && MoveToNextAttribute())
return true;
MoveNext(_element.dataNode);
switch (_internalNodeType)
{
case ExtensionDataNodeType.Element:
case ExtensionDataNodeType.ReferencedElement:
case ExtensionDataNodeType.NullElement:
PushElement();
SetElement();
break;
case ExtensionDataNodeType.Text:
_nodeType = XmlNodeType.Text;
_prefix = String.Empty;
_ns = String.Empty;
_localName = String.Empty;
_attributeCount = 0;
_attributeIndex = -1;
break;
case ExtensionDataNodeType.EndElement:
_nodeType = XmlNodeType.EndElement;
_prefix = String.Empty;
_ns = String.Empty;
_localName = String.Empty;
_value = String.Empty;
_attributeCount = 0;
_attributeIndex = -1;
PopElement();
break;
case ExtensionDataNodeType.None:
if (_depth != 0)
throw new XmlException(SR.InvalidXmlDeserializingExtensionData);
_nodeType = XmlNodeType.None;
_prefix = String.Empty;
_ns = String.Empty;
_localName = String.Empty;
_value = String.Empty;
_attributeCount = 0;
_readState = ReadState.EndOfFile;
return false;
case ExtensionDataNodeType.Xml:
// do nothing
break;
default:
Fx.Assert("ExtensionDataReader in invalid state");
throw new SerializationException(SR.InvalidStateInExtensionDataReader);
}
_readState = ReadState.Interactive;
return true;
}
public override string Name
{
get
{
if (IsXmlDataNode)
{
return _xmlNodeReader.Name;
}
Fx.Assert("ExtensionDataReader Name property should only be called for IXmlSerializable");
return string.Empty;
}
}
public override bool HasValue
{
get
{
if (IsXmlDataNode)
{
return _xmlNodeReader.HasValue;
}
Fx.Assert("ExtensionDataReader HasValue property should only be called for IXmlSerializable");
return false;
}
}
public override string BaseURI
{
get
{
if (IsXmlDataNode)
{
return _xmlNodeReader.BaseURI;
}
Fx.Assert("ExtensionDataReader BaseURI property should only be called for IXmlSerializable");
return string.Empty;
}
}
public override XmlNameTable NameTable
{
get
{
if (IsXmlDataNode)
{
return _xmlNodeReader.NameTable;
}
Fx.Assert("ExtensionDataReader NameTable property should only be called for IXmlSerializable");
return null;
}
}
public override string GetAttribute(string name)
{
if (IsXmlDataNode)
{
return _xmlNodeReader.GetAttribute(name);
}
Fx.Assert("ExtensionDataReader GetAttribute method should only be called for IXmlSerializable");
return null;
}
public override string GetAttribute(int i)
{
if (IsXmlDataNode)
{
return _xmlNodeReader.GetAttribute(i);
}
Fx.Assert("ExtensionDataReader GetAttribute method should only be called for IXmlSerializable");
return null;
}
public override bool MoveToAttribute(string name)
{
if (IsXmlDataNode)
{
return _xmlNodeReader.MoveToAttribute(name);
}
Fx.Assert("ExtensionDataReader MoveToAttribute method should only be called for IXmlSerializable");
return false;
}
public override void ResolveEntity()
{
if (IsXmlDataNode)
{
_xmlNodeReader.ResolveEntity();
}
else
{
Fx.Assert("ExtensionDataReader ResolveEntity method should only be called for IXmlSerializable");
}
}
public override bool ReadAttributeValue()
{
if (IsXmlDataNode)
{
return _xmlNodeReader.ReadAttributeValue();
}
Fx.Assert("ExtensionDataReader ReadAttributeValue method should only be called for IXmlSerializable");
return false;
}
private void MoveNext(IDataNode dataNode)
{
throw NotImplemented.ByDesign;
}
private void SetNextElement(IDataNode node, string name, string ns, string prefix)
{
throw NotImplemented.ByDesign;
}
private void PushElement()
{
GrowElementsIfNeeded();
_elements[_depth++] = _element;
if (_nextElement == null)
_element = GetNextElement();
else
{
_element = _nextElement;
_nextElement = null;
}
}
private void PopElement()
{
_prefix = _element.prefix;
_localName = _element.localName;
_ns = _element.ns;
if (_depth == 0)
return;
_depth--;
if (_elements != null)
{
_element = _elements[_depth];
}
}
private void GrowElementsIfNeeded()
{
if (_elements == null)
_elements = new ElementData[8];
else if (_elements.Length == _depth)
{
ElementData[] newElements = new ElementData[_elements.Length * 2];
Array.Copy(_elements, 0, newElements, 0, _elements.Length);
_elements = newElements;
}
}
private ElementData GetNextElement()
{
int nextDepth = _depth + 1;
return (_elements == null || _elements.Length <= nextDepth || _elements[nextDepth] == null)
? new ElementData() : _elements[nextDepth];
}
[SecuritySafeCritical]
internal static string GetPrefix(string ns)
{
string prefix;
ns = ns ?? String.Empty;
if (!s_nsToPrefixTable.TryGetValue(ns, out prefix))
{
lock (s_nsToPrefixTable)
{
if (!s_nsToPrefixTable.TryGetValue(ns, out prefix))
{
prefix = (ns == null || ns.Length == 0) ? String.Empty : "p" + s_nsToPrefixTable.Count;
AddPrefix(prefix, ns);
}
}
}
return prefix;
}
[SecuritySafeCritical]
private static void AddPrefix(string prefix, string ns)
{
s_nsToPrefixTable.Add(ns, prefix);
s_prefixToNsTable.Add(prefix, ns);
}
}
#if USE_REFEMIT
public class AttributeData
#else
internal class AttributeData
#endif
{
public string prefix;
public string ns;
public string localName;
public string value;
}
#if USE_REFEMIT
public class ElementData
#else
internal class ElementData
#endif
{
public string localName;
public string ns;
public string prefix;
public int attributeCount;
public AttributeData[] attributes;
public IDataNode dataNode;
public int childElementIndex;
public void AddAttribute(string prefix, string ns, string name, string value)
{
GrowAttributesIfNeeded();
AttributeData attribute = attributes[attributeCount];
if (attribute == null)
attributes[attributeCount] = attribute = new AttributeData();
attribute.prefix = prefix;
attribute.ns = ns;
attribute.localName = name;
attribute.value = value;
attributeCount++;
}
private void GrowAttributesIfNeeded()
{
if (attributes == null)
attributes = new AttributeData[4];
else if (attributes.Length == attributeCount)
{
AttributeData[] newAttributes = new AttributeData[attributes.Length * 2];
Array.Copy(attributes, 0, newAttributes, 0, attributes.Length);
attributes = newAttributes;
}
}
}
}
| |
//
// ToolkitEngine.cs
//
// Author:
// Lluis Sanchez Gual <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 Xwt.Backends;
using Xwt.Drawing;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
namespace Xwt
{
public sealed class Toolkit: IFrontend
{
static Toolkit currentEngine;
static Toolkit nativeEngine;
static Dictionary<Type, Toolkit> toolkits = new Dictionary<Type, Toolkit> ();
ToolkitEngineBackend backend;
ApplicationContext context;
XwtTaskScheduler scheduler;
ToolkitType toolkitType;
ToolkitDefaults defaults;
int inUserCode;
Queue<Action> exitActions = new Queue<Action> ();
bool exitCallbackRegistered;
static KnownBackend[] knownBackends = new [] {
new KnownBackend { Type = ToolkitType.Gtk3, TypeName = "Xwt.GtkBackend.GtkEngine, Xwt.Gtk3" },
new KnownBackend { Type = ToolkitType.Gtk, TypeName = "Xwt.GtkBackend.GtkEngine, Xwt.Gtk" },
new KnownBackend { Type = ToolkitType.XamMac, TypeName = "Xwt.Mac.MacEngine, Xwt.XamMac" },
new KnownBackend { Type = ToolkitType.Cocoa, TypeName = "Xwt.Mac.MacEngine, Xwt.Mac" },
new KnownBackend { Type = ToolkitType.Wpf, TypeName = "Xwt.WPFBackend.WPFEngine, Xwt.WPF" },
};
class KnownBackend
{
public ToolkitType Type { get; set; }
public string TypeName { get; set; }
public string FullTypeName {
get {
return TypeName + ", Version=" + typeof(Application).Assembly.GetName ().Version;
}
}
}
Dictionary<string,Image> stockIcons = new Dictionary<string, Image> ();
/// <summary>
/// Gets the current toolkit engine.
/// </summary>
/// <value>The engine currently used by Xwt.</value>
public static Toolkit CurrentEngine {
get { return currentEngine; }
}
/// <summary>
/// Gets the native platform toolkit engine.
/// </summary>
/// <value>The native engine.</value>
public static Toolkit NativeEngine {
get {
if (nativeEngine == null) {
switch (Desktop.DesktopType) {
case DesktopType.Linux:
// don't mix Gtk2 and Gtk3
if (CurrentEngine != null && (CurrentEngine.Type == ToolkitType.Gtk || CurrentEngine.Type == ToolkitType.Gtk3))
nativeEngine = CurrentEngine;
else if (!TryLoad (ToolkitType.Gtk3, out nativeEngine))
TryLoad (ToolkitType.Gtk, out nativeEngine);
break;
case DesktopType.Windows:
TryLoad (ToolkitType.Wpf, out nativeEngine);
break;
case DesktopType.Mac:
TryLoad (ToolkitType.XamMac, out nativeEngine);
break;
}
}
if (nativeEngine == null)
nativeEngine = CurrentEngine;
return nativeEngine;
}
}
/// <summary>
/// Gets all loaded toolkits.
/// </summary>
/// <value>The loaded toolkits.</value>
public static IEnumerable<Toolkit> LoadedToolkits {
get { return toolkits.Values; }
}
/// <summary>
/// Gets the application context.
/// </summary>
/// <value>The application context.</value>
internal ApplicationContext Context {
get { return context; }
}
/// <summary>
/// Gets the toolkit backend.
/// </summary>
/// <value>The toolkit backend.</value>
internal ToolkitEngineBackend Backend {
get { return backend; }
}
/// <summary>
/// Gets the toolkit task scheduler.
/// </summary>
/// <value>The toolkit specific task scheduler.</value>
/// <remarks>
/// The Xwt task scheduler marshals every Task to the Xwt GUI thread without concurrency.
/// </remarks>
internal XwtTaskScheduler Scheduler {
get { return scheduler; }
}
object IFrontend.Backend {
get { return backend; }
}
Toolkit IFrontend.ToolkitEngine {
get { return this; }
}
private Toolkit ()
{
context = new ApplicationContext (this);
scheduler = new XwtTaskScheduler (this);
}
/// <summary>
/// Gets or sets the type of the toolkit.
/// </summary>
/// <value>The toolkit type.</value>
public ToolkitType Type {
get { return toolkitType; }
internal set { toolkitType = value; }
}
/// <summary>
/// Disposes all loaded toolkits.
/// </summary>
internal static void DisposeAll ()
{
foreach (var t in toolkits.Values)
t.Backend.Dispose ();
}
/// <summary>
/// Load toolkit identified by its full type name.
/// </summary>
/// <param name="fullTypeName">The <see cref="Type.FullName"/> of the toolkit type.</param>
public static Toolkit Load (string fullTypeName)
{
return Load (fullTypeName, true);
}
/// <summary>
/// Load toolkit identified by its full type name.
/// </summary>
/// <param name="fullTypeName">The <see cref="Type.FullName"/> of the toolkit type.</param>
/// <param name="isGuest">If set to <c>true</c> the toolkit is loaded as guest of another toolkit.</param>
internal static Toolkit Load (string fullTypeName, bool isGuest)
{
Toolkit t = new Toolkit ();
if (!string.IsNullOrEmpty (fullTypeName)) {
t.LoadBackend (fullTypeName, isGuest, true);
var bk = knownBackends.FirstOrDefault (tk => fullTypeName.StartsWith (tk.TypeName));
if (bk != null)
t.Type = bk.Type;
return t;
}
foreach (var bk in knownBackends) {
if (t.LoadBackend (bk.FullTypeName, isGuest, false)) {
t.Type = bk.Type;
return t;
}
}
throw new InvalidOperationException ("Xwt engine not found");
}
/// <summary>
/// Load a toolkit of a specified type.
/// </summary>
/// <param name="type">The toolkit type.</param>
public static Toolkit Load (ToolkitType type)
{
var et = toolkits.Values.FirstOrDefault (tk => tk.toolkitType == type);
if (et != null)
return et;
Toolkit t = new Toolkit ();
t.toolkitType = type;
t.LoadBackend (GetBackendType (type), true, true);
return t;
}
/// <summary>
/// Tries to load a toolkit
/// </summary>
/// <returns><c>true</c>, the toolkit has been loaded, <c>false</c> otherwise.</returns>
/// <param name="type">Toolkit type</param>
/// <param name="toolkit">The loaded toolkit</param>
public static bool TryLoad (ToolkitType type, out Toolkit toolkit)
{
var et = toolkits.Values.FirstOrDefault (tk => tk.toolkitType == type);
if (et != null) {
toolkit = et;
return true;
}
Toolkit t = new Toolkit ();
t.toolkitType = type;
if (t.LoadBackend (GetBackendType (type), true, false)) {
toolkit = t;
return true;
}
toolkit = null;
return false;
}
/// <summary>
/// Gets the <see cref="Type.FullName"/> of the toolkit identified by toolkit type.
/// </summary>
/// <returns>The toolkit type name.</returns>
/// <param name="type">The toolkit type.</param>
internal static string GetBackendType (ToolkitType type)
{
var t = knownBackends.FirstOrDefault (tk => tk.Type == type);
if (t != null)
return t.FullTypeName;
throw new ArgumentException ("Invalid toolkit type");
}
bool LoadBackend (string type, bool isGuest, bool throwIfFails)
{
int i = type.IndexOf (',');
string assembly = type.Substring (i+1).Trim ();
type = type.Substring (0, i).Trim ();
try {
Assembly asm = Assembly.Load (assembly);
if (asm != null) {
Type t = asm.GetType (type);
if (t != null) {
backend = (ToolkitEngineBackend) Activator.CreateInstance (t);
Initialize (isGuest);
return true;
}
}
}
catch (Exception ex) {
if (throwIfFails)
throw new Exception ("Toolkit could not be loaded", ex);
Application.NotifyException (ex);
}
if (throwIfFails)
throw new Exception ("Toolkit could not be loaded");
return false;
}
void Initialize (bool isGuest)
{
toolkits[Backend.GetType ()] = this;
backend.Initialize (this, isGuest);
ContextBackendHandler = Backend.CreateBackend<ContextBackendHandler> ();
GradientBackendHandler = Backend.CreateBackend<GradientBackendHandler> ();
TextLayoutBackendHandler = Backend.CreateBackend<TextLayoutBackendHandler> ();
FontBackendHandler = Backend.CreateBackend<FontBackendHandler> ();
ClipboardBackend = Backend.CreateBackend<ClipboardBackend> ();
ImageBuilderBackendHandler = Backend.CreateBackend<ImageBuilderBackendHandler> ();
ImagePatternBackendHandler = Backend.CreateBackend<ImagePatternBackendHandler> ();
ImageBackendHandler = Backend.CreateBackend<ImageBackendHandler> ();
DrawingPathBackendHandler = Backend.CreateBackend<DrawingPathBackendHandler> ();
DesktopBackend = Backend.CreateBackend<DesktopBackend> ();
VectorImageRecorderContextHandler = new VectorImageRecorderContextHandler (this);
KeyboardHandler = Backend.CreateBackend<KeyboardHandler> ();
}
/// <summary>
/// Gets the toolkit backend from a loaded toolkit.
/// </summary>
/// <returns>The toolkit backend, or <c>null</c> if the toolkit is not loaded.</returns>
/// <param name="type">The Type of the loaded toolkit.</param>
internal static ToolkitEngineBackend GetToolkitBackend (Type type)
{
Toolkit t;
if (toolkits.TryGetValue (type, out t))
return t.backend;
else
return null;
}
/// <summary>
/// Set the toolkit as the active toolkit used by Xwt.
/// </summary>
internal void SetActive ()
{
currentEngine = this;
}
/// <summary>
/// Gets the defaults for the current toolkit.
/// </summary>
/// <value>The toolkit defaults.</value>
public ToolkitDefaults Defaults {
get {
if (defaults == null)
defaults = new ToolkitDefaults ();
return defaults;
}
}
/// <summary>
/// Gets a reference to the native widget wrapped by an Xwt widget
/// </summary>
/// <returns>The native widget currently used by Xwt for the specific widget.</returns>
/// <param name="w">The Xwt widget.</param>
public object GetNativeWidget (Widget w)
{
ValidateObject (w);
w.SetExtractedAsNative ();
return backend.GetNativeWidget (w);
}
/// <summary>
/// Gets a reference to the native window wrapped by an Xwt window
/// </summary>
/// <returns>The native window currently used by Xwt for the specific window, or null.</returns>
/// <param name="w">The Xwt window.</param>
/// <remarks>
/// If the window backend belongs to a different toolkit and the current toolkit is the
/// native toolkit for the current platform, GetNativeWindow will return the underlying
/// native window, or null if the operation is not supported for the current toolkit.
/// </remarks>
public object GetNativeWindow (WindowFrame w)
{
return backend.GetNativeWindow (w);
}
/// <summary>
/// Gets a reference to the native platform window used by the specified backend.
/// </summary>
/// <returns>The native window currently used by Xwt for the specific window, or null.</returns>
/// <param name="w">The Xwt window.</param>
/// <remarks>
/// If the window backend belongs to a different toolkit and the current toolkit is the
/// native toolkit for the current platform, GetNativeWindow will return the underlying
/// native window, or null if the operation is not supported for the current toolkit.
/// </remarks>
public object GetNativeWindow (IWindowFrameBackend w)
{
return backend.GetNativeWindow (w);
}
/// <summary>
/// Gets a reference to the image object wrapped by an XWT Image
/// </summary>
/// <returns>The native image object used by Xwt for the specific image.</returns>
/// <param name="image">The native Image object.</param>
public object GetNativeImage (Image image)
{
ValidateObject (image);
return backend.GetNativeImage (image);
}
/// <summary>
/// Creates a native toolkit object.
/// </summary>
/// <returns>A new native toolkit object.</returns>
/// <typeparam name="T">The type of the object to create.</typeparam>
public T CreateObject<T> () where T:new()
{
var oldEngine = currentEngine;
try {
currentEngine = this;
return new T ();
} finally {
currentEngine = oldEngine;
}
}
/// <summary>
/// Invokes the specified action using this toolkit.
/// </summary>
/// <param name="a">The action to invoke in the context of this toolkit.</param>
/// <remarks>
/// Invoke allows dynamic toolkit switching. It will set <see cref="CurrentEngine"/> to this toolkit and reset
/// it back to its original value after the action has been executed.
///
/// Invoke must be executed on the UI thread. The action will not be synchronized with the main UI thread automatically.
/// </remarks>
/// <returns><c>true</c> if the action has been executed sucessfully; otherwise, <c>false</c>.</returns>
public bool Invoke (Action a)
{
var oldEngine = currentEngine;
try {
currentEngine = this;
EnterUserCode ();
a ();
ExitUserCode (null);
return true;
} catch (Exception ex) {
ExitUserCode (ex);
return false;
} finally {
currentEngine = oldEngine;
}
}
internal void InvokeAndThrow (Action a)
{
var oldEngine = currentEngine;
try {
currentEngine = this;
EnterUserCode();
a();
} finally {
ExitUserCode(null);
currentEngine = oldEngine;
}
}
/// <summary>
/// Invokes an action after the user code has been processed.
/// </summary>
/// <param name="a">The action to invoke after processing user code.</param>
internal void InvokePlatformCode (Action a)
{
int prevCount = inUserCode;
try {
inUserCode = 1;
ExitUserCode (null);
a ();
} finally {
inUserCode = prevCount;
}
}
/// <summary>
/// Enters the user code.
/// </summary>
/// <remarks>EnterUserCode must be called before executing any user code.</remarks>
internal void EnterUserCode ()
{
inUserCode++;
}
/// <summary>
/// Exits the user code.
/// </summary>
/// <param name="error">Exception thrown during user code execution, or <c>null</c></param>
internal void ExitUserCode (Exception error)
{
if (error != null) {
Invoke (delegate {
Application.NotifyException (error);
});
}
if (inUserCode == 1 && !exitCallbackRegistered) {
while (exitActions.Count > 0) {
try {
exitActions.Dequeue ()();
} catch (Exception ex) {
Invoke (delegate {
Application.NotifyException (ex);
});
}
}
}
inUserCode--;
}
void DispatchExitActions ()
{
// This pair of calls will flush the exit action queue
exitCallbackRegistered = false;
EnterUserCode ();
ExitUserCode (null);
}
/// <summary>
/// Adds the action to the exit action queue.
/// </summary>
/// <param name="a">The action to invoke after processing user code.</param>
internal void QueueExitAction (Action a)
{
exitActions.Enqueue (a);
if (inUserCode == 0) {
// Not in an XWT handler. This may happen when embedding XWT in another toolkit and
// XWT widgets are manipulated from event handlers of the native toolkit which
// are not invoked using ApplicationContext.InvokeUserCode.
if (!exitCallbackRegistered) {
exitCallbackRegistered = true;
// Try to use a native method of queuing exit actions
Toolkit.CurrentEngine.Backend.InvokeBeforeMainLoop (DispatchExitActions);
}
}
}
/// <summary>
/// Gets a value indicating whether the GUI Thread is currently executing user code.
/// </summary>
/// <value><c>true</c> if in user code; otherwise, <c>false</c>.</value>
public bool InUserCode {
get { return inUserCode > 0; }
}
/// <summary>
/// Wraps a native window into an Xwt window object.
/// </summary>
/// <returns>An Xwt window with the specified native window backend.</returns>
/// <param name="nativeWindow">The native window.</param>
public WindowFrame WrapWindow (object nativeWindow)
{
if (nativeWindow == null)
return null;
return new NativeWindowFrame (backend.GetBackendForWindow (nativeWindow));
}
/// <summary>
/// Wraps a native widget into an Xwt widget object.
/// </summary>
/// <returns>An Xwt widget with the specified native widget backend.</returns>
/// <param name="nativeWidget">The native widget.</param>
public Widget WrapWidget (object nativeWidget, NativeWidgetSizing preferredSizing = NativeWidgetSizing.External)
{
var externalWidget = nativeWidget as Widget;
if (externalWidget != null) {
if (externalWidget.Surface.ToolkitEngine == this)
return externalWidget;
nativeWidget = externalWidget.Surface.ToolkitEngine.GetNativeWidget (externalWidget);
}
var embedded = CreateObject<EmbeddedNativeWidget> ();
embedded.Initialize (nativeWidget, externalWidget, preferredSizing);
return embedded;
}
/// <summary>
/// Wraps a native image object into an Xwt image instance.
/// </summary>
/// <returns>The Xwt image containing the native image.</returns>
/// <param name="nativeImage">The native image.</param>
public Image WrapImage (object nativeImage)
{
return new Image (backend.GetBackendForImage (nativeImage), this);
}
/// <summary>
/// Wraps a native drawing context into an Xwt context object.
/// </summary>
/// <returns>The Xwt drawing context.</returns>
/// <param name="nativeWidget">The native widget to use for drawing.</param>
/// <param name="nativeContext">The native drawing context.</param>
public Context WrapContext (object nativeWidget, object nativeContext)
{
return new Context (backend.GetBackendForContext (nativeWidget, nativeContext), this);
}
/// <summary>
/// Validates that the backend of an Xwt component belongs to the currently loaded toolkit.
/// </summary>
/// <returns>The validated Xwt object.</returns>
/// <param name="obj">The Xwt object.</param>
/// <exception cref="InvalidOperationException">The component belongs to a different toolkit</exception>
public object ValidateObject (object obj)
{
if (obj is Image)
((Image)obj).InitForToolkit (this);
else if (obj is TextLayout)
((TextLayout)obj).InitForToolkit (this);
else if (obj is Font) {
var font = (Font)obj;
// If the font instance is a system font, we swap instances
// to not corrupt the backend of the singletons
if (font.ToolkitEngine != this) {
var fbh = font.ToolkitEngine.FontBackendHandler;
if (font.Family == fbh.SystemFont.Family)
font = FontBackendHandler.SystemFont.WithSettings (font);
if (font.Family == fbh.SystemMonospaceFont.Family)
font = FontBackendHandler.SystemMonospaceFont.WithSettings (font);
if (font.Family == fbh.SystemSansSerifFont.Family)
font = FontBackendHandler.SystemSansSerifFont.WithSettings (font);
if (font.Family == fbh.SystemSerifFont.Family)
font = FontBackendHandler.SystemSerifFont.WithSettings (font);
}
font.InitForToolkit (this);
obj = font;
} else if (obj is Gradient) {
((Gradient)obj).InitForToolkit (this);
} else if (obj is IFrontend) {
if (((IFrontend)obj).ToolkitEngine != this)
throw new InvalidOperationException ("Object belongs to a different toolkit");
}
return obj;
}
/// <summary>
/// Gets a toolkit backend of an Xwt component and validates
/// that it belongs to the currently loaded toolkit.
/// </summary>
/// <returns>The toolkit backend of the Xwt component.</returns>
/// <param name="obj">The Xwt component.</param>
/// <exception cref="InvalidOperationException">The component belongs to a different toolkit</exception>
public object GetSafeBackend (object obj)
{
return GetBackend (ValidateObject (obj));
}
/// <summary>
/// Gets a toolkit backend currently used by an Xwt component.
/// </summary>
/// <returns>The toolkit backend of the Xwt component.</returns>
/// <param name="obj">The Xwt component.</param>
/// <exception cref="InvalidOperationException">The component does not have a backend</exception>
public static object GetBackend (object obj)
{
if (obj is IFrontend)
return ((IFrontend)obj).Backend;
else if (obj == null)
return null;
else
throw new InvalidOperationException ("Object doesn't have a backend");
}
/// <summary>
/// Creates an Xwt frontend for a backend.
/// </summary>
/// <returns>The Xwt frontend.</returns>
/// <param name="ob">The toolkit backend.</param>
/// <typeparam name="T">The frontend Type.</typeparam>
public T CreateFrontend<T> (object ob)
{
throw new NotImplementedException ();
}
/// <summary>
/// Renders the widget into an Xwt Image.
/// </summary>
/// <returns>An Xwt Image containing the rendered bitmap.</returns>
/// <param name="widget">The Widget to render.</param>
public Image RenderWidget (Widget widget)
{
return new Image (backend.RenderWidget (widget), this);
}
/// <summary>
/// Renders an image to the provided native drawing context
/// </summary>
/// <param name="nativeWidget">The native widget.</param>
/// <param name="nativeContext">The native context.</param>
/// <param name="img">The Image to render.</param>
/// <param name="x">The destinate x coordinate.</param>
/// <param name="y">The destinate y coordinate.</param>
public void RenderImage (object nativeWidget, object nativeContext, Image img, double x, double y)
{
ValidateObject (img);
img.GetFixedSize (); // Ensure that it has a size
backend.RenderImage (nativeWidget, nativeContext, img.GetImageDescription (this), x, y);
}
/// <summary>
/// Gets the information about Xwt features supported by the toolkit.
/// </summary>
/// <value>The supported features.</value>
public ToolkitFeatures SupportedFeatures {
get { return backend.SupportedFeatures; }
}
/// <summary>
/// Registers a backend for an Xwt backend interface.
/// </summary>
/// <typeparam name="TBackend">The backend Type</typeparam>
/// <typeparam name="TImplementation">The Xwt interface implemented by the backend.</typeparam>
public void RegisterBackend<TBackend, TImplementation> () where TImplementation: TBackend
{
backend.RegisterBackend<TBackend, TImplementation> ();
}
/// <summary>
/// Gets the stock icon identified by the stock id.
/// </summary>
/// <returns>The stock icon.</returns>
/// <param name="id">The stock identifier.</param>
internal Image GetStockIcon (string id)
{
Image img;
if (!stockIcons.TryGetValue (id, out img))
stockIcons [id] = img = ImageBackendHandler.GetStockIcon (id);
return img;
}
internal ContextBackendHandler ContextBackendHandler;
internal GradientBackendHandler GradientBackendHandler;
internal TextLayoutBackendHandler TextLayoutBackendHandler;
internal FontBackendHandler FontBackendHandler;
internal ClipboardBackend ClipboardBackend;
internal ImageBuilderBackendHandler ImageBuilderBackendHandler;
internal ImagePatternBackendHandler ImagePatternBackendHandler;
internal ImageBackendHandler ImageBackendHandler;
internal DrawingPathBackendHandler DrawingPathBackendHandler;
internal DesktopBackend DesktopBackend;
internal VectorImageRecorderContextHandler VectorImageRecorderContextHandler;
internal KeyboardHandler KeyboardHandler;
}
class NativeWindowFrame: WindowFrame
{
public NativeWindowFrame (IWindowFrameBackend backend)
{
BackendHost.SetCustomBackend (backend);
}
}
[Flags]
public enum ToolkitFeatures: int
{
/// <summary>
/// Widget opacity/transparancy.
/// </summary>
WidgetOpacity = 1,
/// <summary>
/// Window opacity/transparancy.
/// </summary>
WindowOpacity = 2,
/// <summary>
/// All available features
/// </summary>
All = WidgetOpacity | WindowOpacity
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
namespace ModestTree
{
public static class LinqExtensions
{
public static IEnumerable<T> Append<T>(this IEnumerable<T> first, T item)
{
foreach (T t in first)
{
yield return t;
}
yield return item;
}
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> first, T item)
{
yield return item;
foreach (T t in first)
{
yield return t;
}
}
// Return the first item when the list is of length one and otherwise returns default
public static TSource OnlyOrDefault<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
var results = source.Take(2).ToArray();
return results.Length == 1 ? results[0] : default(TSource);
}
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
foreach (T t in second)
{
yield return t;
}
foreach (T t in first)
{
yield return t;
}
}
// These are more efficient than Count() in cases where the size of the collection is not known
public static bool HasAtLeast<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount).Count() == amount;
}
public static bool HasMoreThan<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.HasAtLeast(amount+1);
}
public static bool HasLessThan<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.HasAtMost(amount-1);
}
public static bool HasAtMost<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount + 1).Count() <= amount;
}
public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
return !enumerable.Any();
}
public static IEnumerable<T> GetDuplicates<T>(this IEnumerable<T> list)
{
return list.GroupBy(x => x).Where(x => x.Skip(1).Any()).Select(x => x.Key);
}
public static IEnumerable<T> ReplaceOrAppend<T>(
this IEnumerable<T> enumerable, Predicate<T> match, T replacement)
{
bool replaced = false;
foreach (T t in enumerable)
{
if (match(t))
{
replaced = true;
yield return replacement;
}
else
{
yield return t;
}
}
if (!replaced)
{
yield return replacement;
}
}
public static IEnumerable<T> ToEnumerable<T>(this IEnumerator enumerator)
{
while (enumerator.MoveNext())
{
yield return (T)enumerator.Current;
}
}
public static IEnumerable<T> ToEnumerable<T>(this IEnumerator<T> enumerator)
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> enumerable)
{
return new HashSet<T>(enumerable);
}
// This is more efficient than just Count() < x because it will end early
// rather than iterating over the entire collection
public static bool IsLength<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount + 1).Count() == amount;
}
public static T GetSingle<T>(this object[] objectArray, bool required)
{
if (required)
{
return objectArray.Where(x => x is T).Cast<T>().Single();
}
else
{
return objectArray.Where(x => x is T).Cast<T>().SingleOrDefault();
}
}
public static IEnumerable<T> OfType<T>(this IEnumerable<T> source, Type type)
{
Assert.That(type.DerivesFromOrEqual<T>());
return source.Where(x => x.GetType() == type);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return source.DistinctBy(keySelector, null);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
if (source == null)
throw new ArgumentNullException("source");
if (keySelector == null)
throw new ArgumentNullException("keySelector");
return DistinctByImpl(source, keySelector, comparer);
}
static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
var knownKeys = new HashSet<TKey>(comparer);
foreach (var element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
public static T Second<T>(this IEnumerable<T> list)
{
return list.Skip(1).First();
}
public static T SecondOrDefault<T>(this IEnumerable<T> list)
{
return list.Skip(1).FirstOrDefault();
}
public static int RemoveAll<T>(this LinkedList<T> list, Func<T, bool> predicate)
{
int numRemoved = 0;
var currentNode = list.First;
while (currentNode != null)
{
if (predicate(currentNode.Value))
{
var toRemove = currentNode;
currentNode = currentNode.Next;
list.Remove(toRemove);
numRemoved++;
}
else
{
currentNode = currentNode.Next;
}
}
return numRemoved;
}
// LINQ already has a method called "Contains" that does the same thing as this
// BUT it fails to work with Mono 3.5 in some cases.
// For example the following prints False, True in Mono 3.5 instead of True, True like it should:
//
// IEnumerable<string> args = new string[]
// {
// "",
// null,
// };
// Log.Info(args.ContainsItem(null));
// Log.Info(args.Where(x => x == null).Any());
public static bool ContainsItem<T>(this IEnumerable<T> list, T value)
{
// Use object.Equals to support null values
return list.Where(x => object.Equals(x, value)).Any();
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
// The test revealed some problems of GCStress infrastructure on platforms with multi reg returns (arm64, amd64 Unix).
// It required GCStress=0xc and GcStressOnDirectCalls=1 to hit issues. The issues were with saving GC pointers in the return registers.
// The GC infra has to correctly mark registers with pointers as alive and must not report registers without pointers.
#if BIT32
using nint = System.Int32;
#else
using nint = System.Int64;
#endif
namespace GitHub_23199
{
public class Program
{
[MethodImpl(MethodImplOptions.NoInlining)]
static Object TestCrossgenedReturnWith2PointersStruct()
{
ProcessStartInfo pi = new ProcessStartInfo();
// pi.Environment calls crossgened HashtableEnumerator::get_Entry returning struct that we need.
Console.WriteLine(pi.Environment.Count);
return pi;
}
struct TwoPointers
{
public Object a;
public Object b;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static TwoPointers GetTwoPointersStruct()
{
var a = new TwoPointers();
a.a = new String("TestTwoPointers");
a.b = new string("Passed");
return a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static Object TestTwoPointers()
{
var a = GetTwoPointersStruct(); // Report both.
Console.WriteLine(a.a + " " + a.b);
return a;
}
struct OnePointer
{
public Object a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static TwoPointers GetOnePointer()
{
var a = new TwoPointers();
a.a = new String("TestOnePointer Passed");
return a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static Object TestOnePointer()
{
var a = GetOnePointer(); // Report one.
Console.WriteLine(a.a);
return a;
}
struct FirstPointer
{
public Object a;
public nint b;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static FirstPointer GetFirstPointer()
{
var a = new FirstPointer();
a.a = new String("TestFirstPointer Passed");
a.b = 100;
return a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static Object TestFirstPointer()
{
var a = GetFirstPointer(); // Report the first field, do not report the second.
Console.WriteLine(a.a);
return a;
}
struct SecondPointer
{
public nint a;
public Object b;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static SecondPointer GetSecondPointer()
{
var a = new SecondPointer();
a.a = 100;
a.b = new String("TestSecondPointer Passed");
return a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static Object TestSecondPointer()
{
var a = GetSecondPointer(); // Report the second field, do not report the first.
Console.WriteLine(a.b);
return a;
}
struct NoPointer1
{
public nint a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static NoPointer1 GetNoPointer1()
{
var a = new NoPointer1();
a.a = 100;
return a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static Object TestNoPointer1()
{
var a = GetNoPointer1(); // Do not report anything.
Console.WriteLine("TestNoPointer1 Passed");
return a;
}
struct NoPointer2
{
public nint a;
public nint b;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static NoPointer2 GetNoPointer2()
{
var a = new NoPointer2();
a.a = 100;
a.b = 100;
return a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static Object TestNoPointer2()
{
NoPointer2 a = GetNoPointer2(); // Do not report anything.
Console.WriteLine("TestNoPointer2 Passed");
return a;
}
struct ThirdPointer
{
public nint a;
public nint b;
public Object c;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static ThirdPointer GetThirdPointer()
{
var a = new ThirdPointer();
a.a = 100;
a.b = 100;
a.c = new String("TestThirdPointer Passed");
return a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static Object TestThirdPointer()
{
ThirdPointer a = GetThirdPointer(); // Do not return in registers.
Console.WriteLine(a.c);
return a;
}
static int Main(string[] args)
{
TestCrossgenedReturnWith2PointersStruct();
TestTwoPointers();
TestOnePointer();
TestFirstPointer();
TestSecondPointer();
TestNoPointer1();
TestNoPointer2();
TestThirdPointer();
return 100;
}
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Menu.Models;
using YesSql;
namespace OrchardCore.Menu.Controllers
{
public class AdminController : Controller
{
private readonly IContentManager _contentManager;
private readonly IAuthorizationService _authorizationService;
private readonly IContentItemDisplayManager _contentItemDisplayManager;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly ISession _session;
private readonly INotifier _notifier;
private readonly IHtmlLocalizer H;
private readonly IUpdateModelAccessor _updateModelAccessor;
public AdminController(
ISession session,
IContentManager contentManager,
IAuthorizationService authorizationService,
IContentItemDisplayManager contentItemDisplayManager,
IContentDefinitionManager contentDefinitionManager,
INotifier notifier,
IHtmlLocalizer<AdminController> localizer,
IUpdateModelAccessor updateModelAccessor)
{
_contentManager = contentManager;
_authorizationService = authorizationService;
_contentItemDisplayManager = contentItemDisplayManager;
_contentDefinitionManager = contentDefinitionManager;
_session = session;
_notifier = notifier;
_updateModelAccessor = updateModelAccessor;
H = localizer;
}
public async Task<IActionResult> Create(string id, string menuContentItemId, string menuItemId)
{
if (String.IsNullOrWhiteSpace(id))
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu))
{
return Forbid();
}
var contentItem = await _contentManager.NewAsync(id);
dynamic model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true);
model.MenuContentItemId = menuContentItemId;
model.MenuItemId = menuItemId;
return View(model);
}
[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> CreatePost(string id, string menuContentItemId, string menuItemId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu))
{
return Forbid();
}
ContentItem menu;
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Menu");
if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable)
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest);
}
else
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.DraftRequired);
}
if (menu == null)
{
return NotFound();
}
var contentItem = await _contentManager.NewAsync(id);
var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true);
if (!ModelState.IsValid)
{
return View(model);
}
if (menuItemId == null)
{
// Use the menu as the parent if no target is specified
menu.Alter<MenuItemsListPart>(part => part.MenuItems.Add(contentItem));
}
else
{
// Look for the target menu item in the hierarchy
var parentMenuItem = FindMenuItem(menu.Content, menuItemId);
// Couldn't find targeted menu item
if (parentMenuItem == null)
{
return NotFound();
}
var menuItems = parentMenuItem?.MenuItemsListPart?.MenuItems as JArray;
if (menuItems == null)
{
parentMenuItem["MenuItemsListPart"] = new JObject(
new JProperty("MenuItems", menuItems = new JArray())
);
}
menuItems.Add(JObject.FromObject(contentItem));
}
_session.Save(menu);
return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = menuContentItemId });
}
public async Task<IActionResult> Edit(string menuContentItemId, string menuItemId)
{
var menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest);
if (menu == null)
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu, menu))
{
return Forbid();
}
// Look for the target menu item in the hierarchy
JObject menuItem = FindMenuItem(menu.Content, menuItemId);
// Couldn't find targeted menu item
if (menuItem == null)
{
return NotFound();
}
var contentItem = menuItem.ToObject<ContentItem>();
dynamic model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, false);
model.MenuContentItemId = menuContentItemId;
model.MenuItemId = menuItemId;
return View(model);
}
[HttpPost]
[ActionName("Edit")]
public async Task<IActionResult> EditPost(string menuContentItemId, string menuItemId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu))
{
return Forbid();
}
ContentItem menu;
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Menu");
if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable)
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest);
}
else
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.DraftRequired);
}
if (menu == null)
{
return NotFound();
}
// Look for the target menu item in the hierarchy
JObject menuItem = FindMenuItem(menu.Content, menuItemId);
// Couldn't find targeted menu item
if (menuItem == null)
{
return NotFound();
}
var contentItem = menuItem.ToObject<ContentItem>();
var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, false);
if (!ModelState.IsValid)
{
return View(model);
}
menuItem.Merge(contentItem.Content, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Replace,
MergeNullValueHandling = MergeNullValueHandling.Merge
});
_session.Save(menu);
return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = menuContentItemId });
}
[HttpPost]
public async Task<IActionResult> Delete(string menuContentItemId, string menuItemId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu))
{
return Forbid();
}
ContentItem menu;
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Menu");
if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable)
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest);
}
else
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.DraftRequired);
}
if (menu == null)
{
return NotFound();
}
// Look for the target menu item in the hierarchy
var menuItem = FindMenuItem(menu.Content, menuItemId);
// Couldn't find targeted menu item
if (menuItem == null)
{
return NotFound();
}
menuItem.Remove();
_session.Save(menu);
_notifier.Success(H["Menu item deleted successfully"]);
return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = menuContentItemId });
}
private JObject FindMenuItem(JObject contentItem, string menuItemId)
{
if (contentItem["ContentItemId"]?.Value<string>() == menuItemId)
{
return contentItem;
}
if (contentItem.GetValue("MenuItemsListPart") == null)
{
return null;
}
var menuItems = (JArray)contentItem["MenuItemsListPart"]["MenuItems"];
JObject result;
foreach (JObject menuItem in menuItems)
{
// Search in inner menu items
result = FindMenuItem(menuItem, menuItemId);
if (result != null)
{
return result;
}
}
return null;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using NUnit.Framework;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// AssertionHelper is an optional base class for user tests,
/// allowing the use of shorter names for constraints and
/// asserts and avoiding conflict with the definition of
/// <see cref="Is"/>, from which it inherits much of its
/// behavior, in certain mock object frameworks.
/// </summary>
public class AssertionHelper : ConstraintFactory
{
#region Assert
//private Assertions assert = new Assertions();
//public virtual Assertions Assert
//{
// get { return assert; }
//}
#endregion
#region Expect
#region Object
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure. Works
/// identically to <see cref="NUnit.Framework.Assert.That(object, IResolveConstraint)"/>
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
public void Expect(object actual, IResolveConstraint constraint)
{
Assert.That(actual, constraint, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure. Works
/// identically to <see cref="NUnit.Framework.Assert.That(object, IResolveConstraint, string)"/>
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
public void Expect(object actual, IResolveConstraint constraint, string message)
{
Assert.That(actual, constraint, message, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure. Works
/// identically to <see cref="NUnit.Framework.Assert.That(object, IResolveConstraint, string, object[])"/>
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect(object actual, IResolveConstraint constraint, string message, params object[] args)
{
Assert.That(actual, constraint, message, args);
}
#endregion
#region ActualValueDelegate
#if !NUNITLITE
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
public void Expect(ActualValueDelegate del, IResolveConstraint expr)
{
Assert.That(del, expr.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="message">The message that will be displayed on failure</param>
public void Expect(ActualValueDelegate del, IResolveConstraint expr, string message)
{
Assert.That(del, expr.Resolve(), message, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect(ActualValueDelegate del, IResolveConstraint expr, string message, params object[] args)
{
Assert.That(del, expr, message, args);
}
#endif
#endregion
#region ref Object
#if !NUNITLITE
#if NET_2_0
/// <summary>
/// Apply a constraint to a referenced value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
public void Expect<T>(ref T actual, IResolveConstraint constraint)
{
Assert.That(ref actual, constraint.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to a referenced value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
public void Expect<T>(ref T actual, IResolveConstraint constraint, string message)
{
Assert.That(ref actual, constraint.Resolve(), message, null);
}
/// <summary>
/// Apply a constraint to a referenced value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expression">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect<T>(ref T actual, IResolveConstraint expression, string message, params object[] args)
{
Assert.That(ref actual, expression, message, args);
}
#else
/// <summary>
/// Apply a constraint to a referenced boolean, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
public void Expect(ref bool actual, IResolveConstraint constraint)
{
Assert.That(ref actual, constraint.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to a referenced value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
public void Expect(ref bool actual, IResolveConstraint constraint, string message)
{
Assert.That(ref actual, constraint.Resolve(), message, null);
}
/// <summary>
/// Apply a constraint to a referenced value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect(ref bool actual, IResolveConstraint expression, string message, params object[] args)
{
Assert.That( ref actual, expression, message, args );
}
#endif
#endif
#endregion
#region Boolean
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>. Works Identically to
/// <see cref="Assert.That(bool, string, object[])"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect(bool condition, string message, params object[] args)
{
Assert.That(condition, Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>. Works Identically to
/// <see cref="Assert.That(bool, string)"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="message">The message to display if the condition is false</param>
public void Expect(bool condition, string message)
{
Assert.That(condition, Is.True, message, null);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>. Works Identically to <see cref="Assert.That(bool)"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
public void Expect(bool condition)
{
Assert.That(condition, Is.True, null, null);
}
#endregion
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A ThrowsConstraint used in the test</param>
public void Expect(TestDelegate code, IResolveConstraint constraint)
{
Assert.That((object)code, constraint);
}
#endregion
#region Map
#if !NUNITLITE
/// <summary>
/// Returns a ListMapper based on a collection.
/// </summary>
/// <param name="original">The original collection</param>
/// <returns></returns>
public ListMapper Map( ICollection original )
{
return new ListMapper( original );
}
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Content.Server.Chat.Managers;
using Content.Server.Database;
using Content.Server.Players;
using Content.Shared.Administration;
using Content.Shared.CCVar;
using Robust.Server.Console;
using Robust.Server.Player;
using Robust.Shared.Configuration;
using Robust.Shared.Console;
using Robust.Shared.ContentPack;
using Robust.Shared.Enums;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Network;
using Robust.Shared.Utility;
using YamlDotNet.RepresentationModel;
namespace Content.Server.Administration.Managers
{
public sealed class AdminManager : IAdminManager, IPostInjectInit, IConGroupControllerImplementation
{
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IServerDbManager _dbManager = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly IServerNetManager _netMgr = default!;
[Dependency] private readonly IConGroupController _conGroup = default!;
[Dependency] private readonly IResourceManager _res = default!;
[Dependency] private readonly IServerConsoleHost _consoleHost = default!;
[Dependency] private readonly IChatManager _chat = default!;
private readonly Dictionary<IPlayerSession, AdminReg> _admins = new();
private readonly HashSet<NetUserId> _promotedPlayers = new();
public event Action<AdminPermsChangedEventArgs>? OnPermsChanged;
public IEnumerable<IPlayerSession> ActiveAdmins => _admins
.Where(p => p.Value.Data.Active)
.Select(p => p.Key);
public IEnumerable<IPlayerSession> AllAdmins => _admins.Select(p => p.Key);
// If a command isn't in this list it's server-console only.
// if a command is in but the flags value is null it's available to everybody.
private readonly HashSet<string> _anyCommands = new();
private readonly Dictionary<string, AdminFlags[]> _adminCommands = new();
public bool IsAdmin(IPlayerSession session, bool includeDeAdmin = false)
{
return GetAdminData(session, includeDeAdmin) != null;
}
public AdminData? GetAdminData(IPlayerSession session, bool includeDeAdmin = false)
{
if (_admins.TryGetValue(session, out var reg) && (reg.Data.Active || includeDeAdmin))
{
return reg.Data;
}
return null;
}
public void DeAdmin(IPlayerSession session)
{
if (!_admins.TryGetValue(session, out var reg))
{
throw new ArgumentException($"Player {session} is not an admin");
}
if (!reg.Data.Active)
{
return;
}
_chat.SendAdminAnnouncement(Loc.GetString("admin-manager-self-de-admin-message", ("exAdminName", session.Name)));
_chat.DispatchServerMessage(session, Loc.GetString("admin-manager-became-normal-player-message"));
var plyData = session.ContentData()!;
plyData.ExplicitlyDeadminned = true;
reg.Data.Active = false;
SendPermsChangedEvent(session);
UpdateAdminStatus(session);
}
public void ReAdmin(IPlayerSession session)
{
if (!_admins.TryGetValue(session, out var reg))
{
throw new ArgumentException($"Player {session} is not an admin");
}
_chat.DispatchServerMessage(session, Loc.GetString("admin-manager-became-admin-message"));
var plyData = session.ContentData()!;
plyData.ExplicitlyDeadminned = false;
reg.Data.Active = true;
_chat.SendAdminAnnouncement(Loc.GetString("admin-manager-self-re-admin-message", ("newAdminName", session.Name)));
SendPermsChangedEvent(session);
UpdateAdminStatus(session);
}
public async void ReloadAdmin(IPlayerSession player)
{
var data = await LoadAdminData(player);
var curAdmin = _admins.GetValueOrDefault(player);
if (data == null && curAdmin == null)
{
// Wasn't admin before or after.
return;
}
if (data == null)
{
// No longer admin.
_admins.Remove(player);
_chat.DispatchServerMessage(player, Loc.GetString("admin-manager-no-longer-admin-message"));
}
else
{
var (aData, rankId, special) = data.Value;
if (curAdmin == null)
{
// Now an admin.
var reg = new AdminReg(player, aData)
{
IsSpecialLogin = special,
RankId = rankId
};
_admins.Add(player, reg);
_chat.DispatchServerMessage(player, Loc.GetString("admin-manager-became-admin-message"));
}
else
{
// Perms changed.
curAdmin.IsSpecialLogin = special;
curAdmin.RankId = rankId;
curAdmin.Data = aData;
}
if (!player.ContentData()!.ExplicitlyDeadminned)
{
aData.Active = true;
_chat.DispatchServerMessage(player, Loc.GetString("admin-manager-admin-permissions-updated-message"));
}
}
SendPermsChangedEvent(player);
UpdateAdminStatus(player);
}
public void ReloadAdminsWithRank(int rankId)
{
foreach (var dat in _admins.Values.Where(p => p.RankId == rankId).ToArray())
{
ReloadAdmin(dat.Session);
}
}
public void Initialize()
{
_netMgr.RegisterNetMessage<MsgUpdateAdminStatus>();
// Cache permissions for loaded console commands with the requisite attributes.
foreach (var (cmdName, cmd) in _consoleHost.RegisteredCommands)
{
var (isAvail, flagsReq) = GetRequiredFlag(cmd);
if (!isAvail)
{
continue;
}
if (flagsReq.Length != 0)
{
_adminCommands.Add(cmdName, flagsReq);
}
else
{
_anyCommands.Add(cmdName);
}
}
// Load flags for engine commands, since those don't have the attributes.
if (_res.TryContentFileRead(new ResourcePath("/engineCommandPerms.yml"), out var efs))
{
LoadPermissionsFromStream(efs);
}
// Load flags for client-only commands, those don't have the flag attributes, only "AnyCommand".
if (_res.TryContentFileRead(new ResourcePath("/clientCommandPerms.yml"), out var cfs))
{
LoadPermissionsFromStream(cfs);
}
}
private void LoadPermissionsFromStream(Stream fs)
{
using var reader = new StreamReader(fs, EncodingHelpers.UTF8);
var yStream = new YamlStream();
yStream.Load(reader);
var root = (YamlSequenceNode) yStream.Documents[0].RootNode;
foreach (var child in root)
{
var map = (YamlMappingNode) child;
var commands = map.GetNode<YamlSequenceNode>("Commands").Select(p => p.AsString());
if (map.TryGetNode("Flags", out var flagsNode))
{
var flagNames = flagsNode.AsString().Split(",", StringSplitOptions.RemoveEmptyEntries);
var flags = AdminFlagsHelper.NamesToFlags(flagNames);
foreach (var cmd in commands)
{
if (!_adminCommands.TryGetValue(cmd, out var exFlags))
{
_adminCommands.Add(cmd, new[] {flags});
}
else
{
var newArr = new AdminFlags[exFlags.Length + 1];
exFlags.CopyTo(newArr, 0);
exFlags[^1] = flags;
_adminCommands[cmd] = newArr;
}
}
}
else
{
_anyCommands.UnionWith(commands);
}
}
}
public void PromoteHost(IPlayerSession player)
{
_promotedPlayers.Add(player.UserId);
ReloadAdmin(player);
}
void IPostInjectInit.PostInject()
{
_playerManager.PlayerStatusChanged += PlayerStatusChanged;
_conGroup.Implementation = this;
}
// NOTE: Also sends commands list for non admins..
private void UpdateAdminStatus(IPlayerSession session)
{
var msg = _netMgr.CreateNetMessage<MsgUpdateAdminStatus>();
var commands = new List<string>(_anyCommands);
if (_admins.TryGetValue(session, out var adminData))
{
msg.Admin = adminData.Data;
commands.AddRange(_adminCommands
.Where(p => p.Value.Any(f => adminData.Data.HasFlag(f)))
.Select(p => p.Key));
}
msg.AvailableCommands = commands.ToArray();
_netMgr.ServerSendMessage(msg, session.ConnectedClient);
}
private void PlayerStatusChanged(object? sender, SessionStatusEventArgs e)
{
if (e.NewStatus == SessionStatus.Connected)
{
// Run this so that available commands list gets sent.
UpdateAdminStatus(e.Session);
}
else if (e.NewStatus == SessionStatus.InGame)
{
LoginAdminMaybe(e.Session);
}
else if (e.NewStatus == SessionStatus.Disconnected)
{
if (_admins.Remove(e.Session) && _cfg.GetCVar(CCVars.AdminAnnounceLogout))
{
_chat.SendAdminAnnouncement(Loc.GetString("admin-manager-admin-logout-message", ("name", e.Session.Name)));
}
}
}
private async void LoginAdminMaybe(IPlayerSession session)
{
var adminDat = await LoadAdminData(session);
if (adminDat == null)
{
// Not an admin.
return;
}
var (dat, rankId, specialLogin) = adminDat.Value;
var reg = new AdminReg(session, dat)
{
IsSpecialLogin = specialLogin,
RankId = rankId
};
_admins.Add(session, reg);
if (!session.ContentData()!.ExplicitlyDeadminned)
{
reg.Data.Active = true;
if (_cfg.GetCVar(CCVars.AdminAnnounceLogin))
{
_chat.SendAdminAnnouncement(Loc.GetString("admin-manager-admin-login-message", ("name", session.Name)));
}
SendPermsChangedEvent(session);
}
UpdateAdminStatus(session);
}
private async Task<(AdminData dat, int? rankId, bool specialLogin)?> LoadAdminData(IPlayerSession session)
{
if (IsLocal(session) && _cfg.GetCVar(CCVars.ConsoleLoginLocal) || _promotedPlayers.Contains(session.UserId))
{
var data = new AdminData
{
Title = Loc.GetString("admin-manager-admin-data-host-title"),
Flags = AdminFlagsHelper.Everything,
};
return (data, null, true);
}
else
{
var dbData = await _dbManager.GetAdminDataForAsync(session.UserId);
if (dbData == null)
{
// Not an admin!
return null;
}
var flags = AdminFlags.None;
if (dbData.AdminRank != null)
{
flags = AdminFlagsHelper.NamesToFlags(dbData.AdminRank.Flags.Select(p => p.Flag));
}
foreach (var dbFlag in dbData.Flags)
{
var flag = AdminFlagsHelper.NameToFlag(dbFlag.Flag);
if (dbFlag.Negative)
{
flags &= ~flag;
}
else
{
flags |= flag;
}
}
var data = new AdminData
{
Flags = flags
};
if (dbData.Title != null)
{
data.Title = dbData.Title;
}
else if (dbData.AdminRank != null)
{
data.Title = dbData.AdminRank.Name;
}
return (data, dbData.AdminRankId, false);
}
}
private static bool IsLocal(IPlayerSession player)
{
var ep = player.ConnectedClient.RemoteEndPoint;
var addr = ep.Address;
if (addr.IsIPv4MappedToIPv6)
{
addr = addr.MapToIPv4();
}
return Equals(addr, System.Net.IPAddress.Loopback) || Equals(addr, System.Net.IPAddress.IPv6Loopback);
}
public bool CanCommand(IPlayerSession session, string cmdName)
{
if (_anyCommands.Contains(cmdName))
{
// Anybody can use this command.
return true;
}
if (!_adminCommands.TryGetValue(cmdName, out var flagsReq))
{
// Server-console only.
return false;
}
var data = GetAdminData(session);
if (data == null)
{
// Player isn't an admin.
return false;
}
foreach (var flagReq in flagsReq)
{
if (data.HasFlag(flagReq))
{
return true;
}
}
return false;
}
private static (bool isAvail, AdminFlags[] flagsReq) GetRequiredFlag(IConsoleCommand cmd)
{
MemberInfo type = cmd.GetType();
if (cmd is ConsoleHost.RegisteredCommand registered)
{
type = registered.Callback.Method;
}
if (Attribute.IsDefined(type, typeof(AnyCommandAttribute)))
{
// Available to everybody.
return (true, Array.Empty<AdminFlags>());
}
var attribs = type.GetCustomAttributes(typeof(AdminCommandAttribute))
.Cast<AdminCommandAttribute>()
.Select(p => p.Flags)
.ToArray();
// If attribs.length == 0 then no access attribute is specified,
// and this is a server-only command.
return (attribs.Length != 0, attribs);
}
public bool CanViewVar(IPlayerSession session)
{
return CanCommand(session, "vv");
}
public bool CanAdminPlace(IPlayerSession session)
{
return GetAdminData(session)?.CanAdminPlace() ?? false;
}
public bool CanScript(IPlayerSession session)
{
return GetAdminData(session)?.CanScript() ?? false;
}
public bool CanAdminMenu(IPlayerSession session)
{
return GetAdminData(session)?.CanAdminMenu() ?? false;
}
public bool CanAdminReloadPrototypes(IPlayerSession session)
{
return GetAdminData(session)?.CanAdminReloadPrototypes() ?? false;
}
private void SendPermsChangedEvent(IPlayerSession session)
{
var flags = GetAdminData(session)?.Flags;
OnPermsChanged?.Invoke(new AdminPermsChangedEventArgs(session, flags));
}
private sealed class AdminReg
{
public readonly IPlayerSession Session;
public AdminData Data;
public int? RankId;
// Such as console.loginlocal or promotehost
public bool IsSpecialLogin;
public AdminReg(IPlayerSession session, AdminData data)
{
Data = data;
Session = session;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataGridRow.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Runtime.Remoting;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Collections;
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow"]/*' />
/// <devdoc>
/// <para>Encapsulates the painting logic for a new row added to a
/// <see cref='System.Windows.Forms.DataGrid'/>
/// control.</para>
/// </devdoc>
internal abstract class DataGridRow : MarshalByRefObject {
internal protected int number; // row number
private bool selected;
private int height;
// protected DataRow dataRow;
private IntPtr tooltipID = new IntPtr(-1);
private string tooltip = String.Empty;
AccessibleObject accessibleObject;
// for accessibility...
//
// internal DataGrid dataGrid;
// will need this for the painting information ( row header color )
//
protected DataGridTableStyle dgTable;
// we will be mapping only the black color to
// the HeaderForeColor
//
private static ColorMap[] colorMap = new ColorMap[] {new ColorMap()};
// bitmaps
//
private static Bitmap rightArrow = null;
private static Bitmap leftArrow = null;
private static Bitmap errorBmp = null;
private static Bitmap pencilBmp = null;
private static Bitmap starBmp = null;
protected const int xOffset = 3;
protected const int yOffset = 2;
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.DataGridRow"]/*' />
/// <devdoc>
/// <para>Initializes a new instance of a <see cref='System.Windows.Forms.DataGridRow'/> . </para>
/// </devdoc>
[
SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // This class and its derived classes are internal.
// So this is not a security back door.
]
public DataGridRow(DataGrid dataGrid, DataGridTableStyle dgTable, int rowNumber) {
if (dataGrid == null || dgTable.DataGrid == null)
throw new ArgumentNullException("dataGrid");
if (rowNumber < 0)
throw new ArgumentException(SR.GetString(SR.DataGridRowRowNumber), "rowNumber");
// this.dataGrid = dataGrid;
this.number = rowNumber;
// map the black color in the pictures to the DataGrid's HeaderForeColor
//
colorMap[0].OldColor = Color.Black;
colorMap[0].NewColor = dgTable.HeaderForeColor;
this.dgTable = dgTable;
height = MinimumRowHeight(dgTable);
}
public AccessibleObject AccessibleObject {
get {
if (accessibleObject == null) {
accessibleObject = CreateAccessibleObject();
}
return accessibleObject;
}
}
protected virtual AccessibleObject CreateAccessibleObject() {
return new DataGridRowAccessibleObject(this);
}
internal protected virtual int MinimumRowHeight(DataGridTableStyle dgTable) {
return MinimumRowHeight(dgTable.GridColumnStyles);
}
internal protected virtual int MinimumRowHeight(GridColumnStylesCollection columns) {
int h = dgTable.IsDefault ? this.DataGrid.PreferredRowHeight : dgTable.PreferredRowHeight;
try {
if (this.dgTable.DataGrid.DataSource != null) {
int nCols = columns.Count;
for (int i = 0; i < nCols; ++i) {
// if (columns[i].Visible && columns[i].PropertyDescriptor != null)
if (columns[i].PropertyDescriptor != null)
h = Math.Max(h, columns[i].GetMinimumHeight());
}
}
}
catch {
}
return h;
}
// =------------------------------------------------------------------
// = Properties
// =------------------------------------------------------------------
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.DataGrid"]/*' />
/// <devdoc>
/// <para>Gets the <see cref='System.Windows.Forms.DataGrid'/> control the row belongs to.</para>
/// </devdoc>
public DataGrid DataGrid {
get {
return this.dgTable.DataGrid;
}
}
internal DataGridTableStyle DataGridTableStyle {
get {
return this.dgTable;
}
set {
dgTable = value;
}
}
/*
public DataGridTable DataGridTable {
get {
return dgTable;
}
}
*/
/*
public DataRow DataRow {
get {
return dataRow;
}
}
*/
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.Height"]/*' />
/// <devdoc>
/// <para>Gets or sets the height of the row.</para>
/// </devdoc>
public virtual int Height {
get {
return height;
}
set {
// the height of the row should be at least 0.
// this way, if the row has a relationship list and the user resizes the row such that
// the new height does not accomodate the height of the relationship list
// the row will at least show the relationship list ( and not paint on the portion of the row above this one )
height = Math.Max(0, value);
// when we resize the row, or when we set the PreferredRowHeigth on the
// DataGridTableStyle, we change the height of the Row, which will cause to invalidate,
// then the grid itself will do another invalidate call.
this.dgTable.DataGrid.OnRowHeightChanged(this);
}
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.RowNumber"]/*' />
/// <devdoc>
/// <para>Gets the row's number.</para>
/// </devdoc>
public int RowNumber {
get {
return this.number;
}
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.Selected"]/*' />
/// <devdoc>
/// <para>Gets or sets a value indicating whether the row is selected.</para>
/// </devdoc>
public virtual bool Selected {
get {
return selected;
}
set {
selected = value;
InvalidateRow();
}
}
// =------------------------------------------------------------------
// = Methods
// =------------------------------------------------------------------
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.GetBitmap"]/*' />
/// <devdoc>
/// <para>Gets the bitmap associated with the row.</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
protected Bitmap GetBitmap(string bitmapName) {
Bitmap b = null;
try {
b = new Bitmap(typeof(DataGridCaption), bitmapName);
b.MakeTransparent();
}
catch (Exception e) {
Debug.Fail("Failed to load bitmap: " + bitmapName, e.ToString());
throw e;
}
return b;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.GetCellBounds"]/*' />
/// <devdoc>
/// <para>When overridden in a derived class, gets the <see cref='System.Drawing.Rectangle'/>
/// where a cell's contents gets painted.</para>
/// </devdoc>
public virtual Rectangle GetCellBounds(int col) {
int firstVisibleCol = this.dgTable.DataGrid.FirstVisibleColumn;
int cx = 0;
Rectangle cellBounds = new Rectangle();
GridColumnStylesCollection columns = this.dgTable.GridColumnStyles;
if (columns != null) {
for (int i = firstVisibleCol; i < col; i++)
if (columns[i].PropertyDescriptor != null)
cx += columns[i].Width;
int borderWidth = this.dgTable.GridLineWidth;
cellBounds = new Rectangle(cx,
0,
columns[col].Width - borderWidth,
Height - borderWidth);
}
return cellBounds;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.GetNonScrollableArea"]/*' />
/// <devdoc>
/// <para>When overridden in a derived class, gets the <see cref='System.Drawing.Rectangle'/> of the non-scrollable area of
/// the row.</para>
/// </devdoc>
public virtual Rectangle GetNonScrollableArea() {
return Rectangle.Empty;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.GetStarBitmap"]/*' />
/// <devdoc>
/// <para>Gets or sets the bitmap displayed in the row header of a new row.</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
protected Bitmap GetStarBitmap() {
if (starBmp == null)
starBmp = GetBitmap("DataGridRow.star.bmp");
return starBmp;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.GetPencilBitmap"]/*' />
/// <devdoc>
/// <para>Gets or sets the bitmap displayed in the row header that indicates a row can
/// be edited.</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
protected Bitmap GetPencilBitmap() {
if (pencilBmp == null)
pencilBmp = GetBitmap("DataGridRow.pencil.bmp");
return pencilBmp;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.GetErrorBitmap"]/*' />
/// <devdoc>
/// <para>Gets or sets the bitmap displayed on a row with an error.</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
protected Bitmap GetErrorBitmap() {
if (errorBmp == null)
errorBmp = GetBitmap("DataGridRow.error.bmp");
errorBmp.MakeTransparent();
return errorBmp;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
protected Bitmap GetLeftArrowBitmap() {
if (leftArrow == null)
leftArrow = GetBitmap("DataGridRow.left.bmp");
return leftArrow;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
protected Bitmap GetRightArrowBitmap() {
if (rightArrow == null)
rightArrow = GetBitmap("DataGridRow.right.bmp");
return rightArrow;
}
public virtual void InvalidateRow() {
this.dgTable.DataGrid.InvalidateRow(number);
}
public virtual void InvalidateRowRect(Rectangle r) {
this.dgTable.DataGrid.InvalidateRowRect(number, r);
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.OnEdit"]/*' />
/// <devdoc>
/// <para>When overridden in a derived class, notifies the grid that an edit will
/// occur.</para>
/// </devdoc>
public virtual void OnEdit() {
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.OnKeyPress"]/*' />
/// <devdoc>
/// <para>When overridden in a derived class, called by the <see cref='System.Windows.Forms.DataGrid'/> control when a key press occurs on a row with focus.</para>
/// </devdoc>
public virtual bool OnKeyPress(Keys keyData) {
int currentColIndex = this.dgTable.DataGrid.CurrentCell.ColumnNumber;
GridColumnStylesCollection columns = this.dgTable.GridColumnStyles;
if (columns != null && currentColIndex >= 0 && currentColIndex < columns.Count) {
DataGridColumnStyle currentColumn = columns[currentColIndex];
if (currentColumn.KeyPress(this.RowNumber, keyData)) {
return true;
}
}
return false;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.OnMouseDown"]/*' />
/// <devdoc>
/// <para> Called by the <see cref='System.Windows.Forms.DataGrid'/> when a click occurs in the row's client area
/// specifed by the x and y coordinates and the specified <see cref='System.Drawing.Rectangle'/>
/// .</para>
/// </devdoc>
public virtual bool OnMouseDown(int x, int y, Rectangle rowHeaders)
{
return OnMouseDown(x,y,rowHeaders, false);
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.OnMouseDown1"]/*' />
/// <devdoc>
/// <para>When overridden in a derived class, is called by the <see cref='System.Windows.Forms.DataGrid'/> when a click occurs
/// in the row's
/// client area, specified by x and y coordinates.</para>
/// </devdoc>
public virtual bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignToRight) {
// if we call base.OnMouseDown, then the row could not use this
// mouse click at all. in that case LoseChildFocus, so the edit control
// will become visible
LoseChildFocus(rowHeaders, alignToRight);
// we did not use this click at all.
return false;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.OnMouseMove"]/*' />
/// <devdoc>
/// </devdoc>
public virtual bool OnMouseMove(int x, int y, Rectangle rowHeaders) {
return false;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.OnMouseMove1"]/*' />
/// <devdoc>
/// <para>When overridden in a derived class, is called by the <see cref='System.Windows.Forms.DataGrid'/> when
/// the mouse moves within the row's client area.</para>
/// </devdoc>
public virtual bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignToRight) {
return false;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.OnMouseLeft"]/*' />
/// <devdoc>
/// </devdoc>
public virtual void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) {
}
public virtual void OnMouseLeft() {
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.OnRowEnter"]/*' />
/// <devdoc>
/// <para>When overridden in a derived class, causes the RowEnter event to occur.</para>
/// </devdoc>
public virtual void OnRowEnter() {}
public virtual void OnRowLeave() {}
// processes the Tab Key
// returns TRUE if the TAB key is processed
internal abstract bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool alignToRight);
// tells the dataGridRow that it lost the focus
internal abstract void LoseChildFocus(Rectangle rowHeaders, bool alignToRight);
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.Paint"]/*' />
/// <devdoc>
/// Paints the row.
/// </devdoc>
public abstract int Paint(Graphics g,
Rectangle dataBounds,
Rectangle rowBounds,
int firstVisibleColumn,
int numVisibleColumns);
public abstract int Paint(Graphics g,
Rectangle dataBounds,
Rectangle rowBounds,
int firstVisibleColumn,
int numVisibleColumns,
bool alignToRight);
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.PaintBottomBorder"]/*' />
/// <devdoc>
/// Draws a border on the bottom DataGrid.GridLineWidth pixels
/// of the bounding rectangle passed in.
/// </devdoc>
protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataWidth)
{
PaintBottomBorder(g, bounds, dataWidth, this.dgTable.GridLineWidth, false);
}
protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataWidth, int borderWidth, bool alignToRight) {
// paint bottom border
Rectangle bottomBorder = new Rectangle(alignToRight ? bounds.Right - dataWidth : bounds.X,
bounds.Bottom - borderWidth,
dataWidth,
borderWidth);
g.FillRectangle(this.dgTable.IsDefault ? this.DataGrid.GridLineBrush : this.dgTable.GridLineBrush, bottomBorder);
// paint any exposed region to the right
if (dataWidth < bounds.Width) {
g.FillRectangle(this.dgTable.DataGrid.BackgroundBrush,
alignToRight ? bounds.X: bottomBorder.Right,
bottomBorder.Y,
bounds.Width - bottomBorder.Width,
borderWidth);
}
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.PaintData"]/*' />
/// <devdoc>
/// Paints the row.
/// </devdoc>
public virtual int PaintData(Graphics g,
Rectangle bounds,
int firstVisibleColumn,
int columnCount)
{
return PaintData(g, bounds, firstVisibleColumn, columnCount, false);
}
public virtual int PaintData(Graphics g,
Rectangle bounds,
int firstVisibleColumn,
int columnCount,
bool alignToRight) {
Debug.WriteLineIf(CompModSwitches.DGRowPaint.TraceVerbose, "Painting DataGridAddNewRow: bounds = " + bounds.ToString());
Rectangle cellBounds = bounds;
int bWidth = this.dgTable.IsDefault ? this.DataGrid.GridLineWidth : this.dgTable.GridLineWidth;
int cx = 0;
DataGridCell current = this.dgTable.DataGrid.CurrentCell;
GridColumnStylesCollection columns = dgTable.GridColumnStyles;
int nCols = columns.Count;
for (int col = firstVisibleColumn; col < nCols; ++col) {
if (cx > bounds.Width)
break;
// if (!columns[col].Visible || columns[col].PropertyDescriptor == null)
if (columns[col].PropertyDescriptor == null || columns[col].Width <= 0)
continue;
cellBounds.Width = columns[col].Width - bWidth;
if (alignToRight)
cellBounds.X = bounds.Right - cx - cellBounds.Width;
else
cellBounds.X = bounds.X + cx;
// Paint the data with the the DataGridColumn
Brush backBr = BackBrushForDataPaint(ref current, columns[col], col);
Brush foreBrush = ForeBrushForDataPaint(ref current, columns[col], col);
PaintCellContents(g,
cellBounds,
columns[col],
backBr,
foreBrush,
alignToRight);
// Paint the border to the right of each cell
if (bWidth > 0) {
g.FillRectangle(this.dgTable.IsDefault ? this.DataGrid.GridLineBrush : this.dgTable.GridLineBrush,
alignToRight ? cellBounds.X - bWidth : cellBounds.Right,
cellBounds.Y,
bWidth,
cellBounds.Height);
}
cx += cellBounds.Width + bWidth;
}
// Paint any exposed area to the right ( or left ) of the data cell area
if (cx < bounds.Width) {
g.FillRectangle(this.dgTable.DataGrid.BackgroundBrush,
alignToRight ? bounds.X : bounds.X + cx,
bounds.Y,
bounds.Width - cx,
bounds.Height);
}
return cx;
}
protected virtual void PaintCellContents(Graphics g, Rectangle cellBounds, DataGridColumnStyle column,
Brush backBr, Brush foreBrush)
{
PaintCellContents(g, cellBounds, column, backBr, foreBrush, false);
}
protected virtual void PaintCellContents(Graphics g, Rectangle cellBounds, DataGridColumnStyle column,
Brush backBr, Brush foreBrush, bool alignToRight) {
g.FillRectangle(backBr, cellBounds);
}
//
// This function will do the following: if paintIcon is set to true, then
// will draw the image on the RowHeader. if paintIcon is set to false,
// then this function will fill the rectangle on which otherwise will
// have been drawn the image
//
// will return the rectangle that includes the Icon
//
protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon, bool alignToRight, Bitmap bmp) {
return PaintIcon(g, visualBounds, paintIcon, alignToRight, bmp,
this.dgTable.IsDefault ? this.DataGrid.HeaderBackBrush : this.dgTable.HeaderBackBrush);
}
protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon, bool alignToRight, Bitmap bmp, Brush backBrush) {
Size bmpSize = bmp.Size;
Rectangle bmpRect = new Rectangle(alignToRight ? visualBounds.Right - xOffset - bmpSize.Width : visualBounds.X + xOffset,
visualBounds.Y + yOffset,
bmpSize.Width,
bmpSize.Height);
g.FillRectangle(backBrush, visualBounds);
if (paintIcon)
{
colorMap[0].NewColor = this.dgTable.IsDefault ? this.DataGrid.HeaderForeColor : this.dgTable.HeaderForeColor;
colorMap[0].OldColor = Color.Black;
ImageAttributes attr = new ImageAttributes();
attr.SetRemapTable(colorMap, ColorAdjustType.Bitmap);
g.DrawImage(bmp, bmpRect, 0, 0, bmpRect.Width, bmpRect.Height,GraphicsUnit.Pixel, attr);
// g.DrawImage(bmp, bmpRect);
attr.Dispose();
}
return bmpRect;
}
// assume that the row is not aligned to right, and that the row is not dirty
public virtual void PaintHeader(Graphics g, Rectangle visualBounds) {
PaintHeader(g, visualBounds, false);
}
// assume that the row is not dirty
public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignToRight) {
PaintHeader(g,visualBounds, alignToRight, false);
}
public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignToRight, bool rowIsDirty) {
Rectangle bounds = visualBounds;
// paint the first part of the row header: the Arror or Pencil/Star
Bitmap bmp;
if (this is DataGridAddNewRow)
{
bmp = GetStarBitmap();
lock (bmp) {
bounds.X += PaintIcon(g, bounds, true, alignToRight, bmp).Width + xOffset;
}
return;
}
else if (rowIsDirty)
{
bmp = GetPencilBitmap();
lock (bmp) {
bounds.X += PaintIcon(g, bounds, RowNumber == this.DataGrid.CurrentCell.RowNumber, alignToRight, bmp).Width + xOffset;
}
}
else
{
bmp = alignToRight ? GetLeftArrowBitmap() : GetRightArrowBitmap();
lock (bmp) {
bounds.X += PaintIcon(g, bounds, RowNumber == this.DataGrid.CurrentCell.RowNumber, alignToRight, bmp).Width + xOffset;
}
}
// Paint the error icon
//
object errorInfo = DataGrid.ListManager[this.number];
if (!(errorInfo is IDataErrorInfo))
return;
string errString = ((IDataErrorInfo) errorInfo).Error;
if (errString == null)
errString = String.Empty;
if (tooltip != errString) {
if (!String.IsNullOrEmpty(tooltip)) {
DataGrid.ToolTipProvider.RemoveToolTip(tooltipID);
tooltip = String.Empty;
tooltipID = new IntPtr(-1);
}
}
if (String.IsNullOrEmpty(errString))
return;
// we now have an error string: paint the errorIcon and add the tooltip
Rectangle errRect;
bmp = GetErrorBitmap();
lock (bmp) {
errRect = PaintIcon(g, bounds, true, alignToRight, bmp);
}
bounds.X += errRect.Width + xOffset;
tooltip = errString;
tooltipID = (IntPtr)((int)DataGrid.ToolTipId++);
DataGrid.ToolTipProvider.AddToolTip(tooltip, tooltipID, errRect);
}
protected Brush GetBackBrush() {
Brush br = this.dgTable.IsDefault ? DataGrid.BackBrush : this.dgTable.BackBrush;
if (DataGrid.LedgerStyle && (RowNumber % 2 == 1)) {
br = this.dgTable.IsDefault ? this.DataGrid.AlternatingBackBrush : this.dgTable.AlternatingBackBrush;
}
return br;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.BackBrushForDataPaint"]/*' />
/// <devdoc>
/// Returns the BackColor and TextColor that the Graphics object should use
/// for the appropriate values for a given row and column when painting the data.
///
/// </devdoc>
protected Brush BackBrushForDataPaint(ref DataGridCell current, DataGridColumnStyle gridColumn, int column) {
Brush backBr = this.GetBackBrush();
if (Selected) {
backBr = this.dgTable.IsDefault ? this.DataGrid.SelectionBackBrush : this.dgTable.SelectionBackBrush;
}
/*
if (RowNumber == current.RowNumber && column == current.ColumnNumber) {
backBr = grid.CurrentCellBackBrush;
}
*/
return backBr;
}
protected Brush ForeBrushForDataPaint(ref DataGridCell current, DataGridColumnStyle gridColumn, int column) {
// Brush foreBrush = gridColumn.ForeBrush;
Brush foreBrush = this.dgTable.IsDefault ? this.DataGrid.ForeBrush : this.dgTable.ForeBrush;
if (Selected) {
foreBrush = this.dgTable.IsDefault ? this.DataGrid.SelectionForeBrush : this.dgTable.SelectionForeBrush;
}
/*
if (RowNumber == current.RowNumber && column == current.ColumnNumber) {
foreColor = grid.CurrentCellForeColor;
}
*/
return foreBrush;
}
[ComVisible(true)]
protected class DataGridRowAccessibleObject : AccessibleObject {
ArrayList cells;
DataGridRow owner = null;
internal static string CellToDisplayString(DataGrid grid, int row, int column) {
if (column < grid.myGridTable.GridColumnStyles.Count) {
return grid.myGridTable.GridColumnStyles[column].PropertyDescriptor.Converter.ConvertToString(grid[row, column]);
}
else {
return "";
}
}
internal static object DisplayStringToCell(DataGrid grid, int row, int column, string value) {
if (column < grid.myGridTable.GridColumnStyles.Count) {
return grid.myGridTable.GridColumnStyles[column].PropertyDescriptor.Converter.ConvertFromString(value);
}
// ignore...
//
return null;
}
[
SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // This class and its derived classes are internal.
// So this is not a security back door.
]
public DataGridRowAccessibleObject(DataGridRow owner) : base() {
Debug.Assert(owner != null, "DataGridRowAccessibleObject must have a valid owner DataGridRow");
this.owner = owner;
DataGrid grid = DataGrid;
Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, "Create row accessible object");
EnsureChildren();
}
private void EnsureChildren() {
if (cells == null) {
// default size... little extra for relationships...
//
cells = new ArrayList(DataGrid.myGridTable.GridColumnStyles.Count + 2);
AddChildAccessibleObjects(cells);
}
}
protected virtual void AddChildAccessibleObjects(IList children) {
Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, "Create row's accessible children");
Debug.Indent();
GridColumnStylesCollection cols = DataGrid.myGridTable.GridColumnStyles;
int len = cols.Count;
Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, len + " columns present");
for (int i=0; i<len; i++) {
children.Add(CreateCellAccessibleObject(i));
}
Debug.Unindent();
}
protected virtual AccessibleObject CreateCellAccessibleObject(int column) {
return new DataGridCellAccessibleObject(owner, column);
}
public override Rectangle Bounds {
get {
return DataGrid.RectangleToScreen(DataGrid.GetRowBounds(owner));
}
}
public override string Name {
get {
if (owner is DataGridAddNewRow) {
return SR.GetString(SR.AccDGNewRow);
}
else {
return DataGridRowAccessibleObject.CellToDisplayString(DataGrid, owner.RowNumber, 0);
}
}
}
protected DataGridRow Owner {
get {
return owner;
}
}
public override AccessibleObject Parent {
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get {
return DataGrid.AccessibilityObject;
}
}
private DataGrid DataGrid {
get {
return owner.DataGrid;
}
}
public override AccessibleRole Role {
get {
return AccessibleRole.Row;
}
}
public override AccessibleStates State {
get {
AccessibleStates state = AccessibleStates.Selectable | AccessibleStates.Focusable;
// Determine focus
//
if (DataGrid.CurrentCell.RowNumber == owner.RowNumber) {
state |= AccessibleStates.Focused;
}
// Determine selected
//
if (DataGrid.CurrentRowIndex == owner.RowNumber) {
state |= AccessibleStates.Selected;
}
return state;
}
}
public override string Value {
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get {
return Name;
}
}
public override AccessibleObject GetChild(int index) {
if (index < cells.Count) {
return (AccessibleObject)cells[index];
}
return null;
}
public override int GetChildCount() {
return cells.Count;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.DataGridRowAccessibleObject.GetFocused"]/*' />
/// <devdoc>
/// Returns the currently focused child, if any.
/// Returns this if the object itself is focused.
/// </devdoc>
public override AccessibleObject GetFocused() {
if (DataGrid.Focused) {
DataGridCell cell = DataGrid.CurrentCell;
if (cell.RowNumber == owner.RowNumber) {
return (AccessibleObject)cells[cell.ColumnNumber];
}
}
return null;
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.DataGridRowAccessibleObject.Navigate"]/*' />
/// <devdoc>
/// Navigate to the next or previous grid entry.entry.
/// </devdoc>
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override AccessibleObject Navigate(AccessibleNavigation navdir) {
switch (navdir) {
case AccessibleNavigation.Down:
case AccessibleNavigation.Right:
case AccessibleNavigation.Next:
return DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber + 1);
case AccessibleNavigation.Up:
case AccessibleNavigation.Left:
case AccessibleNavigation.Previous:
return DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber - 1);
case AccessibleNavigation.FirstChild:
if (GetChildCount() > 0) {
return GetChild(0);
}
break;
case AccessibleNavigation.LastChild:
if (GetChildCount() > 0) {
return GetChild(GetChildCount() - 1);
}
break;
}
return null;
}
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override void Select(AccessibleSelection flags) {
// Focus the PropertyGridView window
//
if ( (flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) {
DataGrid.Focus();
}
// Select the grid entry
//
if ( (flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) {
DataGrid.CurrentRowIndex = owner.RowNumber;
}
}
}
[ComVisible(true)]
protected class DataGridCellAccessibleObject : AccessibleObject {
DataGridRow owner = null;
int column;
public DataGridCellAccessibleObject(DataGridRow owner, int column) : base() {
Debug.Assert(owner != null, "DataGridColumnAccessibleObject must have a valid owner DataGridRow");
this.owner = owner;
this.column = column;
Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, "Create cell accessible object");
}
public override Rectangle Bounds {
get {
return DataGrid.RectangleToScreen(DataGrid.GetCellBounds(new DataGridCell(owner.RowNumber, column)));
}
}
public override string Name {
get {
return DataGrid.myGridTable.GridColumnStyles[column].HeaderText;
}
}
public override AccessibleObject Parent {
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get {
return owner.AccessibleObject;
}
}
protected DataGrid DataGrid {
get {
return owner.DataGrid;
}
}
public override string DefaultAction {
get {
return SR.GetString(SR.AccDGEdit);
}
}
public override AccessibleRole Role {
get {
return AccessibleRole.Cell;
}
}
public override AccessibleStates State {
get {
AccessibleStates state = AccessibleStates.Selectable | AccessibleStates.Focusable;
// Determine focus
//
if (DataGrid.CurrentCell.RowNumber == owner.RowNumber
&& DataGrid.CurrentCell.ColumnNumber == column) {
if (DataGrid.Focused) {
state |= AccessibleStates.Focused;
}
state |= AccessibleStates.Selected;
}
return state;
}
}
public override string Value {
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get {
if (owner is DataGridAddNewRow) {
return null;
}
else {
return DataGridRowAccessibleObject.CellToDisplayString(DataGrid, owner.RowNumber, column);
}
}
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
set {
if (!(owner is DataGridAddNewRow)) {
object realValue = DataGridRowAccessibleObject.DisplayStringToCell(DataGrid, owner.RowNumber, column, value);
DataGrid[owner.RowNumber, column] = realValue;
}
}
}
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override void DoDefaultAction() {
Select(AccessibleSelection.TakeFocus | AccessibleSelection.TakeSelection);
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.DataGridCellAccessibleObject.GetFocused"]/*' />
/// <devdoc>
/// Returns the currently focused child, if any.
/// Returns this if the object itself is focused.
/// </devdoc>
public override AccessibleObject GetFocused() {
// Datagrid always returns the cell as the focused thing... so do we!
//
return DataGrid.AccessibilityObject.GetFocused();
}
/// <include file='doc\DataGridRow.uex' path='docs/doc[@for="DataGridRow.DataGridCellAccessibleObject.Navigate"]/*' />
/// <devdoc>
/// Navigate to the next or previous grid entry.
/// </devdoc>
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override AccessibleObject Navigate(AccessibleNavigation navdir) {
switch (navdir) {
case AccessibleNavigation.Right:
case AccessibleNavigation.Next:
if (column < owner.AccessibleObject.GetChildCount() - 1) {
return owner.AccessibleObject.GetChild(column + 1);
}
else {
AccessibleObject o = DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber + 1);
if (o != null) {
return o.Navigate(AccessibleNavigation.FirstChild);
}
}
break;
case AccessibleNavigation.Down:
return DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber + 1).Navigate(AccessibleNavigation.FirstChild);
case AccessibleNavigation.Up:
return DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber - 1).Navigate(AccessibleNavigation.FirstChild);
case AccessibleNavigation.Left:
case AccessibleNavigation.Previous:
if (column > 0) {
return owner.AccessibleObject.GetChild(column - 1);
}
else {
AccessibleObject o = DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber - 1);
if (o != null) {
return o.Navigate(AccessibleNavigation.LastChild);
}
}
break;
case AccessibleNavigation.FirstChild:
case AccessibleNavigation.LastChild:
break;
}
return null;
}
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override void Select(AccessibleSelection flags) {
// Focus the PropertyGridView window
//
if ( (flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) {
DataGrid.Focus();
}
// Select the grid entry
//
if ( (flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) {
DataGrid.CurrentCell = new DataGridCell(owner.RowNumber, column);
}
}
}
}
}
| |
/*
Microsoft Automatic Graph Layout,MSAGL
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
""Software""), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Core.Routing;
using Microsoft.Msagl.Drawing;
using Microsoft.Msagl.Layout.Incremental;
using Microsoft.Msagl.Layout.Layered;
using Microsoft.Msagl.Layout.MDS;
using Microsoft.Msagl.Prototype.Ranking;
using MouseButtons=System.Windows.Forms.MouseButtons;
using Point = Microsoft.Msagl.Core.Geometry.Point;
using Rectangle = System.Drawing.Rectangle;
using Size=System.Drawing.Size;
namespace Microsoft.Msagl.GraphViewerGdi{
/// <summary>
/// Summary description for DOTViewer.
/// </summary>
partial class GViewer : IViewer{
const int ScrollMax = 0xFFFF;
const string windowZoomButtonDisabledToolTipText = "Zoom in by dragging a rectangle, is disabled now";
internal static double Dpi = GetDotsPerInch();
internal static double dpix;
internal static double dpiy;
readonly MdsLayoutSettings mdsLayoutSettings;
readonly RankingLayoutSettings rankingSettings = new RankingLayoutSettings();
readonly SugiyamaLayoutSettings sugiyamaSettings;
LayoutMethod currentLayoutMethod = LayoutMethod.UseSettingsOfTheGraph;
System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(0, 0, 0, 0);
DrawingPanel panel;
bool saveAsImageEnabled = true;
bool saveAsMsaglEnabled = true;
bool saveInVectorFormatEnabled = true;
bool zoomWhenMouseWheelScroll = true;
const string panButtonToolTipText = "Pan";
RectangleF srcRect = new RectangleF(0, 0, 0, 0);
internal double zoomFraction = 0.5f;
/// <summary>
/// Default constructor
/// </summary>
public GViewer(){
mdsLayoutSettings = new MdsLayoutSettings();
sugiyamaSettings = new SugiyamaLayoutSettings();
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
BackwardEnabled = false;
ForwardEnabled = false;
toolbar.MouseMove += ToolBarMouseMoved;
Assembly a = Assembly.GetExecutingAssembly();
foreach (string r in a.GetManifestResourceNames()){
if (r.Contains("hmove.cur"))
panGrabCursor = new Cursor(a.GetManifestResourceStream(r));
else if (r.Contains("oph.cur"))
panOpenCursor = new Cursor(a.GetManifestResourceStream(r));
}
originalCursor = Cursor;
panButton.Pushed = false;
windowZoomButton.Pushed = false;
layoutSettingsButton.ToolTipText = "Configures the layout algorithm settings";
undoButton.ToolTipText = "Undo layout editing";
redoButton.ToolTipText = "Redo layout editing";
forwardButton.ToolTipText = "Forward";
panButton.ToolTipText = panButton.Pushed ? panButtonToolTipText : PanButtonDisabledToolTipText;
windowZoomButton.ToolTipText = windowZoomButton.Pushed
? WindowZoomButtonToolTipText
: windowZoomButtonDisabledToolTipText;
InitDrawingLayoutEditor();
toolbar.Invalidate();
SuspendLayout();
InitPanel();
Controls.Add(toolbar);
ResumeLayout();
}
/// <summary>
/// Sets or gets the fraction on which the zoom value changes in every zoom out or zoom in
/// </summary>
public double ZoomFraction{
get { return zoomFraction; }
set{
if (value > 0.9)
value = 0.9f;
else if (value < 0.0001)
value = 0.0001f;
zoomFraction = value;
}
}
internal double LocalScale { get; set; }
/*
* (s, 0,a)(srcRect.X)= (destRect.Left,destRect.Top)
* (0,-s,b)(srcRect.Y)
* a=destRect.Left-s*srcRect.Left
* b=destRect.Bottom + srcRect.Bottom * s
* */
internal RectangleF SrcRect{
get { return srcRect; }
set { srcRect = value; }
}
/// <summary>
/// The width of the current graph
/// </summary>
public double GraphWidth{
get { return OriginalGraph.Width; }
}
/// <summary>
/// The height of the current graph
/// </summary>
public double GraphHeight{
get { return OriginalGraph.Height; }
}
/// <summary>
/// Gets or sets the zoom factor
/// </summary>
public double ZoomF{
get { return CurrentScale/GetFitScale(); }
set{
if (OriginalGraph == null)
return;
if (value < ApproximateComparer.Tolerance || double.IsNaN(value)){
//MessageBox.Show("the zoom value is out of range ")
return;
}
var center = new Point(panel.Width/2.0, panel.Height/2.0);
var centerOnSource = transformation.Inverse*center;
var scaleForZoom1 = GetFitScale();
var scale = scaleForZoom1*value;
SetTransformOnScaleAndCenter(scale,centerOnSource);
panel.Invalidate();
}
}
internal int PanelWidth{
get { return panel.ClientRectangle.Width; }
}
internal int PanelHeight{
get { return panel.ClientRectangle.Height; }
}
/// <summary>
/// capturing the previous user's choice of which veiw to save
/// </summary>
internal bool SaveCurrentViewInImage { get; set; }
/// <summary>
/// The panel containing GViewer object
/// </summary>
public Control DrawingPanel{
get { return panel; }
}
/// <summary>
/// Gets or sets the forward and backward buttons visibility
/// </summary>
public bool NavigationVisible{
get { return forwardButton.Visible; }
set{
forwardButton.Visible = value;
backwardButton.Visible = value;
}
}
/// <summary>
/// Gets or sets the save button visibility
/// </summary>
public bool SaveButtonVisible{
get { return saveButton.Visible; }
set { saveButton.Visible = value; }
}
///// <summary>
///// The event raised when the graph object under the mouse cursor changes
///// </summary>
//public event EventHandler SelectionChanged;
/// <summary>
/// The rectangle for drawing
/// </summary>
internal System.Drawing.Rectangle DestRect{
get { return destRect; }
set { destRect = value; }
}
/// <summary>
/// Enables or disables the forward button
/// </summary>
public bool ForwardEnabled{
get { return forwardButton.ImageIndex == (int) ImageEnum.Forward; }
set { forwardButton.ImageIndex = (int) (value ? ImageEnum.Forward : ImageEnum.ForwardDis); }
}
/// <summary>
/// Enables or disables the backward button
/// </summary>
public bool BackwardEnabled{
get { return backwardButton.ImageIndex == (int) ImageEnum.Backward; }
set { backwardButton.ImageIndex = (int) (value ? ImageEnum.Backward : ImageEnum.BackwardDis); }
}
/// <summary>
/// hides/shows the toolbar
/// </summary>
public bool ToolBarIsVisible{
get { return Controls.Contains(toolbar); }
set{
if (value != ToolBarIsVisible){
SuspendLayout();
if (value){
Controls.Add(toolbar);
Controls.SetChildIndex(toolbar, 1); //it follows the panel
}
else
Controls.Remove(toolbar);
ResumeLayout();
}
}
}
/// <summary>
/// Enables or disables zoom in/out when mouse wheel scrool.
/// </summary>
public bool ZoomWhenMouseWheelScroll{
get { return zoomWhenMouseWheelScroll; }
set { zoomWhenMouseWheelScroll = value; }
}
/// <summary>
/// If this property is set to true the control enables saving and loading of .MSAGL files
/// Otherwise the "Load file" button and saving as .MSAGL file is disabled.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msagl")]
public bool SaveAsMsaglEnabled{
get { return saveAsMsaglEnabled; }
set{
if (saveAsMsaglEnabled != value){
openButton.Visible = value;
saveAsMsaglEnabled = value;
}
}
}
/// <summary>
/// enables or disables saving the graph in a vector format
/// </summary>
public bool SaveInVectorFormatEnabled{
get { return saveInVectorFormatEnabled; }
set { saveInVectorFormatEnabled = value; }
}
/// <summary>
/// enables or disables saving the graph as an image
/// </summary>
public bool SaveAsImageEnabled{
get { return saveAsImageEnabled; }
set { saveAsImageEnabled = value; }
}
/// <summary>
///hides and shows the layout algorithm settings button
/// </summary>
public bool LayoutAlgorithmSettingsButtonVisible{
get { return layoutSettingsButton.Visible; }
set { layoutSettingsButton.Visible = value; }
}
/// <summary>
/// hides and shows the "Save graph" button
/// </summary>
public bool SaveGraphButtonVisible{
get { return saveButton.Visible; }
set { saveButton.Visible = value; }
}
/// <summary>
/// exposes the kind of the layout that is used when the graph is laid out by the viewer
/// </summary>
public LayoutMethod CurrentLayoutMethod{
get { return currentLayoutMethod; }
set { currentLayoutMethod = value; }
}
#region Members
const int minimalSizeToDraw = 10;
Brush imageBackgroungBrush = Brushes.White;
readonly ViewInfosList listOfViewInfos = new ViewInfosList();
System.Drawing.Point mousePositonWhenSetSelectedObject;
internal Cursor originalCursor;
Brush outsideAreaBrush = Brushes.LightGray;
internal Cursor panGrabCursor;
internal Cursor panOpenCursor;
internal DObject selectedDObject;
bool storeViewInfo = true;
/// <summary>
/// The color of the area outside of the graph.
/// </summary>
public Brush OutsideAreaBrush{
get { return outsideAreaBrush; }
set { outsideAreaBrush = value; }
}
/// <summary>
/// The object which is currently located under the mouse cursor
/// </summary>
public object SelectedObject{
get { return selectedDObject != null ? selectedDObject.DrawingObject : null; }
}
internal System.Drawing.Point MousePositonWhenSetSelectedObject{
get { return mousePositonWhenSetSelectedObject; }
set { mousePositonWhenSetSelectedObject = value; }
}
internal ToolTip ToolTip{
get { return toolTip1; }
set { toolTip1 = value; }
}
internal void SetSelectedObject(object o){
selectedDObject = (DObject) o;
MousePositonWhenSetSelectedObject = MousePosition;
}
//public static double LocationToFloat(int location) { return ((double)location) * LayoutAlgorithmSettings.PointSize; }
//public static double LocationToFloat(string location) { return LocationToFloat(Int32.Parse(location)); }
internal bool DestRectContainsPoint(System.Drawing.Point p){
return destRect.Contains(p);
}
#endregion
bool editingEnabled = true;
readonly FastIncrementalLayoutSettings
fastIncrementalLayoutSettings = FastIncrementalLayoutSettings.CreateFastIncrementalLayoutSettings();
/// <summary>
///
/// </summary>
bool EditingEnabled
{
get { return editingEnabled; }
set { editingEnabled = value; }
}
#region IViewer Members
/// <summary>
///
/// </summary>
public event EventHandler<EventArgs> ViewChangeEvent;
/// <summary>
/// enables and disables the default editing of the viewer
/// </summary>
public bool LayoutEditingEnabled{
get { return !(panButton.Pushed || windowZoomButton.Pushed) && EditingEnabled; }
set { EditingEnabled = value; }
}
/// <summary>
///
/// </summary>
public Core.Geometry.Rectangle ClientViewport { get; private set; }
/// <summary>
///
/// </summary>
public double DistanceForSnappingThePortToNodeBoundary{
get { return UnderlyingPolylineCircleRadius*2; }
}
#endregion
void ZoomWithOne(){
}
void CalcDestRect() {
var lt = Transform*new Point(srcRect.Left, srcRect.Bottom);
destRect.X = (int) lt.X;
destRect.Y = (int) lt.Y;
destRect.Width = (int) (CurrentScale*srcRect.Width);
destRect.Height = (int) (CurrentScale*srcRect.Height);
}
void GetSizes(out int panelWidth, out int panelHeight, PrintPageEventArgs printPageEvenArgs) {
if (printPageEvenArgs == null) {
panelWidth = PanelWidth;
panelHeight = PanelHeight;
} else {
panelWidth = (int) printPageEvenArgs.PageSettings.PrintableArea.Width;
panelHeight = (int) printPageEvenArgs.PageSettings.PrintableArea.Height;
}
}
void CalcRects(PrintPageEventArgs printPageEvenArgs) {
var w = printPageEvenArgs == null ? PanelWidth : printPageEvenArgs.PageBounds.Width;
var h = printPageEvenArgs == null ? PanelHeight : printPageEvenArgs.PageBounds.Height;
if (OriginalGraph != null){
CalcSrcRect(w,h);
CalcDestRect();
}
prevPanelClientRectangle = panel.ClientRectangle;
}
void CalcSrcRect(double w, double h) {
var m = Transform.Inverse;
var rec=new Core.Geometry.Rectangle(m*(new Point(0, 0)), m*new Point(w, h));
rec = Core.Geometry.Rectangle.Intersect(originalGraph.BoundingBox,rec);
srcRect = new RectangleF((float)rec.Left, (float)rec.Bottom, (float)rec.Width, (float)rec.Height);
// if (scaledDown == false){
// double k = OriginalGraph.Width/ScrollMaxF;
//
// srcRect.Width = (float) Math.Min(OriginalGraph.Width, k*HLargeChangeF);
// srcRect.X = (float) (k*HValF) + (float) OriginalGraph.Left;
//
// k = OriginalGraph.Height/ScrollMaxF;
// srcRect.Y = (float) OriginalGraph.Height + (float) ScaleFromScrollToSrcY(VVal + VLargeChange) +
// (float) OriginalGraph.Bottom;
// srcRect.Height = (float) Math.Min(OriginalGraph.Height, k*VLargeChangeF);
// }
// else{
// srcRect.X = (float) OriginalGraph.Left;
// srcRect.Y = (float) OriginalGraph.Height + (float) ScaleFromScrollToSrcY(vScrollBar.Maximum) +
// (float) OriginalGraph.Bottom;
// srcRect.Width = (float) GraphWidth;
// srcRect.Height = (float) GraphHeight;
// }
}
static double GetDotsPerInch(){
Graphics g = (new Form()).CreateGraphics();
return Math.Max(dpix = g.DpiX, dpiy = g.DpiY);
}
/// <summary>
/// The ViewInfo gives all info needed for setting the view
/// </summary>
protected override void OnPaint(PaintEventArgs e){
panel.Invalidate();
}
void SetViewFromViewInfo(ViewInfo viewInfo) {
Transform = viewInfo.Transformation.Clone();
panel.Invalidate();
}
void ToolBarMouseMoved(object o, MouseEventArgs a){
Cursor = originalCursor;
}
void vScrollBar_MouseEnter(object o, EventArgs a){
ToolBarMouseMoved(null, null);
}
/// <summary>
/// Tightly fit the bounding box around the graph
/// </summary>
public void FitGraphBoundingBox(){
if (LayoutEditor != null){
if (Graph != null)
LayoutEditor.FitGraphBoundingBox(DGraph);
Invalidate();
}
}
void InitPanel(){
panel = new DrawingPanel{TabIndex = 0};
Controls.Add(panel);
panel.Dock = DockStyle.Fill;
panel.Name = "panel";
panel.TabIndex = 0;
panel.GViewer = this;
panel.SetDoubleBuffering();
panel.Click += PanelClick;
DrawingPanel.MouseClick += DrawingPanelMouseClick;
DrawingPanel.MouseDoubleClick += DrawingPanel_MouseDoubleClick;
DrawingPanel.MouseCaptureChanged += DrawingPanel_MouseCaptureChanged;
DrawingPanel.MouseDown += DrawingPanel_MouseDown;
DrawingPanel.MouseEnter += DrawingPanel_MouseEnter;
DrawingPanel.MouseHover += DrawingPanel_MouseHover;
DrawingPanel.MouseLeave += DrawingPanel_MouseLeave;
DrawingPanel.MouseMove += DrawingPanel_MouseMove;
DrawingPanel.MouseUp += DrawingPanel_MouseUp;
DrawingPanel.MouseWheel += GViewer_MouseWheel;
DrawingPanel.Move += GViewer_Move;
DrawingPanel.KeyDown += DrawingPanel_KeyDown;
DrawingPanel.KeyPress += DrawingPanel_KeyPress;
DrawingPanel.KeyUp += DrawingPanel_KeyUp;
DrawingPanel.DoubleClick += DrawingPanel_DoubleClick;
DrawingPanel.SizeChanged += DrawingPanelSizeChanged;
this.SizeChanged += GViewer_SizeChanged;
}
void GViewer_SizeChanged(object sender, EventArgs e) {
panel.Invalidate();
}
Rectangle prevPanelClientRectangle;
void DrawingPanelSizeChanged(object sender, EventArgs e) {
if (originalGraph == null || panel.ClientRectangle.Width<2 || panel.ClientRectangle.Height<2) return;
double oldFitFactor = Math.Min(prevPanelClientRectangle.Width/originalGraph.Width, prevPanelClientRectangle.Height/originalGraph.Height);
var center = new Point(prevPanelClientRectangle.Width / 2.0, prevPanelClientRectangle.Height / 2.0);
var centerOnSource = transformation.Inverse * center;
SetTransformOnScaleAndCenter(GetFitScale()*CurrentScale/oldFitFactor, centerOnSource);
prevPanelClientRectangle = panel.ClientRectangle;
}
void DrawingPanel_DoubleClick(object sender, EventArgs e){
OnDoubleClick(e);
}
void DisableDrawingLayoutEditor(){
if (LayoutEditor != null){
LayoutEditor.DetouchFromViewerEvents();
LayoutEditor = null;
}
}
void InitDrawingLayoutEditor(){
if (LayoutEditor == null){
LayoutEditor = new LayoutEditor(this);
LayoutEditor.ChangeInUndoRedoList += DrawingLayoutEditor_ChangeInUndoRedoList;
}
undoButton.ImageIndex = (int) ImageEnum.UndoDisabled;
redoButton.ImageIndex = (int) ImageEnum.RedoDisabled;
}
void DrawingLayoutEditor_ChangeInUndoRedoList(object sender, EventArgs args) {
if (InvokeRequired)
Invoke((Invoker) FixUndoRedoButtons);
else
FixUndoRedoButtons();
}
void FixUndoRedoButtons() {
undoButton.ImageIndex = UndoImageIndex();
redoButton.ImageIndex = RedoImageIndex();
}
int RedoImageIndex(){
return (int) (LayoutEditor.CanRedo ? ImageEnum.Redo : ImageEnum.RedoDisabled);
}
int UndoImageIndex(){
return (int) (LayoutEditor.CanUndo ? ImageEnum.Undo : ImageEnum.UndoDisabled);
}
/// <summary>
/// Set context menu strip for DrawingPanel
/// </summary>
/// <param name="contexMenuStrip"></param>
public void SetContextMenumStrip(ContextMenuStrip contexMenuStrip)
{
DrawingPanel dp = this.DrawingPanel as DrawingPanel;
dp.SetCms(contexMenuStrip);
}
void DrawingPanel_KeyUp(object sender, KeyEventArgs e){
OnKeyUp(e);
}
void DrawingPanel_KeyPress(object sender, KeyPressEventArgs e){
OnKeyPress(e);
}
void DrawingPanel_KeyDown(object sender, KeyEventArgs e){
OnKeyDown(e);
}
void GViewer_Move(object sender, EventArgs e){
OnMove(e);
}
void GViewer_MouseWheel(object sender, MouseEventArgs e){
if (zoomWhenMouseWheelScroll){
if (OriginalGraph == null) return;
var pointSrc = ScreenToSource(e.X, e.Y);
const double zoomFractionLocal = 0.9;
var zoomInc = e.Delta > 0 ? zoomFractionLocal : 1.0 / zoomFractionLocal;
var scale = CurrentScale*zoomInc;
var d = OriginalGraph.BoundingBox.Diagonal;
if (d*scale < 5 || d*scale > HugeDiagonal)
return;
var dx = e.X - pointSrc.X*scale;
var dy = e.Y + pointSrc.Y*scale;
Transform[0, 0] = scale;
Transform[1, 1] = -scale;
Transform[0, 2] = dx;
Transform[1, 2] = dy;
panel.Invalidate();
}
OnMouseWheel(e);
}
/*
double FindZoomIncrementForWheel(double zoomFraction, MouseEventArgs e) {
double xs = FindZoomIncrementForWheelX(e);
double ys = FindZoomIncrementForWheelY(e);
double s = 1/Math.Max(xs, ys);
return Math.Min(zoomFraction, s);
}
*/
/*
double FindZoomIncrementForWheelY(MouseEventArgs args){
var y = args.Y;
double ph = PanelHeight;
double gh = originalGraph.Height * LocalScale;
if (scaledDown)
gh *= scaleDownCoefficient;
return Math.Max (y/(y - (ph - gh) / 2), (ph - y) / ((ph + gh) / 2 - y));
}
*/
/*
double FindZoomIncrementForWheelX(MouseEventArgs args){
var x = args.X;
double pw = PanelWidth;
double gw = originalGraph.Width*LocalScale;
if (scaledDown)
gw *= scaleDownCoefficient;
return Math.Max(x/(x - (pw - gw) / 2), (pw - x) / ((pw + gw) / 2 - x));
}
*/
void DrawingPanel_MouseUp(object sender, MouseEventArgs e){
OnMouseUp(e);
}
void DrawingPanel_MouseMove(object sender, MouseEventArgs e){
OnMouseMove(e);
}
void DrawingPanel_MouseLeave(object sender, EventArgs e){
OnMouseLeave(e);
}
void DrawingPanel_MouseHover(object sender, EventArgs e){
OnMouseHover(e);
}
void DrawingPanel_MouseEnter(object sender, EventArgs e){
OnMouseEnter(e);
}
void DrawingPanel_MouseDown(object sender, MouseEventArgs e){
OnMouseDown(e);
}
void DrawingPanel_MouseCaptureChanged(object sender, EventArgs e){
OnMouseCaptureChanged(e);
}
void DrawingPanel_MouseDoubleClick(object sender, MouseEventArgs e){
OnMouseDoubleClick(e);
}
internal void Hit(MouseEventArgs args){
if (args.Button == MouseButtons.None)
UnconditionalHit(args, EntityFilterDelegate);
}
#region Nested type: ImageEnum
enum ImageEnum{
ZoomIn,
ZoomOut,
WindowZoom,
Hand,
Forward,
ForwardDis,
Backward,
BackwardDis,
Save,
Undo,
Redo,
Print,
Open,
UndoDisabled,
RedoDisabled
}
#endregion
/// <summary>
/// maps a screen point to the graph
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public Point ScreenToSource(double x, double y){
return ScreenToSource(new Point(x, y));
}
}
}
| |
using System;
using System.Globalization;
using Premotion.Mansion.Core.Collections;
using Premotion.Mansion.Core.Data;
using Premotion.Mansion.Core.IO;
using Premotion.Mansion.Core.Nucleus;
using Premotion.Mansion.Core.Patterns;
using Premotion.Mansion.Core.Scripting;
using Premotion.Mansion.Core.Scripting.TagScript;
using Premotion.Mansion.Core.Security;
using Premotion.Mansion.Core.Templating;
namespace Premotion.Mansion.Core
{
/// <summary>
/// Implements the base class for <see cref="IMansionContext"/> decorators.
/// </summary>
public abstract class MansionContextDecorator : DisposableBase, IMansionContext
{
#region Constructors
/// <summary>
/// Constructs the mansion context decorator.
/// </summary>
/// <param name="decoratedContext">The <see cref="IMansionContext"/> being decorated.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="decoratedContext"/> is null.</exception>
protected MansionContextDecorator(IMansionContext decoratedContext)
{
// validate arguments
if (decoratedContext == null)
throw new ArgumentNullException("decoratedContext");
// set values
this.decoratedContext = decoratedContext;
}
#endregion
#region Implementation of IMansionContext
/// <summary>
/// Extends this context.
/// </summary>
/// <typeparam name="TContextExtension">The type of extension, must have a default constructor and inherit from <see cref="MansionContextExtension"/>.</typeparam>
/// <returns>Returns the extions.</returns>
/// <exception cref="MansionContextExtensionNotFoundException">Thrown when the extension is not found.</exception>
public TContextExtension Extend<TContextExtension>() where TContextExtension : MansionContextExtension
{
return decoratedContext.Extend<TContextExtension>();
}
/// <summary>
/// Extends this context.
/// </summary>
/// <typeparam name="TContextExtension">The type of extension, must have a default constructor and inherit from <see cref="MansionContextExtension"/>.</typeparam>
/// <param name="factory">The <see cref="Func{IContext,TContextExtension}"/> creating the context when needed.</param>
/// <returns>Returns the extions.</returns>
public TContextExtension Extend<TContextExtension>(Func<IMansionContext, TContextExtension> factory) where TContextExtension : MansionContextExtension
{
return decoratedContext.Extend(factory);
}
/// <summary>
/// Tries to cast this context into another form..
/// </summary>
/// <typeparam name="TContext">The type of context, must implement <see cref="IMansionContext"/>.</typeparam>
/// <returns>Returns context.</returns>
/// <exception cref="InvalidCastException">Thrown when this context can not be cast into the desired context type.</exception>
public TContext Cast<TContext>() where TContext : class, IMansionContext
{
return decoratedContext.Cast<TContext>();
}
/// <summary>
/// Gets a flag indicating whether the execution of this script should stop.
/// </summary>
public bool HaltExecution
{
get { return decoratedContext.HaltExecution; }
}
/// <summary>
/// Breaks all the execution.
/// </summary>
public bool BreakExecution
{
set { decoratedContext.BreakExecution = value; }
}
/// <summary>
/// Sets a flag indicating whether the execution of the current procedure should be stopped.
/// </summary>
public bool BreakTopMostProcedure
{
set { decoratedContext.BreakTopMostProcedure = value; }
}
/// <summary>
/// Sets the current user.
/// </summary>
/// <param name="authenticatedUser">The authenticated user.</param>
public void SetCurrentUserState(UserState authenticatedUser)
{
decoratedContext.SetCurrentUserState(authenticatedUser);
}
/// <summary>
/// Sets the frontoffice user.
/// </summary>
/// <param name="authenticatedUser">The authenticated user.</param>
public void SetFrontofficeUserState(UserState authenticatedUser)
{
decoratedContext.SetFrontofficeUserState(authenticatedUser);
}
/// <summary>
/// Sets the backoffice user.
/// </summary>
/// <param name="authenticatedUser">The authenticated user.</param>
public void SetBackofficeUserState(UserState authenticatedUser)
{
decoratedContext.SetBackofficeUserState(authenticatedUser);
}
/// <summary>
/// Gets the stack of this context.
/// </summary>
public IAutoPopDictionaryStack<string, IPropertyBag> Stack
{
get { return decoratedContext.Stack; }
}
/// <summary>
/// Gets a flag indicating whether this is a front or backoffice contex.t
/// </summary>
public bool IsBackoffice
{
get { return decoratedContext.IsBackoffice; }
}
/// <summary>
/// Gets the procedure stack.
/// </summary>
public IAutoPopDictionaryStack<string, IScript> ProcedureStack
{
get { return decoratedContext.ProcedureStack; }
}
/// <summary>
/// Gets/Sets the depth of the execute nested procedures.
/// </summary>
public int ExecuteNestedProcedureDepth
{
get { return decoratedContext.ExecuteNestedProcedureDepth; }
set { decoratedContext.ExecuteNestedProcedureDepth = value; }
}
/// <summary>
/// Gets the procedure call stack.
/// </summary>
public IAutoPopStack<ScriptTag> ProcedureCallStack
{
get { return decoratedContext.ProcedureCallStack; }
}
/// <summary>
/// Gets the event handler stack.
/// </summary>
public IAutoPopDictionaryStack<string, IScript> EventHandlerStack
{
get { return decoratedContext.EventHandlerStack; }
}
/// <summary>
/// Gets the script stack.
/// </summary>
public IAutoPopStack<ITagScript> ScriptStack
{
get { return decoratedContext.ScriptStack; }
}
/// <summary>
/// Gets the output pipe stack.
/// </summary>
public IAutoPopStack<IOutputPipe> OutputPipeStack
{
get { return decoratedContext.OutputPipeStack; }
}
/// <summary>
/// Gets the top most output pipe.
/// </summary>
public IOutputPipe OutputPipe
{
get { return decoratedContext.OutputPipe; }
}
/// <summary>
/// Gets the input pipe stack.
/// </summary>
public IAutoPopStack<IInputPipe> InputPipeStack
{
get { return decoratedContext.InputPipeStack; }
}
/// <summary>
/// Gets the top most input pipe.
/// </summary>
public IInputPipe InputPipe
{
get { return decoratedContext.InputPipe; }
}
/// <summary>
/// Gets the template stack.
/// </summary>
public IAutoPopStack<ITemplate> TemplateStack
{
get { return decoratedContext.TemplateStack; }
}
/// <summary>
/// Gets the active section stack.
/// </summary>
public IAutoPopStack<ActiveSection> ActiveSectionStack
{
get { return decoratedContext.ActiveSectionStack; }
}
/// <summary>
/// Gets the <see cref="UserState"/> for the frontoffice.
/// </summary>
public UserState FrontofficeUserState
{
get { return decoratedContext.FrontofficeUserState; }
}
/// <summary>
/// Gets the <see cref="UserState"/> for the backoffice.
/// </summary>
public UserState BackofficeUserState
{
get { return decoratedContext.BackofficeUserState; }
}
/// <summary>
/// Gets the user for the current context determined by <see cref="IMansionContext.IsBackoffice"/>
/// </summary>
public UserState CurrentUserState
{
get { return decoratedContext.CurrentUserState; }
}
/// <summary>
/// Gets the repository stack.
/// </summary>
public IAutoPopStack<IRepository> RepositoryStack
{
get { return decoratedContext.RepositoryStack; }
}
/// <summary>
/// Gets the top most repository from the stack.
/// </summary>
public IRepository Repository
{
get { return decoratedContext.Repository; }
}
/// <summary>
/// Gets the <see cref="CultureInfo"/> of the system.
/// </summary>
public CultureInfo SystemCulture
{
get { return decoratedContext.SystemCulture; }
}
/// <summary>
/// Gets the <see cref="CultureInfo"/> of the user interface.
/// </summary>
public CultureInfo UserInterfaceCulture
{
get { return decoratedContext.UserInterfaceCulture; }
}
/// <summary>
/// Gets the <see cref="INucleus"/> used by this context.
/// </summary>
public INucleus Nucleus
{
get { return decoratedContext.Nucleus; }
}
/// <summary>
/// Gets/Sets the depth of the response template stack.
/// </summary>
public int ResponseTemplateStackDepth
{
get { return decoratedContext.ResponseTemplateStackDepth; }
set { decoratedContext.ResponseTemplateStackDepth = value; }
}
/// <summary>
/// Gets the top most <see cref="IPropertyBagReader"/>.
/// </summary>
public IPropertyBagReader Reader
{
get { return decoratedContext.Reader; }
}
/// <summary>
/// Gets the <see cref="IPropertyBag"/> stack.
/// </summary>
public IAutoPopStack<IPropertyBagReader> ReaderStack
{
get { return decoratedContext.ReaderStack; }
}
#endregion
#region Overrides of DisposableBase
/// <summary>
/// Dispose resources. Override this method in derived classes. Unmanaged resources should always be released
/// when this method is called. Managed resources may only be disposed of if disposeManagedResources is true.
/// </summary>
/// <param name="disposeManagedResources">A value which indicates whether managed resources may be disposed of.</param>
protected override void DisposeResources(bool disposeManagedResources)
{
// do nothing might be overriden
}
#endregion
#region Private Fields
private readonly IMansionContext decoratedContext;
#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.
*/
using System.Collections.Generic;
using System.IO;
namespace Apache.Geode.Client.Tests
{
using Apache.Geode.DUnitFramework;
using Apache.Geode.Templates.Cache.Security;
using Apache.Geode.Client;
public class XmlAuthzCredentialGenerator : AuthzCredentialGenerator
{
enum Role
{
Reader,
Writer,
Query,
Admin
}
private const string DocURIProp = "security-authz-xml-uri";
private const string DummyXml = "authz-dummy.xml";
private const string LdapXml = "authz-ldap.xml";
private const string PkcsXml = "authz-pkcs.xml";
private static string[] QueryRegions = { "Portfolios", "Positions" };
public static OperationCode[] ReaderOps = { OperationCode.Get, OperationCode.GetAll,
OperationCode.GetServerKeys,
OperationCode.RegisterInterest, OperationCode.UnregisterInterest, OperationCode.ExecuteCQ };
public static OperationCode[] WriterOps = { OperationCode.Put, OperationCode.PutAll, OperationCode.RemoveAll,
OperationCode.Destroy, OperationCode.ExecuteFunction };
public static OperationCode[] QueryOps = { OperationCode.Query };
private static Dictionary<OperationCode, bool> readerOpsSet;
private static Dictionary<OperationCode, bool> writerOpsSet;
private static Dictionary<OperationCode, bool> queryOpsSet;
private static Dictionary<string, bool> queryRegionSet;
static XmlAuthzCredentialGenerator()
{
readerOpsSet = new Dictionary<OperationCode, bool>();
for (int index = 0; index < ReaderOps.Length; index++)
{
readerOpsSet.Add(ReaderOps[index], true);
}
writerOpsSet = new Dictionary<OperationCode, bool>();
for (int index = 0; index < WriterOps.Length; index++)
{
writerOpsSet.Add(WriterOps[index], true);
}
queryOpsSet = new Dictionary<OperationCode, bool>();
for (int index = 0; index < QueryOps.Length; index++)
{
queryOpsSet.Add(QueryOps[index], true);
}
queryRegionSet = new Dictionary<string, bool>();
for (int index = 0; index < QueryRegions.Length; index++)
{
queryRegionSet.Add(QueryRegions[index], true);
}
}
public XmlAuthzCredentialGenerator()
{
}
protected override Properties<string, string> Init()
{
Properties<string, string> sysProps = new Properties<string, string>();
string dirName = m_cGen.ServerDataDir;
if (dirName != null && dirName.Length > 0)
{
dirName += "/";
}
switch (this.m_cGen.GetClassCode())
{
case CredentialGenerator.ClassCode.Dummy:
sysProps.Insert(DocURIProp, dirName + DummyXml);
break;
case CredentialGenerator.ClassCode.LDAP:
sysProps.Insert(DocURIProp, dirName + LdapXml);
break;
case CredentialGenerator.ClassCode.PKCS:
sysProps.Insert(DocURIProp, dirName + PkcsXml);
break;
default:
throw new IllegalArgumentException(
"No XML defined for XmlAuthorization module to work with " +
this.m_cGen.Authenticator);
}
return sysProps;
}
public override ClassCode GetClassCode()
{
return ClassCode.XML;
}
public override string AccessControl
{
get
{
return "templates.security.XmlAuthorization.create";
}
}
protected override Properties<string, string> GetAllowedPrincipal(
OperationCode[] opCodes, string[] regionNames, int index)
{
CredentialGenerator.ClassCode cGenCode = this.m_cGen.GetClassCode();
Role roleType = GetRequiredRole(opCodes, regionNames);
switch (cGenCode)
{
case CredentialGenerator.ClassCode.Dummy:
return GetDummyPrincipal(roleType, index);
case CredentialGenerator.ClassCode.LDAP:
return GetLdapPrincipal(roleType, index);
case CredentialGenerator.ClassCode.PKCS:
return GetPKCSPrincipal(roleType, index);
}
return null;
}
protected override Properties<string, string> GetDisallowedPrincipal(
OperationCode[] opCodes, string[] regionNames, int index)
{
Role roleType = GetRequiredRole(opCodes, regionNames);
Role disallowedRoleType = Role.Reader;
switch (roleType)
{
case Role.Reader:
disallowedRoleType = Role.Writer;
break;
case Role.Writer:
disallowedRoleType = Role.Reader;
break;
case Role.Query:
disallowedRoleType = Role.Reader;
break;
case Role.Admin:
disallowedRoleType = Role.Reader;
break;
}
CredentialGenerator.ClassCode cGenCode = this.m_cGen.GetClassCode();
switch (cGenCode)
{
case CredentialGenerator.ClassCode.Dummy:
return GetDummyPrincipal(disallowedRoleType, index);
case CredentialGenerator.ClassCode.LDAP:
return GetLdapPrincipal(disallowedRoleType, index);
case CredentialGenerator.ClassCode.PKCS:
return GetPKCSPrincipal(disallowedRoleType, index);
}
return null;
}
protected override int GetNumPrincipalTries(
OperationCode[] opCodes, string[] regionNames)
{
return 5;
}
private Properties<string, string> GetDummyPrincipal(Role roleType, int index)
{
string[] admins = new string[] { "root", "admin", "administrator" };
int numReaders = 3;
int numWriters = 3;
switch (roleType)
{
case Role.Reader:
return GetUserPrincipal("reader" + (index % numReaders));
case Role.Writer:
return GetUserPrincipal("writer" + (index % numWriters));
case Role.Query:
return GetUserPrincipal("reader" + ((index % 2) + 3));
default:
return GetUserPrincipal(admins[index % admins.Length]);
}
}
private Properties<string, string> GetLdapPrincipal(Role roleType, int index)
{
return GetUserPrincipal(GetLdapUser(roleType, index));
}
private Properties<string, string> GetPKCSPrincipal(Role roleType, int index)
{
string userName = GetLdapUser(roleType, index);
Properties<string, string> props = new Properties<string, string>();
props.Insert(PKCSCredentialGenerator.KeyStoreAliasProp, userName);
return props;
}
private string GetLdapUser(Role roleType, int index)
{
const string userPrefix = "geode";
int[] readerIndices = { 3, 4, 5 };
int[] writerIndices = { 6, 7, 8 };
int[] queryIndices = { 9, 10 };
int[] adminIndices = { 1, 2 };
switch (roleType)
{
case Role.Reader:
int readerIndex = readerIndices[index % readerIndices.Length];
return (userPrefix + readerIndex);
case Role.Writer:
int writerIndex = writerIndices[index % writerIndices.Length];
return (userPrefix + writerIndex);
case Role.Query:
int queryIndex = queryIndices[index % queryIndices.Length];
return (userPrefix + queryIndex);
default:
int adminIndex = adminIndices[index % adminIndices.Length];
return (userPrefix + adminIndex);
}
}
private Role GetRequiredRole(OperationCode[] opCodes,
string[] regionNames)
{
Role roleType = Role.Admin;
bool requiresReader = true;
bool requiresWriter = true;
bool requiresQuery = true;
for (int opNum = 0; opNum < opCodes.Length; opNum++)
{
if (requiresReader && !readerOpsSet.ContainsKey(opCodes[opNum]))
{
requiresReader = false;
}
if (requiresWriter && !writerOpsSet.ContainsKey(opCodes[opNum]))
{
requiresWriter = false;
}
if (requiresQuery && !queryOpsSet.ContainsKey(opCodes[opNum]))
{
requiresQuery = false;
}
}
if (requiresReader)
{
roleType = Role.Reader;
}
else if (requiresWriter)
{
roleType = Role.Writer;
}
else if (requiresQuery)
{
if (regionNames != null && regionNames.Length > 0)
{
bool queryUsers = true;
for (int index = 0; index < regionNames.Length; index++)
{
if (queryUsers && !queryRegionSet.ContainsKey(regionNames[index]))
{
queryUsers = false;
}
}
if (queryUsers)
{
roleType = Role.Query;
}
}
}
return roleType;
}
private Properties<string, string> GetUserPrincipal(string userName)
{
Properties<string, string> props = new Properties<string, string>();
props.Insert(UserPasswordAuthInit.UserNameProp, userName);
return props;
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009 Oracle. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using BerkeleyDB;
namespace ex_txn {
public class ex_txn {
private DatabaseEnvironment env;
private Database db;
private Random generator = new Random();
private bool inMem;
private string dbName, home;
private const int NUMTHREADS = 5;
public static void Main(string[] args) {
/*
* ex_txn is meant to be run from build_windows\AnyCPU,
* in either the Debug or Release directory. The
* required core libraries, however, are in either
* build_windows\Win32 or build_windows\x64, depending
* upon the platform. That location needs to be added
* to the PATH environment variable for the P/Invoke
* calls to work.
*/
try {
String pwd = Environment.CurrentDirectory;
pwd = Path.Combine(pwd, "..");
pwd = Path.Combine(pwd, "..");
pwd = Path.Combine(pwd, "..");
pwd = Path.Combine(pwd, "build_windows");
if (IntPtr.Size == 4)
pwd = Path.Combine(pwd, "Win32");
else
pwd = Path.Combine(pwd, "x64");
#if DEBUG
pwd = Path.Combine(pwd, "Debug");
#else
pwd = Path.Combine(pwd, "Release");
#endif
pwd += ";" + Environment.GetEnvironmentVariable("PATH");
Environment.SetEnvironmentVariable("PATH", pwd);
} catch (Exception e) {
Console.WriteLine(
"Unable to set the PATH environment variable.");
Console.WriteLine(e.Message);
return;
}
ex_txn obj = new ex_txn();
obj.RunExample(args);
}
private void RunExample(string[] args) {
dbName = "ex_txn.db";
home = "TESTDIR";
if (!ParseArgs(args)) {
Usage();
return;
}
try {
Open();
// Start the threads.
Thread[] threadArray = new Thread[NUMTHREADS];
for (int i = 0; i < NUMTHREADS; i++) {
threadArray[i] = new Thread(
new ThreadStart(WriteData));
threadArray[i].Name = "Thread " + i;
threadArray[i].Start();
}
for (int i = 0; i < NUMTHREADS; i++) {
threadArray[i].Join();
Console.WriteLine("Thread " + i + " finished.");
}
} catch (DatabaseException e) {
Console.WriteLine("Caught exception: {0}", e.Message);
Console.WriteLine(e.StackTrace);
} finally {
Close();
}
}
private void Open() {
Console.WriteLine("Opening environment and database");
// Set up the environment.
DatabaseEnvironmentConfig envCfg = new DatabaseEnvironmentConfig();
envCfg.Create = true;
envCfg.UseMPool = true;
envCfg.UseLocking = true;
envCfg.UseLogging = true;
envCfg.UseTxns = true;
// Allow multiple threads visit to the environment handle.
envCfg.FreeThreaded = true;
if (inMem)
envCfg.Private = true;
else
envCfg.RunRecovery = true;
/*
* Indicate that we want db to internally perform
* deadlock detection, aborting the transaction that
* has performed the least amount of WriteData activity
* in the event of a deadlock.
*/
envCfg.LockSystemCfg = new LockingConfig();
envCfg.LockSystemCfg.DeadlockResolution =
DeadlockPolicy.MIN_WRITE;
if (inMem) {
// Specify in-memory logging.
envCfg.LogSystemCfg = new LogConfig();
envCfg.LogSystemCfg.InMemory = true;
/*
* Specify the size of the in-memory log buffer
* Must be large enough to handle the log data
* created by the largest transaction.
*/
envCfg.LogSystemCfg.BufferSize = 10 * 1024 * 1024;
/*
* Specify the size of the in-memory cache,
* large enough to avoid paging to disk.
*/
envCfg.MPoolSystemCfg = new MPoolConfig();
envCfg.MPoolSystemCfg.CacheSize =
new CacheInfo(0, 10 * 1024 * 1024, 1);
}
// Set up the database.
BTreeDatabaseConfig dbCfg = new BTreeDatabaseConfig();
dbCfg.AutoCommit = true;
dbCfg.Creation = CreatePolicy.IF_NEEDED;
dbCfg.Duplicates = DuplicatesPolicy.SORTED;
dbCfg.FreeThreaded = true;
dbCfg.ReadUncommitted = true;
/*
* Open the environment. Any errors will be caught
* by the caller.
*/
env = DatabaseEnvironment.Open(home, envCfg);
/*
* Open the database. Do not provide a txn handle. This
* Open is autocommitted because BTreeDatabaseConfig.AutoCommit
* is true.
*/
dbCfg.Env = env;
db = BTreeDatabase.Open(dbName, dbCfg);
}
private void Close() {
Console.WriteLine("Closing environment and database");
if (db != null) {
try {
db.Close();
} catch (DatabaseException e) {
Console.WriteLine("Error closing db: " + e.ToString());
Console.WriteLine(e.StackTrace);
}
}
if (env != null) {
try {
env.Close();
} catch (DatabaseException e) {
Console.WriteLine("Error closing env: " + e.ToString());
Console.WriteLine(e.StackTrace);
}
}
}
/*
* This simply counts the number of records contained in the
* database and returns the result. You can use this method
* in three ways:
*
* First call it with an active txn handle.
* Secondly, configure the cursor for dirty reads
* Third, call countRecords AFTER the writer has committed
* its transaction.
*
* If you do none of these things, the writer thread will
* self-deadlock.
*
* Note that this method exists only for illustrative purposes.
* A more straight-forward way to count the number of records in
* a database is to use the Database.getStats() method.
*/
private int CountRecords(Transaction txn) {
int count = 0;
Cursor cursor = null;
try {
// Get the cursor.
CursorConfig cc = new CursorConfig();
/*
* Isolation degree one is ignored if the
* database was not opened for uncommitted
* read support. TxnGuide opens its database
* in this way and TxnGuideInMemory does not.
*/
cc.IsolationDegree = Isolation.DEGREE_ONE;
cursor = db.Cursor(cc, txn);
while (cursor.MoveNext())
count++;
} finally {
if (cursor != null)
cursor.Close();
}
return count;
}
private bool ParseArgs(string[] args) {
for (int i = 0; i < args.Length; i++) {
string s = args[i];
if (s[0] != '-') {
Console.Error.WriteLine(
"Unrecognized option: " + args[i]);
return false;
}
switch (s[1]) {
case 'h':
home = args[++i];
break;
case 'm':
inMem = true;
break;
default:
Console.Error.WriteLine(
"Unrecognized option: " + args[i]);
return false;
}
}
return true;
}
private void Usage() {
Console.WriteLine("ex_txn [-h <env directory>] [-m]");
Console.WriteLine("\t -h home (Set environment directory.)");
Console.WriteLine("\t -m (Run in memory, do not write to disk.)");
}
private void WriteData() {
/*
* Write a series of records to the database using transaction
* protection. Deadlock handling is demonstrated here.
*/
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
Random generator = new Random();
Transaction txn = null;
string[] keys = {"key 1", "key 2", "key 3", "key 4",
"key 5", "key 6", "key 7", "key 8", "key 9", "key 10"};
// Perform 20 transactions.
int iters = 0;
int retry_count = 0;
int maxRetry = 20;
while (iters < 50) {
try {
// Get a transaction.
txn = env.BeginTransaction();
// Write 10 records to the db for each transaction.
for (int j = 0; j < 10; j++) {
// Get the key.
DatabaseEntry key;
key = new DatabaseEntry(
ASCIIEncoding.ASCII.GetBytes(keys[j]));
// Get the data.
PayloadData pd = new PayloadData(
iters + j,
Thread.CurrentThread.Name,
generator.NextDouble());
formatter.Serialize(ms, pd);
Byte[] bytes = ms.GetBuffer();
DatabaseEntry data = new DatabaseEntry(bytes);
// Put key/data pair within the transaction.
db.Put(key, data, txn);
}
// Commit the transaction.
Console.WriteLine("{0} committing txn: {1}",
Thread.CurrentThread.Name, iters);
int recCount = CountRecords(inMem ? txn : null);
Console.WriteLine("{0} found {1} records in the database.",
Thread.CurrentThread.Name, recCount);
try {
txn.Commit();
txn = null;
} catch (DatabaseException e) {
Console.WriteLine(
"Error on txn commit: " +
e.ToString());
}
iters++;
retry_count = 0;
} catch (DeadlockException) {
Console.WriteLine(
"##### {0} deadlocked.", Thread.CurrentThread.Name);
// Retry if necessary.
if (retry_count < maxRetry) {
Console.WriteLine("{0} retrying.",
Thread.CurrentThread.Name);
retry_count++;
} else {
Console.WriteLine("{0} out of retries. Giving up.",
Thread.CurrentThread.Name);
iters++;
retry_count = 0;
}
} catch (DatabaseException e) {
// Abort and don't retry.
iters++;
retry_count = 0;
Console.WriteLine(Thread.CurrentThread.Name +
" : caught exception: " + e.ToString());
Console.WriteLine(Thread.CurrentThread.Name +
" : errno: " + e.ErrorCode);
Console.WriteLine(e.StackTrace);
} finally {
if (txn != null) {
try {
txn.Abort();
} catch (DatabaseException e) {
Console.WriteLine("Error aborting transaction: " +
e.ToString());
Console.WriteLine(e.StackTrace);
}
}
}
}
}
}
}
| |
#region Byline & Disclaimer
//
// Author(s):
//
// Atif Aziz (http://www.raboof.com)
//
// Portion Copyright (c) 2001 Douglas Crockford
// http://www.crockford.com
//
// 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
namespace Jazmin
{
#region Imports
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
#endregion
#region About JavaScriptCompressor (JSMin)
/*
JavaScriptCompressor is a C# port of jsmin.c that was originally written
by Douglas Crockford.
jsmin.c
04-Dec-2003
(c) 2001 Douglas Crockford
http://www.crockford.com
C# port written by Atif Aziz
12-Apr-2005
http://www.raboof.com
The following documentation is a minimal adaption from the original
found at:
http://www.crockford.com/javascript/jsmin.html
The documentation therefore still refers to JSMin, but equally
applies to this C# port since the code implementation has not been
changed or enhanced in any way. Some passages have been omitted
since they don't apply. For example, the original documentation has
a comment about character set. This does not apply to this port
since JavaScriptCompressor works with TextReader and TextWriter
from the Base Class Library (BCL). The character set responsibility
is therefore pushed back to the user of this class.
What JSMin Does
---------------
JSMin is a filter that omits or modifies some characters. This does
not change the behavior of the program that it is minifying. The
result may be harder to debug. It will definitely be harder to read.
JSMin first replaces carriage returns ('\r') with linefeeds ('\n').
It replaces all other control characters (including tab) with spaces.
It replaces comments in the // form with linefeeds. It replaces
comments with spaces. All runs of spaces are replaced with a single
space. All runs of linefeeds are replaced with a single linefeed.
It omits spaces except when a space is preceded or followed by a
non-ASCII character or by an ASCII letter or digit, or by one of
these characters:
\ $ _
It is more conservative in omitting linefeeds, because linefeeds are
sometimes treated as semicolons. A linefeed is not omitted if it
precedes a non-ASCII character or an ASCII letter or digit or one of
these characters:
\ $ _ { [ ( + -
and if it follows a non-ASCII character or an ASCII letter or digit
or one of these characters:
\ $ _ } ] ) + - " '
No other characters are omitted or modified.
JSMin knows to not modify quoted strings and regular expression
literals.
JSMin does not obfuscate, but it does uglify.
Before:
// is.js
// (c) 2001 Douglas Crockford
// 2001 June 3
// is
// The -is- object is used to identify the browser. Every browser edition
// identifies itself, but there is no standard way of doing it, and some of
// the identification is deceptive. This is because the authors of web
// browsers are liars. For example, Microsoft's IE browsers claim to be
// Mozilla 4. Netscape 6 claims to be version 5.
var is = {
ie: navigator.appName == 'Microsoft Internet Explorer',
java: navigator.javaEnabled(),
ns: navigator.appName == 'Netscape',
ua: navigator.userAgent.toLowerCase(),
version: parseFloat(navigator.appVersion.substr(21)) ||
parseFloat(navigator.appVersion),
win: navigator.platform == 'Win32'
}
is.mac = is.ua.indexOf('mac') >= 0;
if (is.ua.indexOf('opera') >= 0) {
is.ie = is.ns = false;
is.opera = true;
}
if (is.ua.indexOf('gecko') >= 0) {
is.ie = is.ns = false;
is.gecko = true;
}
After:
var is={ie:navigator.appName=='MicrosoftInternetExplorer',java:navigator.javaEnabled(),ns:navigator.appName=='Netscape',ua:navigator.userAgent.toLowerCase(),version:parseFloat(navigator.appVersion.substr(21))||parseFloat(navigator.appVersion),win:navigator.platform=='Win32'}
is.mac=is.ua.indexOf('mac')>=0;if(is.ua.indexOf('opera')>=0){is.ie=is.ns=false;is.opera=true;}
if(is.ua.indexOf('gecko')>=0){is.ie=is.ns=false;is.gecko=true;}
Caution
-------
Do not put raw control characters inside a quoted string. That is an
extremely bad practice. Use \xhh notation instead. JSMin will replace
control characters with spaces or linefeeds.
Use parens with confusing sequences of + or -. For example, minification
changes
a + ++b
into
a+++b
which is interpreted as
a++ + b
which is wrong. You can avoid this by using parens:
a + (++b)
JSLint (http://www.jslint.com/) checks for all of these problems. It is
suggested that JSLint be used before using JSMin.
Errors
------
JSMin can detect and produce three error messages:
- Unterminated comment.
- Unterminated string constant.
- Unterminated regular expression.
It ignores all other errors that may be present in your source program.
*/
#endregion
partial class JavaScriptCompressor
{
//
// Public functions
//
public static string Compress(string source)
{
var writer = new StringWriter();
Compress(new StringReader(source), writer);
return writer.ToString();
}
public static void Compress(TextReader reader, TextWriter writer)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
if (writer == null) throw new ArgumentNullException(nameof(writer));
var compressor = new JavaScriptCompressor(reader, writer);
compressor.Compress();
}
//
// Private implementation
//
int aa;
int bb;
int lookahead = eof;
readonly TextReader reader;
readonly TextWriter writer;
const int eof = -1;
JavaScriptCompressor(TextReader reader, TextWriter writer)
{
Debug.Assert(reader != null);
Debug.Assert(writer != null);
this.reader = reader;
this.writer = writer;
}
/* Compress -- Copy the input to the output, deleting the characters which are
insignificant to JavaScript. Comments will be removed. Tabs will be
replaced with spaces. Carriage returns will be replaced with linefeeds.
Most spaces and linefeeds will be removed.
*/
void Compress()
{
aa = '\n';
Action(3);
while (aa != eof)
{
switch (aa)
{
case ' ':
Action(IsAlphanum(bb) ? 1 : 2);
break;
case '\n':
switch (bb)
{
case '{':
case '[':
case '(':
case '+':
case '-':
Action(1);
break;
case ' ':
Action(3);
break;
default:
Action(IsAlphanum(bb) ? 1 : 2);
break;
}
break;
default:
switch (bb)
{
case ' ':
if (IsAlphanum(aa))
{
Action(1);
break;
}
Action(3);
break;
case '\n':
switch (aa)
{
case '}':
case ']':
case ')':
case '+':
case '-':
case '"':
case '\'':
Action(1);
break;
default:
Action(IsAlphanum(aa) ? 1 : 3);
break;
}
break;
default:
Action(1);
break;
}
break;
}
}
}
/* Get -- return the next character from stdin. Watch out for lookahead. If
the character is a control character, translate it to a space or
linefeed.
*/
int Get()
{
var ch = lookahead;
lookahead = eof;
if (ch == eof)
{
ch = reader.Read();
}
if (ch >= ' ' || ch == '\n' || ch == eof)
{
return ch;
}
if (ch == '\r')
{
return '\n';
}
return ' ';
}
/* Peek -- get the next character without getting it.
*/
int Peek() => lookahead = Get();
/* Next -- get the next character, excluding comments. Peek() is used to see
if a '/' is followed by a '/' or '*'.
*/
int Next()
{
var ch = Get();
if (ch == '/')
{
switch (Peek())
{
case '/':
for (;; )
{
ch = Get();
if (ch <= '\n')
{
return ch;
}
}
case '*':
Get();
for (;; )
{
switch (Get())
{
case '*':
if (Peek() == '/')
{
Get();
return ' ';
}
break;
case eof:
throw new Exception("Unterminated comment.");
}
}
default:
return ch;
}
}
return ch;
}
/* Action -- do something! What you do is determined by the argument:
1 Output A. Copy A to B. Get the next B.
2 Copy B to A. Get the next B. (Delete A).
3 Get the next B. (Delete B).
Action treats a string as a single character. Wow!
Action recognizes a regular expression if it is preceded by ( or , or =.
*/
void Action(int d)
{
switch (d)
{
case 1:
Write(aa);
goto case 2;
case 2:
aa = bb;
if (aa == '\'' || aa == '"')
{
for (;; )
{
Write(aa);
aa = Get();
if (aa == bb)
{
break;
}
if (aa <= '\n')
{
var message = $"Unterminated string literal: '{aa}'.";
throw new Exception(message);
}
if (aa == '\\')
{
Write(aa);
aa = Get();
}
}
}
goto case 3;
case 3:
bb = Next();
if (bb == '/' && (aa == '(' || aa == ',' || aa == '='))
{
Write(aa);
Write(bb);
for (;; )
{
aa = Get();
if (aa == '/')
{
break;
}
else if (aa == '\\')
{
Write(aa);
aa = Get();
}
else if (aa <= '\n')
{
throw new Exception("Unterminated Regular Expression literal.");
}
Write(aa);
}
bb = Next();
}
break;
}
}
void Write(int ch) => writer.Write((char) ch);
/* IsAlphanum -- return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character.
*/
static bool IsAlphanum(int ch)
=> ch >= 'a' && ch <= 'z'
|| ch >= '0' && ch <= '9'
|| ch >= 'A' && ch <= 'Z'
|| ch == '_' || ch == '$' || ch == '\\' || ch > 126;
[Serializable]
public class Exception : System.Exception
{
public Exception() {}
public Exception(string message) :
base(message) {}
public Exception(string message, System.Exception innerException) :
base(message, innerException) {}
protected Exception(SerializationInfo info, StreamingContext context) :
base(info, context) {}
}
}
}
| |
// 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 DivideSingle()
{
var test = new SimpleBinaryOpTest__DivideSingle();
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();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// 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();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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 SimpleBinaryOpTest__DivideSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public Vector256<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__DivideSingle testClass)
{
var result = Avx.Divide(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__DivideSingle testClass)
{
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
{
var result = Avx.Divide(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__DivideSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public SimpleBinaryOpTest__DivideSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Divide(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Divide(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Divide(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Divide), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Divide), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Divide), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Divide(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Single>* pClsVar1 = &_clsVar1)
fixed (Vector256<Single>* pClsVar2 = &_clsVar2)
{
var result = Avx.Divide(
Avx.LoadVector256((Single*)(pClsVar1)),
Avx.LoadVector256((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var result = Avx.Divide(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Divide(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Divide(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__DivideSingle();
var result = Avx.Divide(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__DivideSingle();
fixed (Vector256<Single>* pFld1 = &test._fld1)
fixed (Vector256<Single>* pFld2 = &test._fld2)
{
var result = Avx.Divide(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Divide(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
{
var result = Avx.Divide(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Divide(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.Divide(
Avx.LoadVector256((Single*)(&test._fld1)),
Avx.LoadVector256((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(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<Single> op1, Vector256<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(left[0] / right[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(left[i] / right[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Divide)}<Single>(Vector256<Single>, Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>CallView</c> resource.</summary>
public sealed partial class CallViewName : gax::IResourceName, sys::IEquatable<CallViewName>
{
/// <summary>The possible contents of <see cref="CallViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/callViews/{call_detail_id}</c>.
/// </summary>
CustomerCallDetail = 1,
}
private static gax::PathTemplate s_customerCallDetail = new gax::PathTemplate("customers/{customer_id}/callViews/{call_detail_id}");
/// <summary>Creates a <see cref="CallViewName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CallViewName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static CallViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CallViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CallViewName"/> with the pattern <c>customers/{customer_id}/callViews/{call_detail_id}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="callDetailId">The <c>CallDetail</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CallViewName"/> constructed from the provided ids.</returns>
public static CallViewName FromCustomerCallDetail(string customerId, string callDetailId) =>
new CallViewName(ResourceNameType.CustomerCallDetail, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), callDetailId: gax::GaxPreconditions.CheckNotNullOrEmpty(callDetailId, nameof(callDetailId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CallViewName"/> with pattern
/// <c>customers/{customer_id}/callViews/{call_detail_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="callDetailId">The <c>CallDetail</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CallViewName"/> with pattern
/// <c>customers/{customer_id}/callViews/{call_detail_id}</c>.
/// </returns>
public static string Format(string customerId, string callDetailId) =>
FormatCustomerCallDetail(customerId, callDetailId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CallViewName"/> with pattern
/// <c>customers/{customer_id}/callViews/{call_detail_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="callDetailId">The <c>CallDetail</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CallViewName"/> with pattern
/// <c>customers/{customer_id}/callViews/{call_detail_id}</c>.
/// </returns>
public static string FormatCustomerCallDetail(string customerId, string callDetailId) =>
s_customerCallDetail.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(callDetailId, nameof(callDetailId)));
/// <summary>Parses the given resource name string into a new <see cref="CallViewName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/callViews/{call_detail_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="callViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CallViewName"/> if successful.</returns>
public static CallViewName Parse(string callViewName) => Parse(callViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CallViewName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/callViews/{call_detail_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="callViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CallViewName"/> if successful.</returns>
public static CallViewName Parse(string callViewName, bool allowUnparsed) =>
TryParse(callViewName, allowUnparsed, out CallViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CallViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/callViews/{call_detail_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="callViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CallViewName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string callViewName, out CallViewName result) => TryParse(callViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CallViewName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/callViews/{call_detail_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="callViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CallViewName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string callViewName, bool allowUnparsed, out CallViewName result)
{
gax::GaxPreconditions.CheckNotNull(callViewName, nameof(callViewName));
gax::TemplatedResourceName resourceName;
if (s_customerCallDetail.TryParseName(callViewName, out resourceName))
{
result = FromCustomerCallDetail(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(callViewName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CallViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string callDetailId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CallDetailId = callDetailId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CallViewName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/callViews/{call_detail_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="callDetailId">The <c>CallDetail</c> ID. Must not be <c>null</c> or empty.</param>
public CallViewName(string customerId, string callDetailId) : this(ResourceNameType.CustomerCallDetail, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), callDetailId: gax::GaxPreconditions.CheckNotNullOrEmpty(callDetailId, nameof(callDetailId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>CallDetail</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CallDetailId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCallDetail: return s_customerCallDetail.Expand(CustomerId, CallDetailId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CallViewName);
/// <inheritdoc/>
public bool Equals(CallViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CallViewName a, CallViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CallViewName a, CallViewName b) => !(a == b);
}
public partial class CallView
{
/// <summary>
/// <see cref="CallViewName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CallViewName ResourceNameAsCallViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CallViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
// TODO: build indexes for wizard
//#define BUILD_INDEXES
namespace Antlr.Runtime.Tree
{
using System.Collections.Generic;
using IList = System.Collections.IList;
#if BUILD_INDEXES
using IDictionary = System.Collections.IDictionary;
#endif
internal class TreeWizard
{
protected ITreeAdaptor adaptor;
protected IDictionary<string, int> tokenNameToTypeMap;
internal interface IContextVisitor
{
// TODO: should this be called visit or something else?
void Visit( object t, object parent, int childIndex, IDictionary<string, object> labels );
}
internal abstract class Visitor : IContextVisitor
{
public virtual void Visit( object t, object parent, int childIndex, IDictionary<string, object> labels )
{
Visit( t );
}
public abstract void Visit( object t );
}
class ActionVisitor : Visitor
{
System.Action<object> _action;
public ActionVisitor( System.Action<object> action )
{
_action = action;
}
public override void Visit( object t )
{
_action( t );
}
}
internal class TreePattern : CommonTree
{
public string label;
public bool hasTextArg;
public TreePattern( IToken payload ) :
base( payload )
{
}
public override string ToString()
{
if ( label != null )
{
return "%" + label + ":"; //+ base.ToString();
}
else
{
return base.ToString();
}
}
}
internal class WildcardTreePattern : TreePattern
{
public WildcardTreePattern( IToken payload ) :
base( payload )
{
}
}
internal class TreePatternTreeAdaptor : CommonTreeAdaptor
{
public override object Create( IToken payload )
{
return new TreePattern( payload );
}
}
#if BUILD_INDEXES
// TODO: build indexes for the wizard
protected IDictionary<int, IList<int>> tokenTypeToStreamIndexesMap;
public static readonly HashSet<int> INDEX_ALL = new HashSet<int>();
protected HashSet<int> tokenTypesToReverseIndex = null;
#endif
public TreeWizard( ITreeAdaptor adaptor )
{
this.adaptor = adaptor;
}
public TreeWizard( ITreeAdaptor adaptor, IDictionary<string, int> tokenNameToTypeMap )
{
this.adaptor = adaptor;
this.tokenNameToTypeMap = tokenNameToTypeMap;
}
public TreeWizard( ITreeAdaptor adaptor, string[] tokenNames )
{
this.adaptor = adaptor;
this.tokenNameToTypeMap = ComputeTokenTypes( tokenNames );
}
public TreeWizard( string[] tokenNames )
: this( new CommonTreeAdaptor(), tokenNames )
{
}
public virtual IDictionary<string, int> ComputeTokenTypes( string[] tokenNames )
{
IDictionary<string, int> m = new Dictionary<string, int>();
if ( tokenNames == null )
{
return m;
}
for ( int ttype = TokenTypes.Min; ttype < tokenNames.Length; ttype++ )
{
string name = tokenNames[ttype];
m[name] = ttype;
}
return m;
}
public virtual int GetTokenType( string tokenName )
{
if ( tokenNameToTypeMap == null )
{
return TokenTypes.Invalid;
}
int value;
if ( tokenNameToTypeMap.TryGetValue( tokenName, out value ) )
return value;
return TokenTypes.Invalid;
}
public IDictionary<int, IList> Index( object t )
{
IDictionary<int, IList> m = new Dictionary<int, IList>();
IndexCore( t, m );
return m;
}
protected virtual void IndexCore( object t, IDictionary<int, IList> m )
{
if ( t == null )
{
return;
}
int ttype = adaptor.GetType( t );
IList elements;
if ( !m.TryGetValue( ttype, out elements ) || elements == null )
{
elements = new List<object>();
m[ttype] = elements;
}
elements.Add( t );
int n = adaptor.GetChildCount( t );
for ( int i = 0; i < n; i++ )
{
object child = adaptor.GetChild( t, i );
IndexCore( child, m );
}
}
class FindTreeWizardVisitor : TreeWizard.Visitor
{
IList _nodes;
public FindTreeWizardVisitor( IList nodes )
{
_nodes = nodes;
}
public override void Visit( object t )
{
_nodes.Add( t );
}
}
class FindTreeWizardContextVisitor : TreeWizard.IContextVisitor
{
TreeWizard _outer;
TreePattern _tpattern;
IList _subtrees;
public FindTreeWizardContextVisitor( TreeWizard outer, TreePattern tpattern, IList subtrees )
{
_outer = outer;
_tpattern = tpattern;
_subtrees = subtrees;
}
public void Visit( object t, object parent, int childIndex, IDictionary<string, object> labels )
{
if ( _outer.ParseCore( t, _tpattern, null ) )
{
_subtrees.Add( t );
}
}
}
public virtual IList Find( object t, int ttype )
{
IList nodes = new List<object>();
Visit( t, ttype, new FindTreeWizardVisitor( nodes ) );
return nodes;
}
public virtual IList Find( object t, string pattern )
{
IList subtrees = new List<object>();
// Create a TreePattern from the pattern
TreePatternLexer tokenizer = new TreePatternLexer( pattern );
TreePatternParser parser =
new TreePatternParser( tokenizer, this, new TreePatternTreeAdaptor() );
TreePattern tpattern = (TreePattern)parser.Pattern();
// don't allow invalid patterns
if ( tpattern == null ||
tpattern.IsNil ||
tpattern.GetType() == typeof( WildcardTreePattern ) )
{
return null;
}
int rootTokenType = tpattern.Type;
Visit( t, rootTokenType, new FindTreeWizardContextVisitor( this, tpattern, subtrees ) );
return subtrees;
}
public virtual object FindFirst( object t, int ttype )
{
return null;
}
public virtual object FindFirst( object t, string pattern )
{
return null;
}
public void Visit( object t, int ttype, IContextVisitor visitor )
{
VisitCore( t, null, 0, ttype, visitor );
}
public void Visit( object t, int ttype, System.Action<object> action )
{
Visit( t, ttype, new ActionVisitor( action ) );
}
protected virtual void VisitCore( object t, object parent, int childIndex, int ttype, IContextVisitor visitor )
{
if ( t == null )
{
return;
}
if ( adaptor.GetType( t ) == ttype )
{
visitor.Visit( t, parent, childIndex, null );
}
int n = adaptor.GetChildCount( t );
for ( int i = 0; i < n; i++ )
{
object child = adaptor.GetChild( t, i );
VisitCore( child, t, i, ttype, visitor );
}
}
class VisitTreeWizardContextVisitor : TreeWizard.IContextVisitor
{
TreeWizard _outer;
IContextVisitor _visitor;
IDictionary<string, object> _labels;
TreePattern _tpattern;
public VisitTreeWizardContextVisitor( TreeWizard outer, IContextVisitor visitor, IDictionary<string, object> labels, TreePattern tpattern )
{
_outer = outer;
_visitor = visitor;
_labels = labels;
_tpattern = tpattern;
}
public void Visit( object t, object parent, int childIndex, IDictionary<string, object> unusedlabels )
{
// the unusedlabels arg is null as visit on token type doesn't set.
_labels.Clear();
if ( _outer.ParseCore( t, _tpattern, _labels ) )
{
_visitor.Visit( t, parent, childIndex, _labels );
}
}
}
public void Visit( object t, string pattern, IContextVisitor visitor )
{
// Create a TreePattern from the pattern
TreePatternLexer tokenizer = new TreePatternLexer( pattern );
TreePatternParser parser =
new TreePatternParser( tokenizer, this, new TreePatternTreeAdaptor() );
TreePattern tpattern = (TreePattern)parser.Pattern();
// don't allow invalid patterns
if ( tpattern == null ||
tpattern.IsNil ||
tpattern.GetType() == typeof( WildcardTreePattern ) )
{
return;
}
IDictionary<string, object> labels = new Dictionary<string, object>(); // reused for each _parse
int rootTokenType = tpattern.Type;
Visit( t, rootTokenType, new VisitTreeWizardContextVisitor( this, visitor, labels, tpattern ) );
}
public bool Parse( object t, string pattern, IDictionary<string, object> labels )
{
TreePatternLexer tokenizer = new TreePatternLexer( pattern );
TreePatternParser parser =
new TreePatternParser( tokenizer, this, new TreePatternTreeAdaptor() );
TreePattern tpattern = (TreePattern)parser.Pattern();
bool matched = ParseCore( t, tpattern, labels );
return matched;
}
public bool Parse( object t, string pattern )
{
return Parse( t, pattern, null );
}
protected virtual bool ParseCore( object t1, TreePattern tpattern, IDictionary<string, object> labels )
{
// make sure both are non-null
if ( t1 == null || tpattern == null )
{
return false;
}
// check roots (wildcard matches anything)
if ( tpattern.GetType() != typeof( WildcardTreePattern ) )
{
if ( adaptor.GetType( t1 ) != tpattern.Type )
{
return false;
}
// if pattern has text, check node text
if ( tpattern.hasTextArg && !adaptor.GetText( t1 ).Equals( tpattern.Text ) )
{
return false;
}
}
if ( tpattern.label != null && labels != null )
{
// map label in pattern to node in t1
labels[tpattern.label] = t1;
}
// check children
int n1 = adaptor.GetChildCount( t1 );
int n2 = tpattern.ChildCount;
if ( n1 != n2 )
{
return false;
}
for ( int i = 0; i < n1; i++ )
{
object child1 = adaptor.GetChild( t1, i );
TreePattern child2 = (TreePattern)tpattern.GetChild( i );
if ( !ParseCore( child1, child2, labels ) )
{
return false;
}
}
return true;
}
public virtual object Create( string pattern )
{
TreePatternLexer tokenizer = new TreePatternLexer( pattern );
TreePatternParser parser = new TreePatternParser( tokenizer, this, adaptor );
object t = parser.Pattern();
return t;
}
public static bool Equals( object t1, object t2, ITreeAdaptor adaptor )
{
return EqualsCore( t1, t2, adaptor );
}
public new bool Equals( object t1, object t2 )
{
return EqualsCore( t1, t2, adaptor );
}
protected static bool EqualsCore( object t1, object t2, ITreeAdaptor adaptor )
{
// make sure both are non-null
if ( t1 == null || t2 == null )
{
return false;
}
// check roots
if ( adaptor.GetType( t1 ) != adaptor.GetType( t2 ) )
{
return false;
}
if ( !adaptor.GetText( t1 ).Equals( adaptor.GetText( t2 ) ) )
{
return false;
}
// check children
int n1 = adaptor.GetChildCount( t1 );
int n2 = adaptor.GetChildCount( t2 );
if ( n1 != n2 )
{
return false;
}
for ( int i = 0; i < n1; i++ )
{
object child1 = adaptor.GetChild( t1, i );
object child2 = adaptor.GetChild( t2, i );
if ( !EqualsCore( child1, child2, adaptor ) )
{
return false;
}
}
return true;
}
#if BUILD_INDEXES
// TODO: next stuff taken from CommonTreeNodeStream
protected void fillReverseIndex( object node, int streamIndex )
{
//System.out.println("revIndex "+node+"@"+streamIndex);
if ( tokenTypesToReverseIndex == null )
{
return; // no indexing if this is empty (nothing of interest)
}
if ( tokenTypeToStreamIndexesMap == null )
{
tokenTypeToStreamIndexesMap = new Dictionary<int, IList<int>>(); // first indexing op
}
int tokenType = adaptor.getType( node );
if ( !( tokenTypesToReverseIndex == INDEX_ALL ||
tokenTypesToReverseIndex.Contains( tokenType ) ) )
{
return; // tokenType not of interest
}
IList<int> indexes;
if ( !tokenTypeToStreamIndexesMap.TryGetValue( tokenType, out indexes ) || indexes == null )
{
indexes = new List<int>(); // no list yet for this token type
indexes.Add( streamIndex ); // not there yet, add
tokenTypeToStreamIndexesMap[tokenType] = indexes;
}
else
{
if ( !indexes.Contains( streamIndex ) )
{
indexes.Add( streamIndex ); // not there yet, add
}
}
}
public void reverseIndex( int tokenType )
{
if ( tokenTypesToReverseIndex == null )
{
tokenTypesToReverseIndex = new HashSet<int>();
}
else if ( tokenTypesToReverseIndex == INDEX_ALL )
{
return;
}
tokenTypesToReverseIndex.add( tokenType );
}
public void reverseIndex( HashSet<int> tokenTypes )
{
tokenTypesToReverseIndex = tokenTypes;
}
public int getNodeIndex( object node )
{
//System.out.println("get "+node);
if ( tokenTypeToStreamIndexesMap == null )
{
return getNodeIndexLinearly( node );
}
int tokenType = adaptor.getType( node );
IList<int> indexes;
if ( !tokenTypeToStreamIndexesMap.TryGetValue( tokenType, out indexes ) || indexes == null )
{
//System.out.println("found linearly; stream index = "+getNodeIndexLinearly(node));
return getNodeIndexLinearly( node );
}
for ( int i = 0; i < indexes.size(); i++ )
{
int streamIndex = indexes[i];
object n = get( streamIndex );
if ( n == node )
{
//System.out.println("found in index; stream index = "+streamIndexI);
return streamIndex; // found it!
}
}
return -1;
}
#endif
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Streams;
using Orleans.Configuration;
namespace Orleans.Providers
{
/// <summary>
/// Adapter factory for in memory stream provider.
/// This factory acts as the adapter and the adapter factory. The events are stored in an in-memory grain that
/// behaves as an event queue, this provider adapter is primarily used for testing
/// </summary>
public class MemoryAdapterFactory<TSerializer> : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache
where TSerializer : class, IMemoryMessageBodySerializer
{
private readonly MemoryStreamOptions options;
private readonly IGrainFactory grainFactory;
private readonly ITelemetryProducer telemetryProducer;
private readonly ILoggerFactory loggerFactory;
private readonly ILogger logger;
private readonly TSerializer serializer;
private IStreamQueueMapper streamQueueMapper;
private ConcurrentDictionary<QueueId, IMemoryStreamQueueGrain> queueGrains;
private IObjectPool<FixedSizeBuffer> bufferPool;
private BlockPoolMonitorDimensions blockPoolMonitorDimensions;
private IStreamFailureHandler streamFailureHandler;
private TimePurgePredicate purgePredicate;
/// <summary>
/// Name of the adapter. Primarily for logging purposes
/// </summary>
public string Name { get; }
/// <summary>
/// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time.
/// </summary>
/// <returns>True if this is a rewindable stream adapter, false otherwise.</returns>
public bool IsRewindable => true;
/// <summary>
/// Direction of this queue adapter: Read, Write or ReadWrite.
/// </summary>
/// <returns>The direction in which this adapter provides data.</returns>
public StreamProviderDirection Direction => StreamProviderDirection.ReadWrite;
/// <summary>
/// Creates a failure handler for a partition.
/// </summary>
protected Func<string, Task<IStreamFailureHandler>> StreamFailureHandlerFactory { get; set; }
/// <summary>
/// Create a cache monitor to report cache related metrics
/// Return a ICacheMonitor
/// </summary>
protected Func<CacheMonitorDimensions, ITelemetryProducer, ICacheMonitor> CacheMonitorFactory;
/// <summary>
/// Create a block pool monitor to monitor block pool related metrics
/// Return a IBlockPoolMonitor
/// </summary>
protected Func<BlockPoolMonitorDimensions, ITelemetryProducer, IBlockPoolMonitor> BlockPoolMonitorFactory;
/// <summary>
/// Create a monitor to monitor QueueAdapterReceiver related metrics
/// Return a IQueueAdapterReceiverMonitor
/// </summary>
protected Func<ReceiverMonitorDimensions, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory;
public MemoryAdapterFactory(string providerName, MemoryStreamOptions options, IServiceProvider serviceProvider, IGrainFactory grainFactory, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory)
{
this.Name = providerName;
this.options = options ?? throw new ArgumentNullException(nameof(options));
this.grainFactory = grainFactory ?? throw new ArgumentNullException(nameof(grainFactory));
this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer));
this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
this.logger = loggerFactory.CreateLogger<ILogger<MemoryAdapterFactory<TSerializer>>>();
this.serializer = MemoryMessageBodySerializerFactory<TSerializer>.GetOrCreateSerializer(serviceProvider);
}
/// <summary>
/// Factory initialization.
/// </summary>
/// <param name="providerConfig"></param>
/// <param name="name"></param>
/// <param name="svcProvider"></param>
public void Init()
{
this.queueGrains = new ConcurrentDictionary<QueueId, IMemoryStreamQueueGrain>();
if (CacheMonitorFactory == null)
this.CacheMonitorFactory = (dimensions, telemetryProducer) => new DefaultCacheMonitor(dimensions, telemetryProducer);
if (this.BlockPoolMonitorFactory == null)
this.BlockPoolMonitorFactory = (dimensions, telemetryProducer) => new DefaultBlockPoolMonitor(dimensions, telemetryProducer);
if (this.ReceiverMonitorFactory == null)
this.ReceiverMonitorFactory = (dimensions, telemetryProducer) => new DefaultQueueAdapterReceiverMonitor(dimensions, telemetryProducer);
this.purgePredicate = new TimePurgePredicate(this.options.DataMinTimeInCache, this.options.DataMaxAgeInCache);
this.streamQueueMapper = new HashRingBasedStreamQueueMapper(this.options.TotalQueueCount, this.Name);
}
private void CreateBufferPoolIfNotCreatedYet()
{
if (this.bufferPool == null)
{
// 1 meg block size pool
this.blockPoolMonitorDimensions = new BlockPoolMonitorDimensions($"BlockPool-{Guid.NewGuid()}");
var oneMb = 1 << 20;
var objectPoolMonitor = new ObjectPoolMonitorBridge(this.BlockPoolMonitorFactory(blockPoolMonitorDimensions, this.telemetryProducer), oneMb);
this.bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(oneMb), objectPoolMonitor, this.options.StatisticMonitorWriteInterval);
}
}
/// <summary>
/// Create queue adapter.
/// </summary>
/// <returns></returns>
public Task<IQueueAdapter> CreateAdapter()
{
return Task.FromResult<IQueueAdapter>(this);
}
/// <summary>
/// Create queue message cache adapter
/// </summary>
/// <returns></returns>
public IQueueAdapterCache GetQueueAdapterCache()
{
return this;
}
/// <summary>
/// Create queue mapper
/// </summary>
/// <returns></returns>
public IStreamQueueMapper GetStreamQueueMapper()
{
return streamQueueMapper;
}
/// <summary>
/// Creates a quere receiver for the specificed queueId
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public IQueueAdapterReceiver CreateReceiver(QueueId queueId)
{
var dimensions = new ReceiverMonitorDimensions(queueId.ToString());
var receiverLogger = this.loggerFactory.CreateLogger($"{typeof(MemoryAdapterReceiver<TSerializer>).FullName}.{this.Name}.{queueId}");
var receiverMonitor = this.ReceiverMonitorFactory(dimensions, this.telemetryProducer);
IQueueAdapterReceiver receiver = new MemoryAdapterReceiver<TSerializer>(GetQueueGrain(queueId), receiverLogger, this.serializer, receiverMonitor);
return receiver;
}
/// <summary>
/// Writes a set of events to the queue as a single batch associated with the provided streamId.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="streamGuid"></param>
/// <param name="streamNamespace"></param>
/// <param name="events"></param>
/// <param name="token"></param>
/// <param name="requestContext"></param>
/// <returns></returns>
public async Task QueueMessageBatchAsync<T>(Guid streamGuid, string streamNamespace, IEnumerable<T> events, StreamSequenceToken token, Dictionary<string, object> requestContext)
{
try
{
var queueId = streamQueueMapper.GetQueueForStream(streamGuid, streamNamespace);
ArraySegment<byte> bodyBytes = serializer.Serialize(new MemoryMessageBody(events.Cast<object>(), requestContext));
var messageData = MemoryMessageData.Create(streamGuid, streamNamespace, bodyBytes);
IMemoryStreamQueueGrain queueGrain = GetQueueGrain(queueId);
await queueGrain.Enqueue(messageData);
}
catch (Exception exc)
{
logger.Error((int)ProviderErrorCode.MemoryStreamProviderBase_QueueMessageBatchAsync, "Exception thrown in MemoryAdapterFactory.QueueMessageBatchAsync.", exc);
throw;
}
}
/// <summary>
/// Create a cache for a given queue id
/// </summary>
/// <param name="queueId"></param>
public IQueueCache CreateQueueCache(QueueId queueId)
{
//move block pool creation from init method to here, to avoid unnecessary block pool creation when stream provider is initialized in client side.
CreateBufferPoolIfNotCreatedYet();
var logger = this.loggerFactory.CreateLogger($"{typeof(MemoryPooledCache<TSerializer>).FullName}.{this.Name}.{queueId}");
var monitor = this.CacheMonitorFactory(new CacheMonitorDimensions(queueId.ToString(), this.blockPoolMonitorDimensions.BlockPoolId), this.telemetryProducer);
return new MemoryPooledCache<TSerializer>(bufferPool, purgePredicate, logger, this.serializer, monitor, this.options.StatisticMonitorWriteInterval);
}
/// <summary>
/// Acquire delivery failure handler for a queue
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId)
{
return Task.FromResult(streamFailureHandler ?? (streamFailureHandler = new NoOpStreamDeliveryFailureHandler()));
}
/// <summary>
/// Generate a deterministic Guid from a queue Id.
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
private Guid GenerateDeterministicGuid(QueueId queueId)
{
// provider name hash code
int providerNameGuidHash = (int)JenkinsHash.ComputeHash(this.Name);
// get queueId hash code
uint queueIdHash = queueId.GetUniformHashCode();
byte[] queIdHashByes = BitConverter.GetBytes(queueIdHash);
short s1 = BitConverter.ToInt16(queIdHashByes, 0);
short s2 = BitConverter.ToInt16(queIdHashByes, 2);
// build guid tailing 8 bytes from providerNameGuidHash and queIdHashByes.
var tail = new List<byte>();
tail.AddRange(BitConverter.GetBytes(providerNameGuidHash));
tail.AddRange(queIdHashByes);
// make guid.
// - First int is provider name hash
// - Two shorts from queue Id hash
// - 8 byte tail from provider name hash and queue Id hash.
return new Guid(providerNameGuidHash, s1, s2, tail.ToArray());
}
/// <summary>
/// Get a MemoryStreamQueueGrain instance by queue Id.
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
private IMemoryStreamQueueGrain GetQueueGrain(QueueId queueId)
{
return queueGrains.GetOrAdd(queueId, grainFactory.GetGrain<IMemoryStreamQueueGrain>(GenerateDeterministicGuid(queueId)));
}
public static MemoryAdapterFactory<TSerializer> Create(IServiceProvider services, string name)
{
IOptionsSnapshot<MemoryStreamOptions> optionsSnapshot = services.GetRequiredService<IOptionsSnapshot<MemoryStreamOptions>>();
var factory = ActivatorUtilities.CreateInstance<MemoryAdapterFactory<TSerializer>>(services, name, optionsSnapshot.Get(name));
factory.Init();
return factory;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.IO;
namespace Eto.Parse
{
#if PCL
public class IndentedTextWriter : TextWriter
{
bool needsIndent = true;
public const string DefaultTabString = " ";
string tabString;
public int Indent { get; set; }
public TextWriter InnerWriter { get; private set; }
public IndentedTextWriter(TextWriter writer)
: this(writer, DefaultTabString)
{
}
public IndentedTextWriter(TextWriter writer, string tabString)
{
this.InnerWriter = writer;
this.tabString = tabString;
}
public override void Write(char value)
{
InnerWriter.Write(value);
}
public override void Write(bool value)
{
WriteIndent();
InnerWriter.Write(value);
}
public override void Write(char[] buffer)
{
WriteIndent();
InnerWriter.Write(buffer);
}
public override void Write(char[] buffer, int index, int count)
{
WriteIndent();
InnerWriter.Write(buffer, index, count);
}
public override void Write(decimal value)
{
WriteIndent();
InnerWriter.Write(value);
}
public override void Write(double value)
{
WriteIndent();
InnerWriter.Write(value);
}
public override void Write(float value)
{
WriteIndent();
InnerWriter.Write(value);
}
public override void Write(int value)
{
WriteIndent();
InnerWriter.Write(value);
}
public override void Write(long value)
{
WriteIndent();
InnerWriter.Write(value);
}
public override void Write(object value)
{
WriteIndent();
InnerWriter.Write(value);
}
public override void Write(string format, params object[] arg)
{
WriteIndent();
InnerWriter.Write(format, arg);
}
public override void Write(string value)
{
WriteIndent();
InnerWriter.Write(value);
}
public override void Write(uint value)
{
WriteIndent();
InnerWriter.Write(value);
}
public override void Write(ulong value)
{
WriteIndent();
InnerWriter.Write(value);
}
public override void WriteLine()
{
WriteIndent();
InnerWriter.WriteLine();
needsIndent = true;
}
public override void WriteLine(bool value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
public override void WriteLine(char value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
public override void WriteLine(char[] buffer)
{
WriteIndent();
InnerWriter.WriteLine(buffer);
needsIndent = true;
}
public override void WriteLine(char[] buffer, int index, int count)
{
WriteIndent();
InnerWriter.WriteLine(buffer, index, count);
needsIndent = true;
}
public override void WriteLine(decimal value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
public override void WriteLine(double value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
public override void WriteLine(float value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
public override void WriteLine(int value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
public override void WriteLine(long value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
public override void WriteLine(object value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
public override void WriteLine(string format, params object[] arg)
{
WriteIndent();
InnerWriter.WriteLine(format, arg);
needsIndent = true;
}
public override void WriteLine(string value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
public override void WriteLine(uint value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
public override void WriteLine(ulong value)
{
WriteIndent();
InnerWriter.WriteLine(value);
needsIndent = true;
}
void WriteIndent()
{
if (needsIndent)
{
for (int i = 0; i < Indent; i++)
{
InnerWriter.Write(tabString);
}
}
}
public override string NewLine
{
get { return InnerWriter.NewLine; }
set { InnerWriter.NewLine = value; }
}
public override void Flush()
{
InnerWriter.Flush();
}
public override System.Threading.Tasks.Task FlushAsync()
{
return InnerWriter.FlushAsync();
}
public override IFormatProvider FormatProvider
{
get { return InnerWriter.FormatProvider; }
}
protected override void Dispose(bool disposing)
{
if (disposing && InnerWriter != null)
{
InnerWriter.Dispose();
InnerWriter = null;
}
base.Dispose(disposing);
}
public override System.Text.Encoding Encoding
{
get { return InnerWriter.Encoding; }
}
}
#endif
}
| |
using UnityEngine;
using UnityEngine.Events;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NewtonVR
{
public class NVRHand : MonoBehaviour
{
public NVRButtons HoldButton = NVRButtons.Grip;
public bool HoldButtonDown { get { return Inputs[HoldButton].PressDown; } }
public bool HoldButtonUp { get { return Inputs[HoldButton].PressUp; } }
public bool HoldButtonPressed { get { return Inputs[HoldButton].IsPressed; } }
public float HoldButtonAxis { get { return Inputs[HoldButton].SingleAxis; } }
public bool UseTwoButtonsToHold = true; // Player can hold an object by pressing either of two buttons
public NVRButtons SecondHoldButton = NVRButtons.Grip;
public bool SecondHoldButtonDown { get { return Inputs[SecondHoldButton].PressDown; } }
public bool SecondHoldButtonUp { get { return Inputs[SecondHoldButton].PressUp; } }
public bool SecondHoldButtonPressed { get { return Inputs[SecondHoldButton].IsPressed; } }
public float SecondHoldButtonAxis { get { return Inputs[SecondHoldButton].SingleAxis; } }
public NVRButtons UseButton = NVRButtons.Trigger;
public bool UseButtonDown { get { return Inputs[UseButton].PressDown; } }
public bool UseButtonUp { get { return Inputs[UseButton].PressUp; } }
public bool UseButtonPressed { get { return Inputs[UseButton].IsPressed; } }
public float UseButtonAxis { get { return Inputs[UseButton].SingleAxis; } }
public NVRButtons TouchPadButton = NVRButtons.Touchpad;
public Vector2 TouchPadPosition { get { return Inputs[TouchPadButton].Axis; } }
public bool UseTouchPad
{
get
{
return Inputs[TouchPadButton].IsTouched
#if NVR_Gear
|| Inputs[TouchPadButton].Axis != Vector2.zero
#endif
;
}
}
public bool TouchPadDown { get { return Inputs[TouchPadButton].TouchDown; } }
public bool TouchPadClickDown { get { return Inputs[TouchPadButton].PressDown; } }
public NVRButtons RemoteCentreButton = NVRButtons.A;
public bool RemoteCentreClickDown { get { return Inputs[RemoteCentreButton].PressDown; } }
// menu
public NVRButtons MenuButton1 = NVRButtons.Y;
public NVRButtons MenuButton2 = NVRButtons.B;
public NVRButtons MenuButton3 = NVRButtons.ApplicationMenu;
public bool MenuButtonDown { get { return Inputs[MenuButton1].PressDown || Inputs[MenuButton2].PressDown || Inputs[MenuButton3].PressDown; } }
public bool MenuButtonUp { get { return Inputs[MenuButton1].PressUp || Inputs[MenuButton2].PressUp || Inputs[MenuButton3].PressUp; } }
[HideInInspector]
public bool AbleToInteract = true;
[HideInInspector]
public bool IsRight;
[HideInInspector]
public bool IsLeft;
[HideInInspector]
public NVRPlayer Player;
public Dictionary<NVRButtons, NVRButtonInputs> Inputs;
[HideInInspector]
public InterationStyle CurrentInteractionStyle;
public Rigidbody Rigidbody;
[HideInInspector]
public GameObject CustomModel;
[HideInInspector]
public GameObject CustomPhysicalColliders;
private VisibilityLevel CurrentVisibility = VisibilityLevel.Visible;
private bool VisibilityLocked = false;
[HideInInspector]
public HandState CurrentHandState = HandState.Uninitialized;
[HideInInspector]
public Dictionary<NVRInteractable, Dictionary<Collider, float>> CurrentlyHoveringOver;
public NVRInteractable CurrentlyInteracting;
[Serializable]
public class NVRInteractableEvent : UnityEvent<NVRInteractable> { }
public NVRInteractableEvent OnBeginInteraction = new NVRInteractableEvent();
public NVRInteractableEvent OnEndInteraction = new NVRInteractableEvent();
//////// DA: add extra event callbacks for custom hands ////////
public NVRInteractableEvent OnBeginInteractionCustomHands = new NVRInteractableEvent();
public NVRInteractableEvent OnEndInteractionCustomHands = new NVRInteractableEvent();
[Serializable]
public class NVRCanInteractEvent : UnityEvent<bool> { }
public NVRCanInteractEvent OnChangeCanInteract = new NVRCanInteractEvent();
[Serializable]
public class NVRIsHoveringEvent : UnityEvent<bool> { }
public NVRIsHoveringEvent OnChangeIsHovering = new NVRIsHoveringEvent();
[Serializable]
public class NVRIsGrabbingEvent : UnityEvent<bool> { }
public NVRIsGrabbingEvent OnChangeIsGrabbing = new NVRIsGrabbingEvent();
public UnityEvent OnUnfreezeHand = new UnityEvent();
//////// END added event callbacks for custom hands ////////
private int EstimationSampleIndex;
private Vector3[] LastPositions;
private Quaternion[] LastRotations;
private float[] LastDeltas;
private int EstimationSamples = 5;
[HideInInspector]
public NVRPhysicalController PhysicalController;
private Collider[] GhostColliders;
private Renderer[] GhostRenderers;
private NVRInputDevice InputDevice;
private NVRInputDevice AlternativeInputDevice;
private GameObject RenderModel;
private bool m_wasHovering = false; //DA: add to stop ishovering callbacks from triggering every frame, trigger only when change occurs
public NVRInputDevice CurrentInputDevice
{
get { return InputDevice; }
set { InputDevice = value; }
}
public bool IsHovering
{
get
{
var hoveringEnumerator = CurrentlyHoveringOver.GetEnumerator();
while (hoveringEnumerator.MoveNext())
{
var kvp = hoveringEnumerator.Current;
if (kvp.Value.Count > 0)
return true;
}
return false;
}
}
public bool WasHovering
{
get { return m_wasHovering; }
set { m_wasHovering = value; }
}
public bool IsInteracting
{
get
{
return CurrentlyInteracting != null;
}
}
public bool HasCustomModel
{
get
{
return CustomModel != null;
}
}
public bool IsCurrentlyTracked
{
get
{
if (InputDevice != null)
{
return InputDevice.IsCurrentlyTracked;
}
return false;
}
}
public Vector3 CurrentForward
{
get
{
if (PhysicalController != null && PhysicalController.State == true)
{
return PhysicalController.PhysicalController.transform.forward;
}
else
{
return this.transform.forward;
}
}
}
public Vector3 CurrentPosition
{
get
{
if (PhysicalController != null && PhysicalController.State == true)
{
return PhysicalController.PhysicalController.transform.position;
}
else
{
return this.transform.position;
}
}
}
public virtual void PreInitialize(NVRPlayer player)
{
Player = player;
IsRight = Player.RightHand == this;
IsLeft = Player.LeftHand == this;
CurrentInteractionStyle = Player.InteractionStyle;
CurrentlyHoveringOver = new Dictionary<NVRInteractable, Dictionary<Collider, float>>();
LastPositions = new Vector3[EstimationSamples];
LastRotations = new Quaternion[EstimationSamples];
LastDeltas = new float[EstimationSamples];
EstimationSampleIndex = 0;
VisibilityLocked = false;
Inputs = new Dictionary<NVRButtons, NVRButtonInputs>(new NVRButtonsComparer());
for (int buttonIndex = 0; buttonIndex < NVRButtonsHelper.Array.Length; buttonIndex++)
{
if (Inputs.ContainsKey(NVRButtonsHelper.Array[buttonIndex]) == false)
{
Inputs.Add(NVRButtonsHelper.Array[buttonIndex], new NVRButtonInputs());
}
}
if (Player.CurrentIntegrationType == NVRSDKIntegrations.Oculus)
{
AlternativeInputDevice = this.gameObject.AddComponent<NVRRemoteOculusInputDevice>();
AlternativeInputDevice.Initialize(this);
InputDevice = this.gameObject.AddComponent<NVROculusInputDevice>();
if (Player.OverrideOculus == true)
{
if (IsLeft)
{
CustomModel = Player.OverrideOculusLeftHand;
CustomPhysicalColliders = Player.OverrideOculusLeftHandPhysicalColliders;
}
else if (IsRight)
{
CustomModel = Player.OverrideOculusRightHand;
CustomPhysicalColliders = Player.OverrideOculusRightHandPhysicalColliders;
}
else
{
Debug.LogError("[NewtonVR] Error: Unknown hand for oculus model override.");
}
}
}
else if (Player.CurrentIntegrationType == NVRSDKIntegrations.Gear)
{
InputDevice = this.gameObject.AddComponent<NVRGearInputDevice>();
}
else if (Player.CurrentIntegrationType == NVRSDKIntegrations.SteamVR)
{
InputDevice = this.gameObject.AddComponent<NVRSteamVRInputDevice>();
if (Player.OverrideSteamVR == true)
{
if (IsLeft)
{
CustomModel = Player.OverrideSteamVRLeftHand;
CustomPhysicalColliders = Player.OverrideSteamVRLeftHandPhysicalColliders;
}
else if (IsRight)
{
CustomModel = Player.OverrideSteamVRRightHand;
CustomPhysicalColliders = Player.OverrideSteamVRRightHandPhysicalColliders;
}
else
{
Debug.LogError("[NewtonVR] Error: Unknown hand for SteamVR model override.");
}
}
}
else if (Player.CurrentIntegrationType == NVRSDKIntegrations.Daydream)
{
InputDevice = this.gameObject.AddComponent<NVRDaydreamInputDevice>();
}
else
{
//Debug.LogError("[NewtonVR] Critical Error: NVRPlayer.CurrentIntegration not setup.");
return;
}
if (Player.OverrideAll)
{
if (IsLeft)
{
CustomModel = Player.OverrideAllLeftHand;
CustomPhysicalColliders = Player.OverrideAllLeftHandPhysicalColliders;
}
else if (IsRight)
{
CustomModel = Player.OverrideAllRightHand;
CustomPhysicalColliders = Player.OverrideAllRightHandPhysicalColliders;
}
else
{
Debug.LogError("[NewtonVR] Error: Unknown hand for SteamVR model override.");
return;
}
}
if(UseTwoButtonsToHold && (HoldButton == SecondHoldButton))
{
Debug.LogWarning("NVRHand setup wrong. HoldButton and SecondHoldButton are the same.");
}
InputDevice.Initialize(this);
InitializeRenderModel();
//UpdateOculusController();
}
protected virtual void Update()
{
if (CurrentHandState == HandState.Uninitialized)
{
if (InputDevice == null || InputDevice.ReadyToInitialize() == false)
{
return;
}
else
{
Initialize();
//UpdateOculusController();
return;
}
}
UpdateButtonStates();
UpdateInteractions();
UpdateHovering();
UpdateVisibilityAndColliders();
}
public void UseRemoteInput(bool _useRemote){
if (_useRemote && InputDevice == AlternativeInputDevice)
return;
InputDevice = _useRemote ? AlternativeInputDevice : GetComponent<NVROculusInputDevice>();
SkinnedMeshRenderer handSkin = GetComponentInChildren<SkinnedMeshRenderer> ();
handSkin.enabled = !_useRemote;
Collider[] handColliders = GetComponentsInChildren<Collider>();
for (int i = 0; i < handColliders.Length; i++)
{
handColliders[i].enabled = !_useRemote;
}
if(_useRemote)
{
Animator[] allAnimators = GetComponentsInChildren<Animator>();
if(allAnimators.Length > 0)
{
foreach(var item in allAnimators)
{
item.enabled = false;
}
}
}
}
protected void UpdateHovering()
{
if (CurrentHandState == HandState.Idle)
{
var hoveringEnumerator = CurrentlyHoveringOver.GetEnumerator();
while (hoveringEnumerator.MoveNext())
{
var hoveringOver = hoveringEnumerator.Current;
if (hoveringOver.Value.Count > 0)
{
hoveringOver.Key.HoveringUpdate(this, Time.time - hoveringOver.Value.OrderBy(colliderTime => colliderTime.Value).First().Value);
}
}
}
if (InputDevice != null && IsInteracting == false && IsHovering == true)
{
if (Player.VibrateOnHover == true && WasHovering == false)
{
WasHovering = true;
// Implemented hand controller should subscribe to this event and implement appropriate functionality
OnChangeIsHovering.Invoke(true);
}
}
else if (IsHovering == false && WasHovering == true)
{
WasHovering = false;
// Implemented hand controller should subscribe to this event and implement appropriate functionality
OnChangeIsHovering.Invoke(false);
}
}
protected void UpdateButtonStates()
{
for (int index = 0; index < NVRButtonsHelper.Array.Length; index++)
{
NVRButtons nvrbutton = NVRButtonsHelper.Array[index];
NVRButtonInputs button = Inputs[nvrbutton];
button.FrameReset(InputDevice, nvrbutton);
}
}
protected void UpdateInteractions()
{
if(!AbleToInteract)
{
if (CurrentInteractionStyle == InterationStyle.Hold)
{
bool isHoldButtonUp = (HoldButtonUp && !SecondHoldButtonPressed);
bool isSecondHoldButtonUp = (SecondHoldButtonUp && !HoldButtonPressed);
bool isUsingTwoButtonsUp = UseTwoButtonsToHold && (isHoldButtonUp || isSecondHoldButtonUp);
bool isUsingSingleButtonUp = !UseTwoButtonsToHold && HoldButtonUp;
if (isUsingSingleButtonUp || isUsingTwoButtonsUp)
{
// Implemented hand controller should subscribe to this event and implement appropriate functionality
OnChangeIsGrabbing.Invoke(false);
}
}
bool isUsingSingleButtonDown = !UseTwoButtonsToHold && HoldButtonDown;
bool isUsingTwoButtonsDown = UseTwoButtonsToHold && (HoldButtonDown || SecondHoldButtonDown);
if (isUsingSingleButtonDown || isUsingTwoButtonsDown)
{
// Implemented hand controller should subscribe to this event and implement appropriate functionality
OnChangeIsGrabbing.Invoke(true);
}
return;
}
if (CurrentInteractionStyle == InterationStyle.Hold)
{
bool isHoldButtonUp = (HoldButtonUp && !SecondHoldButtonPressed);
bool isSecondHoldButtonUp = (SecondHoldButtonUp && !HoldButtonPressed);
bool isUsingTwoButtonsUp = UseTwoButtonsToHold && (isHoldButtonUp || isSecondHoldButtonUp);
bool isUsingSingleButtonUp = !UseTwoButtonsToHold && HoldButtonUp;
if (isUsingSingleButtonUp || isUsingTwoButtonsUp)
{
VisibilityLocked = false;
// Implemented hand controller should subscribe to this event and implement appropriate functionality
OnChangeIsGrabbing.Invoke(false);
OnUnfreezeHand.Invoke();
}
bool isUsingSingleButtonDown = !UseTwoButtonsToHold && HoldButtonDown;
bool isUsingTwoButtonsDown = UseTwoButtonsToHold && (HoldButtonDown || SecondHoldButtonDown);
if (isUsingSingleButtonDown || isUsingTwoButtonsDown)
{
// Implemented hand controller should subscribe to this event and implement appropriate functionality
OnChangeIsGrabbing.Invoke(true);
if (CurrentlyInteracting == null)
{
PickupClosest();
}
}
else if ((isUsingSingleButtonUp || isUsingTwoButtonsUp) && CurrentlyInteracting != null)
{
EndInteraction(null);
}
}
else if (CurrentInteractionStyle == InterationStyle.Toggle)
{
bool isUsingSingleButtonDown = !UseTwoButtonsToHold && HoldButtonDown;
bool isUsingTwoButtonsDown = UseTwoButtonsToHold && (HoldButtonDown || SecondHoldButtonDown);
if (isUsingSingleButtonDown || isUsingTwoButtonsDown)
{
if (CurrentHandState == HandState.Idle)
{
PickupClosest();
if (IsInteracting)
{
CurrentHandState = HandState.GripToggleOnInteracting;
}
else if (Player.PhysicalHands == true)
{
CurrentHandState = HandState.GripToggleOnNotInteracting;
}
}
else if (CurrentHandState == HandState.GripToggleOnInteracting)
{
CurrentHandState = HandState.Idle;
VisibilityLocked = false;
EndInteraction(null);
}
else if (CurrentHandState == HandState.GripToggleOnNotInteracting)
{
CurrentHandState = HandState.Idle;
VisibilityLocked = false;
}
}
}
else if (CurrentInteractionStyle == InterationStyle.ByScript)
{
//this is handled by user customized scripts.
}
if (IsInteracting == true)
{
CurrentlyInteracting.InteractingUpdate(this);
}
}
private void UpdateVisibilityAndColliders()
{
if (Player.PhysicalHands == true)
{
if (CurrentInteractionStyle == InterationStyle.Hold)
{
if (HoldButtonPressed == true && IsInteracting == false)
{
if (CurrentHandState != HandState.GripDownNotInteracting && VisibilityLocked == false)
{
VisibilityLocked = true;
SetVisibility(VisibilityLevel.Visible);
CurrentHandState = HandState.GripDownNotInteracting;
}
}
else if ((HoldButtonDown || SecondHoldButtonDown) && IsInteracting == true)
{
if (CurrentHandState != HandState.GripDownInteracting && VisibilityLocked == false)
{
VisibilityLocked = true;
if (Player.MakeControllerInvisibleOnInteraction == true)
{
SetVisibility(VisibilityLevel.Invisible);
}
else
{
SetVisibility(VisibilityLevel.Ghost);
}
CurrentHandState = HandState.GripDownInteracting;
}
}
else if (IsInteracting == false)
{
if (CurrentHandState != HandState.Idle && VisibilityLocked == false)
{
SetVisibility(VisibilityLevel.Ghost);
CurrentHandState = HandState.Idle;
}
}
}
else if (CurrentInteractionStyle == InterationStyle.Toggle)
{
if (CurrentHandState == HandState.Idle)
{
if (VisibilityLocked == false && CurrentVisibility != VisibilityLevel.Ghost)
{
SetVisibility(VisibilityLevel.Ghost);
}
else
{
VisibilityLocked = false;
}
}
else if (CurrentHandState == HandState.GripToggleOnInteracting)
{
if (VisibilityLocked == false)
{
VisibilityLocked = true;
SetVisibility(VisibilityLevel.Ghost);
}
}
else if (CurrentHandState == HandState.GripToggleOnNotInteracting)
{
if (VisibilityLocked == false)
{
VisibilityLocked = true;
SetVisibility(VisibilityLevel.Visible);
}
}
}
}
else if (Player.PhysicalHands == false && Player.MakeControllerInvisibleOnInteraction == true)
{
if (IsInteracting == true)
{
SetVisibility(VisibilityLevel.Invisible);
}
else if (IsInteracting == false)
{
SetVisibility(VisibilityLevel.Ghost);
}
}
}
public void TriggerHapticPulse(ushort durationMicroSec = 500, NVRButtons button = NVRButtons.Grip)
{
if (InputDevice != null)
{
if (durationMicroSec < 3000)
{
InputDevice.TriggerHapticPulse(durationMicroSec, button);
}
else
{
Debug.LogWarning("You're trying to pulse for over 3000 microseconds, you probably don't want to do that. If you do, use NVRHand.LongHapticPulse(float seconds)");
}
}
}
public void LongHapticPulse(float seconds, NVRButtons button = NVRButtons.Grip)
{
StartCoroutine(DoLongHapticPulse(seconds, button));
}
private IEnumerator DoLongHapticPulse(float seconds, NVRButtons button)
{
float startTime = Time.time;
float endTime = startTime + seconds;
while (Time.time < endTime)
{
TriggerHapticPulse(100, button);
yield return null;
}
}
public Vector3 GetVelocityEstimation()
{
float delta = LastDeltas.Sum();
Vector3 distance = Vector3.zero;
for (int index = 0; index < LastPositions.Length - 1; index++)
{
Vector3 diff = LastPositions[index + 1] - LastPositions[index];
distance += diff;
}
return distance / delta;
}
public Vector3 GetAngularVelocityEstimation()
{
float delta = LastDeltas.Sum();
float angleDegrees = 0.0f;
Vector3 unitAxis = Vector3.zero;
Quaternion rotation = Quaternion.identity;
rotation = LastRotations[LastRotations.Length - 1] * Quaternion.Inverse(LastRotations[LastRotations.Length - 2]);
//Error: the incorrect rotation is sometimes returned
rotation.ToAngleAxis(out angleDegrees, out unitAxis);
return unitAxis * ((angleDegrees * Mathf.Deg2Rad) / delta);
}
public Vector3 GetPositionDelta()
{
int last = EstimationSampleIndex - 1;
int secondToLast = EstimationSampleIndex - 2;
if (last < 0)
last += EstimationSamples;
if (secondToLast < 0)
secondToLast += EstimationSamples;
return LastPositions[last] - LastPositions[secondToLast];
}
public Quaternion GetRotationDelta()
{
int last = EstimationSampleIndex - 1;
int secondToLast = EstimationSampleIndex - 2;
if (last < 0)
last += EstimationSamples;
if (secondToLast < 0)
secondToLast += EstimationSamples;
return LastRotations[last] * Quaternion.Inverse(LastRotations[secondToLast]);
}
protected virtual void FixedUpdate()
{
if (CurrentHandState == HandState.Uninitialized)
{
return;
}
LastPositions[EstimationSampleIndex] = this.transform.position;
LastRotations[EstimationSampleIndex] = this.transform.rotation;
LastDeltas[EstimationSampleIndex] = Time.deltaTime;
EstimationSampleIndex++;
if (EstimationSampleIndex >= LastPositions.Length)
EstimationSampleIndex = 0;
}
public virtual void BeginInteraction(NVRInteractable interactable)
{
if (interactable.CanAttach == true)
{
// Implemented hand controller should subscribe to this event and implement appropriate functionality
OnBeginInteractionCustomHands.Invoke(interactable);
CurrentlyInteracting = interactable;
CurrentlyInteracting.BeginInteraction(this);
if (PhysicalController)
{
PhysicalController.On(); // enable animation with Phyiscal Hand component during interaction
}
if (OnBeginInteraction != null)
{
OnBeginInteraction.Invoke(interactable);
}
}
}
public virtual void EndInteraction(NVRInteractable item)
{
if (item != null && CurrentlyHoveringOver.ContainsKey(item) == true)
CurrentlyHoveringOver.Remove(item);
if (CurrentlyInteracting != null)
{
// Implemented hand controller should subscribe to this event and implement appropriate functionality
OnEndInteractionCustomHands.Invoke(CurrentlyInteracting);
CurrentlyInteracting.EndInteraction(this);
if (OnEndInteraction != null)
{
OnEndInteraction.Invoke(CurrentlyInteracting);
}
if (PhysicalController)
{
PhysicalController.Off(); // disable Phyiscal Hand component after interaction
}
CurrentlyInteracting = null;
}
if (CurrentInteractionStyle == InterationStyle.Toggle)
{
if (CurrentHandState != HandState.Idle)
{
CurrentHandState = HandState.Idle;
}
}
}
private bool PickupClosest()
{
NVRInteractable closest = null;
float closestDistance = float.MaxValue;
foreach (var hovering in CurrentlyHoveringOver)
{
if (hovering.Key == null)
continue;
float distance = Vector3.Distance(this.transform.position, hovering.Key.transform.position);
if (distance < closestDistance)
{
closestDistance = distance;
closest = hovering.Key;
}
}
if (closest != null)
{
BeginInteraction(closest);
return true;
}
else
{
return false;
}
}
protected virtual void OnTriggerEnter(Collider collider)
{
NVRInteractable interactable = NVRInteractables.GetInteractable(collider);
if (interactable == null || interactable.enabled == false)
return;
if (CurrentlyHoveringOver.ContainsKey(interactable) == false)
CurrentlyHoveringOver[interactable] = new Dictionary<Collider, float>();
if (CurrentlyHoveringOver[interactable].ContainsKey(collider) == false)
CurrentlyHoveringOver[interactable][collider] = Time.time;
}
protected virtual void OnTriggerStay(Collider collider)
{
NVRInteractable interactable = NVRInteractables.GetInteractable(collider);
if (interactable == null || interactable.enabled == false)
return;
if (CurrentlyHoveringOver.ContainsKey(interactable) == false)
CurrentlyHoveringOver[interactable] = new Dictionary<Collider, float>();
if (CurrentlyHoveringOver[interactable].ContainsKey(collider) == false)
CurrentlyHoveringOver[interactable][collider] = Time.time;
}
protected virtual void OnTriggerExit(Collider collider)
{
NVRInteractable interactable = NVRInteractables.GetInteractable(collider);
if (interactable == null)
return;
if (CurrentlyHoveringOver.ContainsKey(interactable) == true)
{
if (CurrentlyHoveringOver[interactable].ContainsKey(collider) == true)
{
CurrentlyHoveringOver[interactable].Remove(collider);
if (CurrentlyHoveringOver[interactable].Count == 0)
{
CurrentlyHoveringOver.Remove(interactable);
}
}
}
}
public string GetDeviceName()
{
if (InputDevice != null)
return InputDevice.GetDeviceName();
else
return null;
}
public Collider[] SetupDefaultPhysicalColliders(Transform ModelParent)
{
return InputDevice.SetupDefaultPhysicalColliders(ModelParent);
}
public void DeregisterInteractable(NVRInteractable interactable)
{
if (CurrentlyInteracting == interactable)
CurrentlyInteracting = null;
if (CurrentlyHoveringOver != null && CurrentlyHoveringOver.ContainsKey(interactable))
CurrentlyHoveringOver.Remove(interactable);
}
private void SetVisibility(VisibilityLevel visibility)
{
if (CurrentVisibility != visibility)
{
if (visibility == VisibilityLevel.Invisible)
{
if (PhysicalController != null)
{
PhysicalController.Off();
}
if (Player.AutomaticallySetControllerTransparency == true)
{
for (int index = 0; index < GhostRenderers.Length; index++)
{
GhostRenderers[index].enabled = false;
}
for (int index = 0; index < GhostColliders.Length; index++)
{
GhostColliders[index].enabled = false;
}
}
}
if (visibility == VisibilityLevel.Ghost)
{
if (PhysicalController != null)
{
PhysicalController.Off();
}
if (Player.AutomaticallySetControllerTransparency == true)
{
for (int index = 0; index < GhostRenderers.Length; index++)
{
GhostRenderers[index].enabled = true;
}
for (int index = 0; index < GhostColliders.Length; index++)
{
GhostColliders[index].enabled = true;
}
}
}
if (visibility == VisibilityLevel.Visible)
{
if (PhysicalController != null)
{
PhysicalController.On();
}
if (Player.AutomaticallySetControllerTransparency == true)
{
for (int index = 0; index < GhostRenderers.Length; index++)
{
GhostRenderers[index].enabled = false;
}
for (int index = 0; index < GhostColliders.Length; index++)
{
GhostColliders[index].enabled = false;
}
}
}
}
CurrentVisibility = visibility;
}
protected void InitializeRenderModel()
{
if (CustomModel == null)
{
RenderModel = InputDevice.SetupDefaultRenderModel();
}
else
{
RenderModel = GameObject.Instantiate(CustomModel);
RenderModel.transform.parent = this.transform;
RenderModel.transform.localScale = RenderModel.transform.localScale;
RenderModel.transform.localPosition = Vector3.zero;
RenderModel.transform.localRotation = Quaternion.identity;
}
}
public void Initialize()
{
Rigidbody = this.GetComponent<Rigidbody>();
#if !UNITY_ANDROID
if (Rigidbody == null)
Rigidbody = this.gameObject.AddComponent<Rigidbody>();
Rigidbody.isKinematic = true;
Rigidbody.maxAngularVelocity = float.MaxValue;
Rigidbody.useGravity = false;
#endif
Collider[] colliders = null;
if (CustomModel == null)
{
colliders = InputDevice.SetupDefaultColliders();
}
else
{
colliders = RenderModel.GetComponentsInChildren<Collider>(); //note: these should be trigger colliders
}
Player.RegisterHand(this);
if (Player.PhysicalHands == true)
{
if (PhysicalController != null)
{
PhysicalController.Kill();
}
PhysicalController = this.gameObject.AddComponent<NVRPhysicalController>();
PhysicalController.Initialize(this, false);
if (Player.AutomaticallySetControllerTransparency == true)
{
Color transparentcolor = Color.white;
transparentcolor.a = (float)VisibilityLevel.Ghost / 100f;
GhostRenderers = this.GetComponentsInChildren<Renderer>();
for (int rendererIndex = 0; rendererIndex < GhostRenderers.Length; rendererIndex++)
{
NVRHelpers.SetTransparent(GhostRenderers[rendererIndex].material, transparentcolor);
}
}
if (colliders != null)
{
GhostColliders = colliders;
}
CurrentVisibility = VisibilityLevel.Ghost;
}
else
{
if (Player.AutomaticallySetControllerTransparency == true)
{
Color transparentcolor = Color.white;
transparentcolor.a = (float)VisibilityLevel.Ghost / 100f;
GhostRenderers = this.GetComponentsInChildren<Renderer>();
for (int rendererIndex = 0; rendererIndex < GhostRenderers.Length; rendererIndex++)
{
NVRHelpers.SetTransparent(GhostRenderers[rendererIndex].material, transparentcolor);
}
}
if (colliders != null)
{
GhostColliders = colliders;
}
CurrentVisibility = VisibilityLevel.Ghost;
}
CurrentHandState = HandState.Idle;
}
public void ForceGhost()
{
SetVisibility(VisibilityLevel.Ghost);
PhysicalController.Off();
}
public void SetInteractable(bool canInteract)
{
OnChangeCanInteract.Invoke(canInteract);
}
}
public enum VisibilityLevel
{
Invisible = 0,
Ghost = 70,
Visible = 100,
}
public enum HandState
{
Uninitialized,
Idle,
GripDownNotInteracting,
GripDownInteracting,
GripToggleOnNotInteracting,
GripToggleOnInteracting,
GripToggleOff
}
public enum InterationStyle
{
Hold,
Toggle,
ByScript,
}
}
| |
namespace Economy.scripts.Messages
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EconConfig;
using Economy.scripts;
using EconStructures;
using ProtoBuf;
using Sandbox.Definitions;
using Sandbox.ModAPI;
using VRage.Game;
using VRage.ModAPI;
using VRage.ObjectBuilders;
/// <summary>
/// this is to do the actual work of setting new prices and stock levels.
/// </summary>
[ProtoContract]
public class MessageSet : MessageBase
{
#region properties
/// <summary>
/// The market to set prices in.
/// </summary>
[ProtoMember(1)]
public ulong MarketId;
/// <summary>
/// The market name to set prices in.
/// </summary>
[ProtoMember(2)]
public string MarketZone;
/// <summary>
/// item id we are setting
/// </summary>
[ProtoMember(3)]
public string ItemTypeId;
/// <summary>
/// item subid we are setting
/// </summary>
[ProtoMember(4)]
public string ItemSubTypeName;
[ProtoMember(5)]
public SetMarketItemType SetType;
/// <summary>
/// qty of item
/// </summary>
[ProtoMember(6)]
public decimal ItemQuantity;
/// <summary>
/// unit price to buy item at.
/// </summary>
[ProtoMember(7)]
public decimal ItemBuyPrice;
/// <summary>
/// unit price to sell item at.
/// </summary>
[ProtoMember(8)]
public decimal ItemSellPrice;
#endregion
public static void SendMessage(ulong marketId, string marketZone, string itemTypeId, string itemSubTypeName, SetMarketItemType setType, decimal itemQuantity, decimal itemBuyPrice, decimal itemSellPrice)
{
ConnectionHelper.SendMessageToServer(new MessageSet { MarketId = marketId, MarketZone = marketZone, ItemTypeId = itemTypeId, ItemSubTypeName = itemSubTypeName, SetType = setType, ItemQuantity = itemQuantity, ItemBuyPrice = itemBuyPrice, ItemSellPrice = itemSellPrice });
}
public static void SendMessageBuy(ulong marketId, string marketZone, string itemTypeId, string itemSubTypeName, decimal itemBuyPrice)
{
ConnectionHelper.SendMessageToServer(new MessageSet { MarketId = marketId, MarketZone = marketZone, ItemTypeId = itemTypeId, ItemSubTypeName = itemSubTypeName, SetType = SetMarketItemType.BuyPrice, ItemBuyPrice = itemBuyPrice });
}
public static void SendMessageSell(ulong marketId, string marketZone, string itemTypeId, string itemSubTypeName, decimal itemSellPrice)
{
ConnectionHelper.SendMessageToServer(new MessageSet { MarketId = marketId, MarketZone = marketZone, ItemTypeId = itemTypeId, ItemSubTypeName = itemSubTypeName, SetType = SetMarketItemType.SellPrice, ItemSellPrice = itemSellPrice });
}
public static void SendMessageQuantity(ulong marketId, string marketZone, string itemTypeId, string itemSubTypeName, decimal itemQuantity)
{
ConnectionHelper.SendMessageToServer(new MessageSet { MarketId = marketId, MarketZone = marketZone, ItemTypeId = itemTypeId, ItemSubTypeName = itemSubTypeName, SetType = SetMarketItemType.Quantity, ItemQuantity = itemQuantity });
}
public override void ProcessClient()
{
// never processed on client
}
public override void ProcessServer()
{
var player = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId);
// Only Admin can change Npc Market prices.
if (!player.IsAdmin() && MarketId == EconomyConsts.NpcMerchantId)
{
EconomyScript.Instance.ServerLogger.WriteWarning("A Player without Admin \"{0}\" {1} attempted to set Default Market characteristics of item {2}/{3} to Quantity={4}.", SenderDisplayName, SenderSteamId, ItemTypeId, ItemSubTypeName, ItemQuantity);
return;
}
// Only Player can change their own Market prices.
if (SenderSteamId != MarketId && MarketId != EconomyConsts.NpcMerchantId)
{
EconomyScript.Instance.ServerLogger.WriteWarning("A Player \"{0}\" {1} attempted to set another Market characteristics of item {2}/{3} to Quantity={4}.", SenderDisplayName, SenderSteamId, ItemTypeId, ItemSubTypeName, ItemQuantity);
return;
}
// TODO: do we check range to market?
MyDefinitionBase definition = null;
MyObjectBuilderType result;
if (MyObjectBuilderType.TryParse(ItemTypeId, out result))
{
var id = new MyDefinitionId(result, ItemSubTypeName);
MyDefinitionManager.Static.TryGetDefinition(id, out definition);
}
if (definition == null)
{
// Passing bad data?
MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "Sorry, the item you specified doesn't exist!");
return;
}
if (SetType.HasFlag(SetMarketItemType.Quantity))
{
// Do a floating point check on the item item. Tools and components cannot have decimals. They must be whole numbers.
if (definition.Id.TypeId != typeof(MyObjectBuilder_Ore) && definition.Id.TypeId != typeof(MyObjectBuilder_Ingot))
{
if (ItemQuantity != Math.Truncate(ItemQuantity))
{
MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "You must provide a whole number for the quantity of that item.");
return;
}
//ItemQuantity = Math.Round(ItemQuantity, 0); // Or do we just round the number?
}
if (ItemQuantity <= 0)
{
MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "Invalid quantity specified");
return;
}
}
// Find the specified market.
List<MarketStruct> markets;
if (string.IsNullOrEmpty(MarketZone))
{
var character = player.GetCharacter();
if (character == null)
{
// Player has no body. Could mean they are dead.
MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "There is no market at your location to set.");
return;
}
var position = ((IMyEntity)character).WorldMatrix.Translation;
markets = MarketManager.FindMarketsFromLocation(position).Where(m => m.MarketId == MarketId).ToList();
}
else
{
markets = EconomyScript.Instance.Data.Markets.Where(m => m.MarketId == MarketId && (MarketZone == "*" || m.DisplayName.Equals(MarketZone, StringComparison.InvariantCultureIgnoreCase))).ToList();
}
if (markets.Count == 0)
{
MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "Sorry, you are not near any markets currently or the market does not exist!");
return;
}
var msg = new StringBuilder();
msg.AppendFormat("Applying changes to : '{0}' {1}/{2}\r\n\r\n", definition.GetDisplayName(), ItemTypeId, ItemSubTypeName);
foreach (var market in markets)
{
msg.AppendFormat("Market: '{0}'\r\n", market.DisplayName);
var marketItem = market.MarketItems.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName);
if (marketItem == null)
{
msg.AppendLine("Sorry, the items you are trying to set doesn't have a market entry!");
// In reality, this shouldn't happen as all markets have their items synced up on start up of the mod.
continue;
}
if (SetType.HasFlag(SetMarketItemType.Quantity))
{
marketItem.Quantity = ItemQuantity;
msg.AppendFormat("Stock on hand to {0} units", ItemQuantity);
}
// Validation to prevent admins setting prices too low for items.
if (SetType.HasFlag(SetMarketItemType.BuyPrice))
{
if (ItemBuyPrice >= 0)
{
marketItem.BuyPrice = ItemBuyPrice;
msg.AppendFormat("Buy price to {0}", ItemBuyPrice);
}
else
msg.AppendFormat("Could not set buy price to less than 0.");
}
// Validation to prevent admins setting prices too low for items.
if (SetType.HasFlag(SetMarketItemType.SellPrice))
{
if (ItemSellPrice >= 0)
{
marketItem.SellPrice = ItemSellPrice;
msg.AppendFormat("Sell price to {0}", ItemSellPrice);
}
else
msg.AppendFormat("Could not set sell price to less than 0.");
}
if (SetType.HasFlag(SetMarketItemType.Blacklisted))
{
marketItem.IsBlacklisted = !marketItem.IsBlacklisted;
msg.AppendFormat("Blacklist to {0}", marketItem.IsBlacklisted ? "On" : "Off");
}
msg.AppendLine();
msg.AppendLine();
}
#region update config for the item
MarketItemStruct configItem = null;
if (player.IsAdmin() && MarketId == EconomyConsts.NpcMerchantId)
configItem = EconomyScript.Instance.ServerConfig.DefaultPrices.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName);
if (configItem != null)
{
if (SetType.HasFlag(SetMarketItemType.BuyPrice))
{
if (ItemBuyPrice >= 0)
{
configItem.BuyPrice = ItemBuyPrice;
msg.AppendFormat("Config updated Buy price to {0}", ItemBuyPrice);
}
}
// Validation to prevent admins setting prices too low for items.
if (SetType.HasFlag(SetMarketItemType.SellPrice))
{
if (ItemSellPrice >= 0)
{
configItem.SellPrice = ItemSellPrice;
msg.AppendFormat("Config updated Sell price to {0}", ItemSellPrice);
}
}
if (SetType.HasFlag(SetMarketItemType.Blacklisted))
{
configItem.IsBlacklisted = !configItem.IsBlacklisted;
msg.AppendFormat("Config updated Blacklist to {0}", configItem.IsBlacklisted ? "On" : "Off");
// If config blacklisted, then all markets should be updated.
if (configItem.IsBlacklisted)
{
int counter = 0;
foreach (var market in EconomyScript.Instance.Data.Markets)
{
var marketItem = market.MarketItems.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName);
if (marketItem != null && !marketItem.IsBlacklisted)
{
counter++;
marketItem.IsBlacklisted = true;
}
}
msg.AppendFormat("Config updated {0} Markets to also Blacklist to {1}.", counter, configItem.IsBlacklisted ? "On" : "Off");
}
}
}
#endregion
MessageClientDialogMessage.SendMessage(SenderSteamId, "SET", " ", msg.ToString());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
namespace System.Linq.Expressions.Tests
{
partial class ExpressionCatalog
{
private static IEnumerable<Expression> MemberInit()
{
yield return ((Expression<Func<MI1>>)(() => new MI1 { })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1 { X = 1 })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1 { X = 1, Y = "bar" })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1(true) { })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1(true) { X = 1 })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1(true) { X = 1, Y = "bar" })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1(false) { })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1(false) { X = 1 })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1(false) { X = 1, Y = "bar" })).Body;
var g1 = new Func<string>(() =>
{
throw new InvalidOperationException("Oops I did it again.");
});
var g2 = new Func<int>(() =>
{
throw new InvalidOperationException("Oops you did it again.");
});
yield return ((Expression<Func<MI1>>)(() => new MI1 { X = 0, Y = g1() })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1 { X = 1, Y = g1() })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1 { Y = g1(), X = 0 })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1 { Y = g1(), X = 1 })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1 { Y = null, X = g2() })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1 { Y = "bar", X = g2() })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1 { X = g2(), Y = null })).Body;
yield return ((Expression<Func<MI1>>)(() => new MI1 { X = g2(), Y = "bar" })).Body;
yield return ((Expression<Func<MI2>>)(() => new MI2 { MI1 = { X = 42, Y = "qux" }, Bars = { 2, 3, 5 } })).Body;
}
private static IEnumerable<KeyValuePair<ExpressionType, Expression>> MemberInit_WithLog()
{
yield return WithLogExpr(ExpressionType.MemberInit, (add, summarize) =>
{
var newTemplate = ((Expression<Func<Action<string>, MIWithLog1>>)(addToLog => new MIWithLog1(addToLog) { Bar = 42, Foo = "qux", Quxs = { 2, 3, 5 }, Baz = { Bar = 43, Foo = "baz" } }));
var valueParam = Expression.Parameter(typeof(MIWithLog1));
var toStringTemplate = ((Expression<Func<MIWithLog1, string>>)(mi => mi.ToString()));
var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2);
return
Expression.Block(
new[] { valueParam },
Expression.Assign(
valueParam,
Expression.Invoke(
ReturnAllConstants(add, newTemplate),
add
)
),
Expression.Invoke(
concatTemplate,
Expression.Invoke(toStringTemplate, valueParam),
Expression.Invoke(summarize)
)
);
});
}
public class MI1 : IEquatable<MI1>
{
private int _x;
private string _y;
public MI1()
{
}
public MI1(bool b)
{
if (!b)
throw new ArgumentException("Can't be false.", "b");
}
public int X
{
get { return _x; }
set
{
if (_x == 0)
throw new ArgumentException("Can't be zero.", "value");
_x = value;
}
}
public string Y
{
get { return _y; }
set
{
if (_y == null)
throw new ArgumentNullException("value", "Can't be null.");
_y = value;
}
}
public bool Equals(MI1 other)
{
if (other == null)
{
return false;
}
return X == other.X && Y == other.Y;
}
public override bool Equals(object obj)
{
return Equals(obj as MI1);
}
public override int GetHashCode()
{
return 0;
}
}
public class MI2 : IEquatable<MI2>
{
private readonly MI1 _mi1 = new MI1();
private readonly List<int> _bars = new List<int>();
public MI1 MI1
{
get
{
return _mi1;
}
}
public List<int> Bars
{
get
{
return _bars;
}
}
public bool Equals(MI2 other)
{
if (other == null)
{
return false;
}
return other.MI1.Equals(MI1) && other.Bars.SequenceEqual(Bars);
}
public override bool Equals(object obj)
{
return Equals(obj as MI2);
}
public override int GetHashCode()
{
return 0;
}
}
class MIWithLog1
{
private readonly Action<string> _addToLog;
private readonly LIWithLog _quxs;
private readonly MIWithLog2 _child;
private int _bar;
private string _foo;
public MIWithLog1(Action<string> addToLog)
{
_addToLog = addToLog;
_quxs = new LIWithLog(addToLog);
_child = new MIWithLog2(addToLog);
_addToLog(".ctor");
}
public int Bar
{
get
{
_addToLog("get_Bar");
return _bar;
}
set
{
_addToLog("set_Bar(" + value + ")");
_bar = value;
}
}
public string Foo
{
get
{
_addToLog("get_Foo");
return _foo;
}
set
{
_addToLog("set_Foo(" + value + ")");
_foo = value;
}
}
public LIWithLog Quxs
{
get
{
_addToLog("get_Quxs");
return _quxs;
}
}
public MIWithLog2 Baz
{
get
{
_addToLog("get_Baz");
return _child;
}
}
public override string ToString()
{
return "{ Bar = " + Bar + ", Foo = " + Foo + ", Baz = " + Baz.ToString() + ", Quxs = " + Quxs.ToString() + " }";
}
}
class MIWithLog2
{
private readonly Action<string> _addToLog;
private int _bar;
private string _foo;
public MIWithLog2(Action<string> addToLog)
{
_addToLog = addToLog;
_addToLog(".ctor");
}
public int Bar
{
get
{
_addToLog("get_Bar");
return _bar;
}
set
{
_addToLog("set_Bar(" + value + ")");
_bar = value;
}
}
public string Foo
{
get
{
_addToLog("get_Foo");
return _foo;
}
set
{
_addToLog("set_Foo(" + value + ")");
_foo = value;
}
}
public override string ToString()
{
return "{ Bar = " + Bar + ", Foo = " + Foo + " }";
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Mail;
using System.Text;
using Xunit;
namespace System.Net.Http.Tests
{
public class HttpRequestHeadersTest
{
private HttpRequestHeaders headers;
public HttpRequestHeadersTest()
{
headers = new HttpRequestHeaders();
}
#region Request headers
[Fact]
public void Accept_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison()
{
// Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison.
Assert.Throws<FormatException>(() => { headers.Add("AcCePt", "this is invalid"); });
}
[Fact]
public void Accept_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain");
value1.CharSet = "utf-8";
value1.Quality = 0.5;
value1.Parameters.Add(new NameValueHeaderValue("custom", "value"));
MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("text/plain");
value2.CharSet = "iso-8859-1";
value2.Quality = 0.3868;
Assert.Equal(0, headers.Accept.Count);
headers.Accept.Add(value1);
headers.Accept.Add(value2);
Assert.Equal(2, headers.Accept.Count);
Assert.Equal(value1, headers.Accept.ElementAt(0));
Assert.Equal(value2, headers.Accept.ElementAt(1));
headers.Accept.Clear();
Assert.Equal(0, headers.Accept.Count);
}
[Fact]
public void Accept_ReadEmptyProperty_EmptyCollection()
{
HttpRequestMessage request = new HttpRequestMessage();
Assert.Equal(0, request.Headers.Accept.Count);
// Copy to another list
List<MediaTypeWithQualityHeaderValue> accepts = request.Headers.Accept.ToList();
Assert.Equal(0, accepts.Count);
accepts = new List<MediaTypeWithQualityHeaderValue>(request.Headers.Accept);
Assert.Equal(0, accepts.Count);
}
[Fact]
public void Accept_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept",
",, , ,,text/plain; charset=iso-8859-1; q=1.0,\r\n */xml; charset=utf-8; q=0.5,,,");
MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain");
value1.CharSet = "iso-8859-1";
value1.Quality = 1.0;
MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("*/xml");
value2.CharSet = "utf-8";
value2.Quality = 0.5;
Assert.Equal(value1, headers.Accept.ElementAt(0));
Assert.Equal(value2, headers.Accept.ElementAt(1));
}
[Fact]
public void Accept_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
// Add a valid media-type with an invalid quality value
headers.TryAddWithoutValidation("Accept", "text/plain; q=a"); // invalid quality
Assert.NotNull(headers.Accept.First());
Assert.Null(headers.Accept.First().Quality);
Assert.Equal("text/plain; q=a", headers.Accept.First().ToString());
headers.Clear();
headers.TryAddWithoutValidation("Accept", "text/plain application/xml"); // no separator
Assert.Equal(0, headers.Accept.Count);
Assert.Equal(1, headers.GetValues("Accept").Count());
Assert.Equal("text/plain application/xml", headers.GetValues("Accept").First());
}
[Fact]
public void AcceptCharset_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.AcceptCharset.Count);
headers.AcceptCharset.Add(new StringWithQualityHeaderValue("iso-8859-5"));
headers.AcceptCharset.Add(new StringWithQualityHeaderValue("unicode-1-1", 0.8));
Assert.Equal(2, headers.AcceptCharset.Count);
Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"), headers.AcceptCharset.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("unicode-1-1", 0.8), headers.AcceptCharset.ElementAt(1));
headers.AcceptCharset.Clear();
Assert.Equal(0, headers.AcceptCharset.Count);
}
[Fact]
public void AcceptCharset_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept-Charset", ", ,,iso-8859-5 , \r\n utf-8 ; q=0.300 ,,,");
Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"),
headers.AcceptCharset.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("utf-8", 0.3),
headers.AcceptCharset.ElementAt(1));
}
[Fact]
public void AcceptCharset_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Accept-Charset", "iso-8859-5 utf-8"); // no separator
Assert.Equal(0, headers.AcceptCharset.Count);
Assert.Equal(1, headers.GetValues("Accept-Charset").Count());
Assert.Equal("iso-8859-5 utf-8", headers.GetValues("Accept-Charset").First());
headers.Clear();
headers.TryAddWithoutValidation("Accept-Charset", "utf-8; q=1; q=0.3");
Assert.Equal(0, headers.AcceptCharset.Count);
Assert.Equal(1, headers.GetValues("Accept-Charset").Count());
Assert.Equal("utf-8; q=1; q=0.3", headers.GetValues("Accept-Charset").First());
}
[Fact]
public void AcceptCharset_AddMultipleValuesAndGetValueString_AllValuesAddedUsingTheCorrectDelimiter()
{
headers.TryAddWithoutValidation("Accept-Charset", "invalid value");
headers.Add("Accept-Charset", "utf-8");
headers.AcceptCharset.Add(new StringWithQualityHeaderValue("iso-8859-5", 0.5));
foreach (var header in headers.GetHeaderStrings())
{
Assert.Equal("Accept-Charset", header.Key);
Assert.Equal("utf-8, iso-8859-5; q=0.5, invalid value", header.Value);
}
}
[Fact]
public void AcceptEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.AcceptEncoding.Count);
headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("compress", 0.9));
headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
Assert.Equal(2, headers.AcceptEncoding.Count);
Assert.Equal(new StringWithQualityHeaderValue("compress", 0.9), headers.AcceptEncoding.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("gzip"), headers.AcceptEncoding.ElementAt(1));
headers.AcceptEncoding.Clear();
Assert.Equal(0, headers.AcceptEncoding.Count);
}
[Fact]
public void AcceptEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept-Encoding", ", gzip; q=1.0, identity; q=0.5, *;q=0, ");
Assert.Equal(new StringWithQualityHeaderValue("gzip", 1),
headers.AcceptEncoding.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("identity", 0.5),
headers.AcceptEncoding.ElementAt(1));
Assert.Equal(new StringWithQualityHeaderValue("*", 0),
headers.AcceptEncoding.ElementAt(2));
headers.AcceptEncoding.Clear();
headers.TryAddWithoutValidation("Accept-Encoding", "");
Assert.Equal(0, headers.AcceptEncoding.Count);
Assert.False(headers.Contains("Accept-Encoding"));
}
[Fact]
public void AcceptEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Accept-Encoding", "gzip deflate"); // no separator
Assert.Equal(0, headers.AcceptEncoding.Count);
Assert.Equal(1, headers.GetValues("Accept-Encoding").Count());
Assert.Equal("gzip deflate", headers.GetValues("Accept-Encoding").First());
headers.Clear();
headers.TryAddWithoutValidation("Accept-Encoding", "compress; q=1; gzip");
Assert.Equal(0, headers.AcceptEncoding.Count);
Assert.Equal(1, headers.GetValues("Accept-Encoding").Count());
Assert.Equal("compress; q=1; gzip", headers.GetValues("Accept-Encoding").First());
}
[Fact]
public void AcceptLanguage_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.AcceptLanguage.Count);
headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("da"));
headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-GB", 0.8));
headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en", 0.7));
Assert.Equal(3, headers.AcceptLanguage.Count);
Assert.Equal(new StringWithQualityHeaderValue("da"), headers.AcceptLanguage.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("en-GB", 0.8), headers.AcceptLanguage.ElementAt(1));
Assert.Equal(new StringWithQualityHeaderValue("en", 0.7), headers.AcceptLanguage.ElementAt(2));
headers.AcceptLanguage.Clear();
Assert.Equal(0, headers.AcceptLanguage.Count);
}
[Fact]
public void AcceptLanguage_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept-Language", " , de-DE;q=0.9,de-AT;q=0.5,*;q=0.010 , ");
Assert.Equal(new StringWithQualityHeaderValue("de-DE", 0.9),
headers.AcceptLanguage.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("de-AT", 0.5),
headers.AcceptLanguage.ElementAt(1));
Assert.Equal(new StringWithQualityHeaderValue("*", 0.01),
headers.AcceptLanguage.ElementAt(2));
headers.AcceptLanguage.Clear();
headers.TryAddWithoutValidation("Accept-Language", "");
Assert.Equal(0, headers.AcceptLanguage.Count);
Assert.False(headers.Contains("Accept-Language"));
}
[Fact]
public void AcceptLanguage_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Accept-Language", "de -DE"); // no separator
Assert.Equal(0, headers.AcceptLanguage.Count);
Assert.Equal(1, headers.GetValues("Accept-Language").Count());
Assert.Equal("de -DE", headers.GetValues("Accept-Language").First());
headers.Clear();
headers.TryAddWithoutValidation("Accept-Language", "en; q=0.4,[");
Assert.Equal(0, headers.AcceptLanguage.Count);
Assert.Equal(1, headers.GetValues("Accept-Language").Count());
Assert.Equal("en; q=0.4,[", headers.GetValues("Accept-Language").First());
}
[Fact]
public void Expect_Add100Continue_Success()
{
// use non-default casing to make sure we do case-insensitive comparison.
headers.Expect.Add(new NameValueWithParametersHeaderValue("100-CONTINUE"));
Assert.True(headers.ExpectContinue == true);
Assert.Equal(1, headers.Expect.Count);
}
[Fact]
public void Expect_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Expect.Count);
Assert.Null(headers.ExpectContinue);
headers.Expect.Add(new NameValueWithParametersHeaderValue("custom1"));
headers.Expect.Add(new NameValueWithParametersHeaderValue("custom2"));
headers.ExpectContinue = true;
// Connection collection has 2 values plus '100-Continue'
Assert.Equal(3, headers.Expect.Count);
Assert.Equal(3, headers.GetValues("Expect").Count());
Assert.True(headers.ExpectContinue == true, "ExpectContinue == true");
Assert.Equal(new NameValueWithParametersHeaderValue("custom1"), headers.Expect.ElementAt(0));
Assert.Equal(new NameValueWithParametersHeaderValue("custom2"), headers.Expect.ElementAt(1));
// Remove '100-continue' value from store. But leave other 'Expect' values.
headers.ExpectContinue = false;
Assert.True(headers.ExpectContinue == false, "ExpectContinue == false");
Assert.Equal(2, headers.Expect.Count);
Assert.Equal(new NameValueWithParametersHeaderValue("custom1"), headers.Expect.ElementAt(0));
Assert.Equal(new NameValueWithParametersHeaderValue("custom2"), headers.Expect.ElementAt(1));
headers.ExpectContinue = true;
headers.Expect.Clear();
Assert.True(headers.ExpectContinue == false, "ExpectContinue should be modified by Expect.Clear().");
Assert.Equal(0, headers.Expect.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Expect", out dummyArray), "Expect header count after Expect.Clear().");
// Remove '100-continue' value from store. Since there are no other 'Expect' values, remove whole header.
headers.ExpectContinue = false;
Assert.True(headers.ExpectContinue == false, "ExpectContinue == false");
Assert.Equal(0, headers.Expect.Count);
Assert.False(headers.Contains("Expect"));
headers.ExpectContinue = null;
Assert.Null(headers.ExpectContinue);
}
[Fact]
public void Expect_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Expect",
", , 100-continue, name1 = value1, name2; param2=paramValue2, name3=value3; param3 ,");
// Connection collection has 3 values plus '100-continue'
Assert.Equal(4, headers.Expect.Count);
Assert.Equal(4, headers.GetValues("Expect").Count());
Assert.True(headers.ExpectContinue == true, "ExpectContinue expected to be true.");
Assert.Equal(new NameValueWithParametersHeaderValue("100-continue"),
headers.Expect.ElementAt(0));
Assert.Equal(new NameValueWithParametersHeaderValue("name1", "value1"),
headers.Expect.ElementAt(1));
NameValueWithParametersHeaderValue expected2 = new NameValueWithParametersHeaderValue("name2");
expected2.Parameters.Add(new NameValueHeaderValue("param2", "paramValue2"));
Assert.Equal(expected2, headers.Expect.ElementAt(2));
NameValueWithParametersHeaderValue expected3 = new NameValueWithParametersHeaderValue("name3", "value3");
expected3.Parameters.Add(new NameValueHeaderValue("param3"));
Assert.Equal(expected3, headers.Expect.ElementAt(3));
headers.Expect.Clear();
Assert.Null(headers.ExpectContinue);
Assert.Equal(0, headers.Expect.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Expect", out dummyArray), "Expect header count after Expect.Clear().");
}
[Fact]
public void Expect_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Expect", "100-continue other"); // no separator
Assert.Equal(0, headers.Expect.Count);
Assert.Equal(1, headers.GetValues("Expect").Count());
Assert.Equal("100-continue other", headers.GetValues("Expect").First());
}
[Fact]
public void Host_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Host);
headers.Host = "host";
Assert.Equal("host", headers.Host);
headers.Host = null;
Assert.Null(headers.Host);
Assert.False(headers.Contains("Host"),
"Header store should not contain a header 'Host' after setting it to null.");
Assert.Throws<FormatException>(() => { headers.Host = "invalid host"; });
}
[Fact]
public void Host_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Host", "host:80");
Assert.Equal("host:80", headers.Host);
}
[Fact]
public void IfMatch_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.IfMatch.Count);
headers.IfMatch.Add(new EntityTagHeaderValue("\"custom1\""));
headers.IfMatch.Add(new EntityTagHeaderValue("\"custom2\"", true));
Assert.Equal(2, headers.IfMatch.Count);
Assert.Equal(2, headers.GetValues("If-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"custom1\""), headers.IfMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"custom2\"", true), headers.IfMatch.ElementAt(1));
headers.IfMatch.Clear();
Assert.Equal(0, headers.IfMatch.Count);
Assert.False(headers.Contains("If-Match"), "Header store should not contain 'If-Match'");
}
[Fact]
public void IfMatch_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Match", ", , W/\"tag1\", \"tag2\", W/\"tag3\" ,");
Assert.Equal(3, headers.IfMatch.Count);
Assert.Equal(3, headers.GetValues("If-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"tag1\"", true), headers.IfMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"tag2\"", false), headers.IfMatch.ElementAt(1));
Assert.Equal(new EntityTagHeaderValue("\"tag3\"", true), headers.IfMatch.ElementAt(2));
headers.IfMatch.Clear();
headers.Add("If-Match", "*");
Assert.Equal(1, headers.IfMatch.Count);
Assert.Same(EntityTagHeaderValue.Any, headers.IfMatch.ElementAt(0));
}
[Fact]
public void IfMatch_UseAddMethodWithInvalidInput_PropertyNotUpdated()
{
headers.TryAddWithoutValidation("If-Match", "W/\"tag1\" \"tag2\""); // no separator
Assert.Equal(0, headers.IfMatch.Count);
Assert.Equal(1, headers.GetValues("If-Match").Count());
}
[Fact]
public void IfNoneMatch_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.IfNoneMatch.Count);
headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"custom1\""));
headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"custom2\"", true));
Assert.Equal(2, headers.IfNoneMatch.Count);
Assert.Equal(2, headers.GetValues("If-None-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"custom1\""), headers.IfNoneMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"custom2\"", true), headers.IfNoneMatch.ElementAt(1));
headers.IfNoneMatch.Clear();
Assert.Equal(0, headers.IfNoneMatch.Count);
Assert.False(headers.Contains("If-None-Match"), "Header store should not contain 'If-None-Match'");
}
[Fact]
public void IfNoneMatch_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-None-Match", "W/\"tag1\", \"tag2\", W/\"tag3\"");
Assert.Equal(3, headers.IfNoneMatch.Count);
Assert.Equal(3, headers.GetValues("If-None-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"tag1\"", true), headers.IfNoneMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"tag2\"", false), headers.IfNoneMatch.ElementAt(1));
Assert.Equal(new EntityTagHeaderValue("\"tag3\"", true), headers.IfNoneMatch.ElementAt(2));
headers.IfNoneMatch.Clear();
headers.Add("If-None-Match", "*");
Assert.Equal(1, headers.IfNoneMatch.Count);
Assert.Same(EntityTagHeaderValue.Any, headers.IfNoneMatch.ElementAt(0));
}
[Fact]
public void TE_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
TransferCodingWithQualityHeaderValue value1 = new TransferCodingWithQualityHeaderValue("custom");
value1.Quality = 0.5;
value1.Parameters.Add(new NameValueHeaderValue("name", "value"));
TransferCodingWithQualityHeaderValue value2 = new TransferCodingWithQualityHeaderValue("custom");
value2.Quality = 0.3868;
Assert.Equal(0, headers.TE.Count);
headers.TE.Add(value1);
headers.TE.Add(value2);
Assert.Equal(2, headers.TE.Count);
Assert.Equal(value1, headers.TE.ElementAt(0));
Assert.Equal(value2, headers.TE.ElementAt(1));
headers.TE.Clear();
Assert.Equal(0, headers.TE.Count);
}
[Fact]
public void TE_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("TE",
",custom1; param1=value1; q=1.0,,\r\n custom2; param2=value2; q=0.5 ,");
TransferCodingWithQualityHeaderValue value1 = new TransferCodingWithQualityHeaderValue("custom1");
value1.Parameters.Add(new NameValueHeaderValue("param1", "value1"));
value1.Quality = 1.0;
TransferCodingWithQualityHeaderValue value2 = new TransferCodingWithQualityHeaderValue("custom2");
value2.Parameters.Add(new NameValueHeaderValue("param2", "value2"));
value2.Quality = 0.5;
Assert.Equal(value1, headers.TE.ElementAt(0));
Assert.Equal(value2, headers.TE.ElementAt(1));
headers.Clear();
headers.TryAddWithoutValidation("TE", "");
Assert.False(headers.Contains("TE"), "'TE' header should not be added if it just has empty values.");
}
[Fact]
public void Range_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Range);
RangeHeaderValue value = new RangeHeaderValue(1, 2);
headers.Range = value;
Assert.Equal(value, headers.Range);
headers.Range = null;
Assert.Null(headers.Range);
}
[Fact]
public void Range_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Range", "custom= , ,1-2, -4 , ");
RangeHeaderValue value = new RangeHeaderValue();
value.Unit = "custom";
value.Ranges.Add(new RangeItemHeaderValue(1, 2));
value.Ranges.Add(new RangeItemHeaderValue(null, 4));
Assert.Equal(value, headers.Range);
}
[Fact]
public void Authorization_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Authorization);
headers.Authorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
Assert.Equal(new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="), headers.Authorization);
headers.Authorization = null;
Assert.Null(headers.Authorization);
Assert.False(headers.Contains("Authorization"),
"Header store should not contain a header 'Authorization' after setting it to null.");
}
[Fact]
public void Authorization_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Authorization", "NTLM blob");
Assert.Equal(new AuthenticationHeaderValue("NTLM", "blob"), headers.Authorization);
}
[Fact]
public void ProxyAuthorization_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.ProxyAuthorization);
headers.ProxyAuthorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
Assert.Equal(new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="),
headers.ProxyAuthorization);
headers.ProxyAuthorization = null;
Assert.Null(headers.ProxyAuthorization);
Assert.False(headers.Contains("ProxyAuthorization"),
"Header store should not contain a header 'ProxyAuthorization' after setting it to null.");
}
[Fact]
public void ProxyAuthorization_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Proxy-Authorization", "NTLM blob");
Assert.Equal(new AuthenticationHeaderValue("NTLM", "blob"), headers.ProxyAuthorization);
}
[Fact]
public void UserAgent_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.UserAgent.Count);
headers.UserAgent.Add(new ProductInfoHeaderValue("(custom1)"));
headers.UserAgent.Add(new ProductInfoHeaderValue("custom2", "1.1"));
Assert.Equal(2, headers.UserAgent.Count);
Assert.Equal(2, headers.GetValues("User-Agent").Count());
Assert.Equal(new ProductInfoHeaderValue("(custom1)"), headers.UserAgent.ElementAt(0));
Assert.Equal(new ProductInfoHeaderValue("custom2", "1.1"), headers.UserAgent.ElementAt(1));
headers.UserAgent.Clear();
Assert.Equal(0, headers.UserAgent.Count);
Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after calling Clear().");
headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)"));
headers.UserAgent.Remove(new ProductInfoHeaderValue("(comment)"));
Assert.Equal(0, headers.UserAgent.Count);
Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after removing last value.");
}
[Fact]
public void UserAgent_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("User-Agent", "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.6.30 Version/10.63");
Assert.Equal(4, headers.UserAgent.Count);
Assert.Equal(4, headers.GetValues("User-Agent").Count());
Assert.Equal(new ProductInfoHeaderValue("Opera", "9.80"), headers.UserAgent.ElementAt(0));
Assert.Equal(new ProductInfoHeaderValue("(Windows NT 6.1; U; en)"), headers.UserAgent.ElementAt(1));
Assert.Equal(new ProductInfoHeaderValue("Presto", "2.6.30"), headers.UserAgent.ElementAt(2));
Assert.Equal(new ProductInfoHeaderValue("Version", "10.63"), headers.UserAgent.ElementAt(3));
headers.UserAgent.Clear();
Assert.Equal(0, headers.UserAgent.Count);
Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after calling Clear().");
}
[Fact]
public void UserAgent_TryGetValuesAndGetValues_Malformed()
{
string malformedUserAgent = "Mozilla/4.0 (compatible (compatible; MSIE 8.0; Windows NT 6.1; Trident/7.0)";
headers.TryAddWithoutValidation("User-Agent", malformedUserAgent);
Assert.True(headers.TryGetValues("User-Agent", out IEnumerable<string> ua));
Assert.Equal(1, ua.Count());
Assert.Equal(malformedUserAgent, ua.First());
Assert.Equal(malformedUserAgent, headers.GetValues("User-Agent").First());
}
[Fact]
public void UserAgent_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("User-Agent", "custom\u4F1A");
Assert.Null(headers.GetParsedValues(KnownHeaders.UserAgent.Descriptor));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal("custom\u4F1A", headers.GetValues("User-Agent").First());
headers.Clear();
// Note that "User-Agent" uses whitespace as separators, so the following is an invalid value
headers.TryAddWithoutValidation("User-Agent", "custom1, custom2");
Assert.Null(headers.GetParsedValues(KnownHeaders.UserAgent.Descriptor));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal("custom1, custom2", headers.GetValues("User-Agent").First());
headers.Clear();
headers.TryAddWithoutValidation("User-Agent", "custom1, ");
Assert.Null(headers.GetParsedValues(KnownHeaders.UserAgent.Descriptor));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal("custom1, ", headers.GetValues("User-Agent").First());
headers.Clear();
headers.TryAddWithoutValidation("User-Agent", ",custom1");
Assert.Null(headers.GetParsedValues(KnownHeaders.UserAgent.Descriptor));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal(",custom1", headers.GetValues("User-Agent").First());
}
[Fact]
public void UserAgent_AddMultipleValuesAndGetValueString_AllValuesAddedUsingTheCorrectDelimiter()
{
headers.TryAddWithoutValidation("User-Agent", "custom\u4F1A");
headers.Add("User-Agent", "custom2/1.1");
headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)"));
foreach (var header in headers.GetHeaderStrings())
{
Assert.Equal("User-Agent", header.Key);
Assert.Equal("custom2/1.1 (comment) custom\u4F1A", header.Value);
}
}
[Fact]
public void IfRange_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.IfRange);
headers.IfRange = new RangeConditionHeaderValue("\"x\"");
Assert.Equal(1, headers.GetValues("If-Range").Count());
Assert.Equal(new RangeConditionHeaderValue("\"x\""), headers.IfRange);
headers.IfRange = null;
Assert.Null(headers.IfRange);
Assert.False(headers.Contains("If-Range"), "If-Range header should be removed after calling Clear().");
}
[Fact]
public void IfRange_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Range", " W/\"tag\" ");
Assert.Equal(new RangeConditionHeaderValue(new EntityTagHeaderValue("\"tag\"", true)),
headers.IfRange);
Assert.Equal(1, headers.GetValues("If-Range").Count());
headers.IfRange = null;
Assert.Null(headers.IfRange);
Assert.False(headers.Contains("If-Range"), "If-Range header should be removed after calling Clear().");
}
[Fact]
public void IfRange_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("If-Range", "\"tag\"\u4F1A");
Assert.Null(headers.GetParsedValues(KnownHeaders.IfRange.Descriptor));
Assert.Equal(1, headers.GetValues("If-Range").Count());
Assert.Equal("\"tag\"\u4F1A", headers.GetValues("If-Range").First());
headers.Clear();
headers.TryAddWithoutValidation("If-Range", " \"tag\", ");
Assert.Null(headers.GetParsedValues(KnownHeaders.IfRange.Descriptor));
Assert.Equal(1, headers.GetValues("If-Range").Count());
Assert.Equal(" \"tag\", ", headers.GetValues("If-Range").First());
}
[Fact]
public void From_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.From);
headers.From = "info@example.com";
Assert.Equal("info@example.com", headers.From);
headers.From = null;
Assert.Null(headers.From);
Assert.False(headers.Contains("From"),
"Header store should not contain a header 'From' after setting it to null.");
Assert.Throws<FormatException>(() => { headers.From = " "; });
Assert.Throws<FormatException>(() => { headers.From = "invalid email address"; });
}
[Fact]
public void From_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("From", " \"My Name\" info@example.com ");
Assert.Equal("\"My Name\" info@example.com ", headers.From);
// The following encoded string represents the character sequence "\u4F1A\u5458\u670D\u52A1".
headers.Clear();
headers.TryAddWithoutValidation("From", "=?utf-8?Q?=E4=BC=9A=E5=91=98=E6=9C=8D=E5=8A=A1?= <info@example.com>");
Assert.Equal("=?utf-8?Q?=E4=BC=9A=E5=91=98=E6=9C=8D=E5=8A=A1?= <info@example.com>", headers.From);
}
[Fact]
public void From_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("From", " info@example.com ,");
Assert.Null(headers.GetParsedValues(KnownHeaders.From.Descriptor));
Assert.Equal(1, headers.GetValues("From").Count());
Assert.Equal(" info@example.com ,", headers.GetValues("From").First());
headers.Clear();
headers.TryAddWithoutValidation("From", "info@");
Assert.Null(headers.GetParsedValues(KnownHeaders.From.Descriptor));
Assert.Equal(1, headers.GetValues("From").Count());
Assert.Equal("info@", headers.GetValues("From").First());
}
[Fact]
public void IfModifiedSince_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.IfModifiedSince);
DateTimeOffset expected = DateTimeOffset.Now;
headers.IfModifiedSince = expected;
Assert.Equal(expected, headers.IfModifiedSince);
headers.IfModifiedSince = null;
Assert.Null(headers.IfModifiedSince);
Assert.False(headers.Contains("If-Modified-Since"),
"Header store should not contain a header 'IfModifiedSince' after setting it to null.");
}
[Fact]
public void IfModifiedSince_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfModifiedSince);
headers.Clear();
headers.TryAddWithoutValidation("If-Modified-Since", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfModifiedSince);
}
[Fact]
public void IfModifiedSince_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(headers.GetParsedValues(KnownHeaders.IfModifiedSince.Descriptor));
Assert.Equal(1, headers.GetValues("If-Modified-Since").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("If-Modified-Since").First());
headers.Clear();
headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov ");
Assert.Null(headers.GetParsedValues(KnownHeaders.IfModifiedSince.Descriptor));
Assert.Equal(1, headers.GetValues("If-Modified-Since").Count());
Assert.Equal(" Sun, 06 Nov ", headers.GetValues("If-Modified-Since").First());
}
[Fact]
public void IfUnmodifiedSince_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.IfUnmodifiedSince);
DateTimeOffset expected = DateTimeOffset.Now;
headers.IfUnmodifiedSince = expected;
Assert.Equal(expected, headers.IfUnmodifiedSince);
headers.IfUnmodifiedSince = null;
Assert.Null(headers.IfUnmodifiedSince);
Assert.False(headers.Contains("If-Unmodified-Since"),
"Header store should not contain a header 'IfUnmodifiedSince' after setting it to null.");
}
[Fact]
public void IfUnmodifiedSince_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfUnmodifiedSince);
headers.Clear();
headers.TryAddWithoutValidation("If-Unmodified-Since", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfUnmodifiedSince);
}
[Fact]
public void IfUnmodifiedSince_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(headers.GetParsedValues(KnownHeaders.IfUnmodifiedSince.Descriptor));
Assert.Equal(1, headers.GetValues("If-Unmodified-Since").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("If-Unmodified-Since").First());
headers.Clear();
headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov ");
Assert.Null(headers.GetParsedValues(KnownHeaders.IfUnmodifiedSince.Descriptor));
Assert.Equal(1, headers.GetValues("If-Unmodified-Since").Count());
Assert.Equal(" Sun, 06 Nov ", headers.GetValues("If-Unmodified-Since").First());
}
[Fact]
public void Referrer_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Referrer);
Uri expected = new Uri("http://example.com/path/");
headers.Referrer = expected;
Assert.Equal(expected, headers.Referrer);
headers.Referrer = null;
Assert.Null(headers.Referrer);
Assert.False(headers.Contains("Referer"),
"Header store should not contain a header 'Referrer' after setting it to null.");
}
[Fact]
public void Referrer_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Referer", " http://www.example.com/path/?q=v ");
Assert.Equal(new Uri("http://www.example.com/path/?q=v"), headers.Referrer);
headers.Clear();
headers.TryAddWithoutValidation("Referer", "/relative/uri/");
Assert.Equal(new Uri("/relative/uri/", UriKind.Relative), headers.Referrer);
}
[Fact]
public void Referrer_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Referer", " http://example.com http://other");
Assert.Null(headers.GetParsedValues(KnownHeaders.Referer.Descriptor));
Assert.Equal(1, headers.GetValues("Referer").Count());
Assert.Equal(" http://example.com http://other", headers.GetValues("Referer").First());
headers.Clear();
headers.TryAddWithoutValidation("Referer", "http://host /other");
Assert.Null(headers.GetParsedValues(KnownHeaders.Referer.Descriptor));
Assert.Equal(1, headers.GetValues("Referer").Count());
Assert.Equal("http://host /other", headers.GetValues("Referer").First());
}
[Fact]
public void MaxForwards_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.MaxForwards);
headers.MaxForwards = 15;
Assert.Equal(15, headers.MaxForwards);
headers.MaxForwards = null;
Assert.Null(headers.MaxForwards);
Assert.False(headers.Contains("Max-Forwards"),
"Header store should not contain a header 'MaxForwards' after setting it to null.");
// Make sure the header gets serialized correctly
headers.MaxForwards = 12345;
Assert.Equal("12345", headers.GetValues("Max-Forwards").First());
}
[Fact]
public void MaxForwards_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Max-Forwards", " 00123 ");
Assert.Equal(123, headers.MaxForwards);
headers.Clear();
headers.TryAddWithoutValidation("Max-Forwards", "0");
Assert.Equal(0, headers.MaxForwards);
}
[Fact]
public void MaxForwards_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Max-Forwards", "15,");
Assert.Null(headers.GetParsedValues(KnownHeaders.MaxForwards.Descriptor));
Assert.Equal(1, headers.GetValues("Max-Forwards").Count());
Assert.Equal("15,", headers.GetValues("Max-Forwards").First());
headers.Clear();
headers.TryAddWithoutValidation("Max-Forwards", "1.0");
Assert.Null(headers.GetParsedValues(KnownHeaders.MaxForwards.Descriptor));
Assert.Equal(1, headers.GetValues("Max-Forwards").Count());
Assert.Equal("1.0", headers.GetValues("Max-Forwards").First());
}
[Fact]
public void AddHeaders_SpecialHeaderValuesOnSourceNotOnDestination_Copied()
{
// Positive
HttpRequestHeaders source = new HttpRequestHeaders();
source.ExpectContinue = true;
source.TransferEncodingChunked = true;
source.ConnectionClose = true;
HttpRequestHeaders destination = new HttpRequestHeaders();
Assert.Null(destination.ExpectContinue);
Assert.Null(destination.TransferEncodingChunked);
Assert.Null(destination.ConnectionClose);
destination.AddHeaders(source);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.True(destination.ExpectContinue.Value);
Assert.True(destination.TransferEncodingChunked.Value);
Assert.True(destination.ConnectionClose.Value);
// Negative
source = new HttpRequestHeaders();
source.ExpectContinue = false;
source.TransferEncodingChunked = false;
source.ConnectionClose = false;
destination = new HttpRequestHeaders();
Assert.Null(destination.ExpectContinue);
Assert.Null(destination.TransferEncodingChunked);
Assert.Null(destination.ConnectionClose);
destination.AddHeaders(source);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.False(destination.ExpectContinue.Value);
Assert.False(destination.TransferEncodingChunked.Value);
Assert.False(destination.ConnectionClose.Value);
}
[Fact]
public void AddHeaders_SpecialHeaderValuesOnDestinationNotOnSource_NotCopied()
{
// Positive
HttpRequestHeaders destination = new HttpRequestHeaders();
destination.ExpectContinue = true;
destination.TransferEncodingChunked = true;
destination.ConnectionClose = true;
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.True(destination.ExpectContinue.Value);
Assert.True(destination.TransferEncodingChunked.Value);
Assert.True(destination.ConnectionClose.Value);
HttpRequestHeaders source = new HttpRequestHeaders();
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
destination.AddHeaders(source);
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.True(destination.ExpectContinue.Value);
Assert.True(destination.TransferEncodingChunked.Value);
Assert.True(destination.ConnectionClose.Value);
// Negative
destination = new HttpRequestHeaders();
destination.ExpectContinue = false;
destination.TransferEncodingChunked = false;
destination.ConnectionClose = false;
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.False(destination.ExpectContinue.Value);
Assert.False(destination.TransferEncodingChunked.Value);
Assert.False(destination.ConnectionClose.Value);
source = new HttpRequestHeaders();
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
destination.AddHeaders(source);
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.False(destination.ExpectContinue.Value);
Assert.False(destination.TransferEncodingChunked.Value);
Assert.False(destination.ConnectionClose.Value);
}
#endregion
#region General headers
[Fact]
public void Connection_AddClose_Success()
{
headers.Connection.Add("CLOSE"); // use non-default casing to make sure we do case-insensitive comparison.
Assert.True(headers.ConnectionClose == true);
Assert.Equal(1, headers.Connection.Count);
}
[Fact]
public void Connection_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Connection.Count);
Assert.Null(headers.ConnectionClose);
headers.Connection.Add("custom1");
headers.Connection.Add("custom2");
headers.ConnectionClose = true;
// Connection collection has 2 values plus 'close'
Assert.Equal(3, headers.Connection.Count);
Assert.Equal(3, headers.GetValues("Connection").Count());
Assert.True(headers.ConnectionClose == true, "ConnectionClose");
Assert.Equal("custom1", headers.Connection.ElementAt(0));
Assert.Equal("custom2", headers.Connection.ElementAt(1));
// Remove 'close' value from store. But leave other 'Connection' values.
headers.ConnectionClose = false;
Assert.True(headers.ConnectionClose == false, "ConnectionClose == false");
Assert.Equal(2, headers.Connection.Count);
Assert.Equal("custom1", headers.Connection.ElementAt(0));
Assert.Equal("custom2", headers.Connection.ElementAt(1));
headers.ConnectionClose = true;
headers.Connection.Clear();
Assert.True(headers.ConnectionClose == false,
"ConnectionClose should be modified by Connection.Clear().");
Assert.Equal(0, headers.Connection.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Connection", out dummyArray),
"Connection header count after Connection.Clear().");
// Remove 'close' value from store. Since there are no other 'Connection' values, remove whole header.
headers.ConnectionClose = false;
Assert.True(headers.ConnectionClose == false, "ConnectionClose == false");
Assert.Equal(0, headers.Connection.Count);
Assert.False(headers.Contains("Connection"));
headers.ConnectionClose = null;
Assert.Null(headers.ConnectionClose);
}
[Fact]
public void Connection_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Connection", "custom1, close, custom2, custom3");
// Connection collection has 3 values plus 'close'
Assert.Equal(4, headers.Connection.Count);
Assert.Equal(4, headers.GetValues("Connection").Count());
Assert.True(headers.ConnectionClose == true);
Assert.Equal("custom1", headers.Connection.ElementAt(0));
Assert.Equal("close", headers.Connection.ElementAt(1));
Assert.Equal("custom2", headers.Connection.ElementAt(2));
Assert.Equal("custom3", headers.Connection.ElementAt(3));
headers.Connection.Clear();
Assert.Null(headers.ConnectionClose);
Assert.Equal(0, headers.Connection.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Connection", out dummyArray),
"Connection header count after Connection.Clear().");
}
[Fact]
public void Connection_AddInvalidValue_Throw()
{
Assert.Throws<FormatException>(() => { headers.Connection.Add("this is invalid"); });
}
[Fact]
public void TransferEncoding_AddChunked_Success()
{
// use non-default casing to make sure we do case-insensitive comparison.
headers.TransferEncoding.Add(new TransferCodingHeaderValue("CHUNKED"));
Assert.True(headers.TransferEncodingChunked == true);
Assert.Equal(1, headers.TransferEncoding.Count);
}
[Fact]
public void TransferEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.Null(headers.TransferEncodingChunked);
headers.TransferEncoding.Add(new TransferCodingHeaderValue("custom1"));
headers.TransferEncoding.Add(new TransferCodingHeaderValue("custom2"));
headers.TransferEncodingChunked = true;
// Connection collection has 2 values plus 'chunked'
Assert.Equal(3, headers.TransferEncoding.Count);
Assert.Equal(3, headers.GetValues("Transfer-Encoding").Count());
Assert.Equal(true, headers.TransferEncodingChunked);
Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0));
Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1));
// Remove 'chunked' value from store. But leave other 'Transfer-Encoding' values. Note that according to
// the RFC this is not valid, since 'chunked' must always be present. However this check is done
// in the transport handler since the user can add invalid header values anyways.
headers.TransferEncodingChunked = false;
Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked == false");
Assert.Equal(2, headers.TransferEncoding.Count);
Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0));
Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1));
headers.TransferEncodingChunked = true;
headers.TransferEncoding.Clear();
Assert.True(headers.TransferEncodingChunked == false,
"TransferEncodingChunked should be modified by TransferEncoding.Clear().");
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.Contains("Transfer-Encoding"));
// Remove 'chunked' value from store. Since there are no other 'Transfer-Encoding' values, remove whole
// header.
headers.TransferEncodingChunked = false;
Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked == false");
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.Contains("Transfer-Encoding"));
headers.TransferEncodingChunked = null;
Assert.Null(headers.TransferEncodingChunked);
}
[Fact]
public void TransferEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Transfer-Encoding", " , custom1, , custom2, custom3, chunked ,");
// Connection collection has 3 values plus 'chunked'
Assert.Equal(4, headers.TransferEncoding.Count);
Assert.Equal(4, headers.GetValues("Transfer-Encoding").Count());
Assert.True(headers.TransferEncodingChunked == true, "TransferEncodingChunked expected to be true.");
Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0));
Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1));
Assert.Equal(new TransferCodingHeaderValue("custom3"), headers.TransferEncoding.ElementAt(2));
headers.TransferEncoding.Clear();
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.Contains("Transfer-Encoding"),
"Transfer-Encoding header after TransferEncoding.Clear().");
}
[Fact]
public void TransferEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Transfer-Encoding", "custom\u4F1A");
Assert.Null(headers.GetParsedValues(KnownHeaders.TransferEncoding.Descriptor));
Assert.Equal(1, headers.GetValues("Transfer-Encoding").Count());
Assert.Equal("custom\u4F1A", headers.GetValues("Transfer-Encoding").First());
headers.Clear();
headers.TryAddWithoutValidation("Transfer-Encoding", "custom1 custom2");
Assert.Null(headers.GetParsedValues(KnownHeaders.TransferEncoding.Descriptor));
Assert.Equal(1, headers.GetValues("Transfer-Encoding").Count());
Assert.Equal("custom1 custom2", headers.GetValues("Transfer-Encoding").First());
headers.Clear();
headers.TryAddWithoutValidation("Transfer-Encoding", "");
Assert.False(headers.Contains("Transfer-Encoding"), "'Transfer-Encoding' header should not be added if it just has empty values.");
}
[Fact]
public void Upgrade_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Upgrade.Count);
headers.Upgrade.Add(new ProductHeaderValue("custom1"));
headers.Upgrade.Add(new ProductHeaderValue("custom2", "1.1"));
Assert.Equal(2, headers.Upgrade.Count);
Assert.Equal(2, headers.GetValues("Upgrade").Count());
Assert.Equal(new ProductHeaderValue("custom1"), headers.Upgrade.ElementAt(0));
Assert.Equal(new ProductHeaderValue("custom2", "1.1"), headers.Upgrade.ElementAt(1));
headers.Upgrade.Clear();
Assert.Equal(0, headers.Upgrade.Count);
Assert.False(headers.Contains("Upgrade"), "Upgrade header should be removed after calling Clear().");
}
[Fact]
public void Upgrade_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Upgrade", " , custom1 / 1.0, , custom2, custom3/2.0,");
Assert.Equal(3, headers.Upgrade.Count);
Assert.Equal(3, headers.GetValues("Upgrade").Count());
Assert.Equal(new ProductHeaderValue("custom1", "1.0"), headers.Upgrade.ElementAt(0));
Assert.Equal(new ProductHeaderValue("custom2"), headers.Upgrade.ElementAt(1));
Assert.Equal(new ProductHeaderValue("custom3", "2.0"), headers.Upgrade.ElementAt(2));
headers.Upgrade.Clear();
Assert.Equal(0, headers.Upgrade.Count);
Assert.False(headers.Contains("Upgrade"), "Upgrade header should be removed after calling Clear().");
}
[Fact]
public void Upgrade_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Upgrade", "custom\u4F1A");
Assert.Null(headers.GetParsedValues(KnownHeaders.Upgrade.Descriptor));
Assert.Equal(1, headers.GetValues("Upgrade").Count());
Assert.Equal("custom\u4F1A", headers.GetValues("Upgrade").First());
headers.Clear();
headers.TryAddWithoutValidation("Upgrade", "custom1 custom2");
Assert.Null(headers.GetParsedValues(KnownHeaders.Upgrade.Descriptor));
Assert.Equal(1, headers.GetValues("Upgrade").Count());
Assert.Equal("custom1 custom2", headers.GetValues("Upgrade").First());
}
[Fact]
public void Date_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Date);
DateTimeOffset expected = DateTimeOffset.Now;
headers.Date = expected;
Assert.Equal(expected, headers.Date);
headers.Date = null;
Assert.Null(headers.Date);
Assert.False(headers.Contains("Date"),
"Header store should not contain a header 'Date' after setting it to null.");
// Make sure the header gets serialized correctly
headers.Date = (new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero));
Assert.Equal("Sun, 06 Nov 1994 08:49:37 GMT", headers.GetValues("Date").First());
}
[Fact]
public void Date_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Date", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.Date);
headers.Clear();
headers.TryAddWithoutValidation("Date", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.Date);
}
[Fact]
public void Date_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Date", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(headers.GetParsedValues(KnownHeaders.Date.Descriptor));
Assert.Equal(1, headers.GetValues("Date").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("Date").First());
headers.Clear();
headers.TryAddWithoutValidation("Date", " Sun, 06 Nov ");
Assert.Null(headers.GetParsedValues(KnownHeaders.Date.Descriptor));
Assert.Equal(1, headers.GetValues("Date").Count());
Assert.Equal(" Sun, 06 Nov ", headers.GetValues("Date").First());
}
[Fact]
public void Via_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Via.Count);
headers.Via.Add(new ViaHeaderValue("x11", "host"));
headers.Via.Add(new ViaHeaderValue("1.1", "example.com:8080", "HTTP", "(comment)"));
Assert.Equal(2, headers.Via.Count);
Assert.Equal(new ViaHeaderValue("x11", "host"), headers.Via.ElementAt(0));
Assert.Equal(new ViaHeaderValue("1.1", "example.com:8080", "HTTP", "(comment)"),
headers.Via.ElementAt(1));
headers.Via.Clear();
Assert.Equal(0, headers.Via.Count);
}
[Fact]
public void Via_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Via", ", 1.1 host, WS/1.0 [::1],X/11 192.168.0.1 (c(comment)) ");
Assert.Equal(new ViaHeaderValue("1.1", "host"), headers.Via.ElementAt(0));
Assert.Equal(new ViaHeaderValue("1.0", "[::1]", "WS"), headers.Via.ElementAt(1));
Assert.Equal(new ViaHeaderValue("11", "192.168.0.1", "X", "(c(comment))"), headers.Via.ElementAt(2));
headers.Via.Clear();
headers.TryAddWithoutValidation("Via", "");
Assert.Equal(0, headers.Via.Count);
Assert.False(headers.Contains("Via"));
}
[Fact]
public void Via_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Via", "1.1 host1 1.1 host2"); // no separator
Assert.Equal(0, headers.Via.Count);
Assert.Equal(1, headers.GetValues("Via").Count());
Assert.Equal("1.1 host1 1.1 host2", headers.GetValues("Via").First());
headers.Clear();
headers.TryAddWithoutValidation("Via", "X/11 host/1");
Assert.Equal(0, headers.Via.Count);
Assert.Equal(1, headers.GetValues("Via").Count());
Assert.Equal("X/11 host/1", headers.GetValues("Via").First());
}
[Fact]
public void Warning_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Warning.Count);
headers.Warning.Add(new WarningHeaderValue(199, "microsoft.com", "\"Miscellaneous warning\""));
headers.Warning.Add(new WarningHeaderValue(113, "example.com", "\"Heuristic expiration\""));
Assert.Equal(2, headers.Warning.Count);
Assert.Equal(new WarningHeaderValue(199, "microsoft.com", "\"Miscellaneous warning\""),
headers.Warning.ElementAt(0));
Assert.Equal(new WarningHeaderValue(113, "example.com", "\"Heuristic expiration\""),
headers.Warning.ElementAt(1));
headers.Warning.Clear();
Assert.Equal(0, headers.Warning.Count);
}
[Fact]
public void Warning_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Warning",
"112 example.com \"Disconnected operation\", 111 example.org \"Revalidation failed\"");
Assert.Equal(new WarningHeaderValue(112, "example.com", "\"Disconnected operation\""),
headers.Warning.ElementAt(0));
Assert.Equal(new WarningHeaderValue(111, "example.org", "\"Revalidation failed\""),
headers.Warning.ElementAt(1));
headers.Warning.Clear();
headers.TryAddWithoutValidation("Warning", "");
Assert.Equal(0, headers.Warning.Count);
Assert.False(headers.Contains("Warning"));
}
[Fact]
public void Warning_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Warning", "123 host1 \"\" 456 host2 \"\""); // no separator
Assert.Equal(0, headers.Warning.Count);
Assert.Equal(1, headers.GetValues("Warning").Count());
Assert.Equal("123 host1 \"\" 456 host2 \"\"", headers.GetValues("Warning").First());
headers.Clear();
headers.TryAddWithoutValidation("Warning", "123 host1\"text\"");
Assert.Equal(0, headers.Warning.Count);
Assert.Equal(1, headers.GetValues("Warning").Count());
Assert.Equal("123 host1\"text\"", headers.GetValues("Warning").First());
}
[Fact]
public void CacheControl_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.CacheControl);
CacheControlHeaderValue value = new CacheControlHeaderValue();
value.NoCache = true;
value.NoCacheHeaders.Add("token1");
value.NoCacheHeaders.Add("token2");
value.MustRevalidate = true;
value.SharedMaxAge = new TimeSpan(1, 2, 3);
headers.CacheControl = value;
Assert.Equal(value, headers.CacheControl);
headers.CacheControl = null;
Assert.Null(headers.CacheControl);
Assert.False(headers.Contains("Cache-Control"),
"Header store should not contain a header 'Cache-Control' after setting it to null.");
}
[Fact]
public void CacheControl_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Cache-Control", "no-cache=\"token1, token2\", must-revalidate, max-age=3");
headers.Add("Cache-Control", "");
headers.Add("Cache-Control", "public, s-maxage=15");
headers.TryAddWithoutValidation("Cache-Control", "");
CacheControlHeaderValue value = new CacheControlHeaderValue();
value.NoCache = true;
value.NoCacheHeaders.Add("token1");
value.NoCacheHeaders.Add("token2");
value.MustRevalidate = true;
value.MaxAge = new TimeSpan(0, 0, 3);
value.Public = true;
value.SharedMaxAge = new TimeSpan(0, 0, 15);
Assert.Equal(value, headers.CacheControl);
}
[Fact]
public void Trailer_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Trailer.Count);
headers.Trailer.Add("custom1");
headers.Trailer.Add("custom2");
Assert.Equal(2, headers.Trailer.Count);
Assert.Equal(2, headers.GetValues("Trailer").Count());
Assert.Equal("custom1", headers.Trailer.ElementAt(0));
Assert.Equal("custom2", headers.Trailer.ElementAt(1));
headers.Trailer.Clear();
Assert.Equal(0, headers.Trailer.Count);
Assert.False(headers.Contains("Trailer"),
"There should be no Trailer header after calling Clear().");
}
[Fact]
public void Trailer_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Trailer", ",custom1, custom2, custom3,");
Assert.Equal(3, headers.Trailer.Count);
Assert.Equal(3, headers.GetValues("Trailer").Count());
Assert.Equal("custom1", headers.Trailer.ElementAt(0));
Assert.Equal("custom2", headers.Trailer.ElementAt(1));
Assert.Equal("custom3", headers.Trailer.ElementAt(2));
headers.Trailer.Clear();
Assert.Equal(0, headers.Trailer.Count);
Assert.False(headers.Contains("Trailer"),
"There should be no Trailer header after calling Clear().");
}
[Fact]
public void Trailer_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Trailer", "custom1 custom2"); // no separator
Assert.Equal(0, headers.Trailer.Count);
Assert.Equal(1, headers.GetValues("Trailer").Count());
Assert.Equal("custom1 custom2", headers.GetValues("Trailer").First());
}
[Fact]
public void Pragma_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Pragma.Count);
headers.Pragma.Add(new NameValueHeaderValue("custom1", "value1"));
headers.Pragma.Add(new NameValueHeaderValue("custom2"));
Assert.Equal(2, headers.Pragma.Count);
Assert.Equal(2, headers.GetValues("Pragma").Count());
Assert.Equal(new NameValueHeaderValue("custom1", "value1"), headers.Pragma.ElementAt(0));
Assert.Equal(new NameValueHeaderValue("custom2"), headers.Pragma.ElementAt(1));
headers.Pragma.Clear();
Assert.Equal(0, headers.Pragma.Count);
Assert.False(headers.Contains("Pragma"),
"There should be no Pragma header after calling Clear().");
}
[Fact]
public void Pragma_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Pragma", ",custom1=value1, custom2, custom3=value3,");
Assert.Equal(3, headers.Pragma.Count);
Assert.Equal(3, headers.GetValues("Pragma").Count());
Assert.Equal(new NameValueHeaderValue("custom1", "value1"), headers.Pragma.ElementAt(0));
Assert.Equal(new NameValueHeaderValue("custom2"), headers.Pragma.ElementAt(1));
Assert.Equal(new NameValueHeaderValue("custom3", "value3"), headers.Pragma.ElementAt(2));
headers.Pragma.Clear();
Assert.Equal(0, headers.Pragma.Count);
Assert.False(headers.Contains("Pragma"),
"There should be no Pragma header after calling Clear().");
}
[Fact]
public void Pragma_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Pragma", "custom1, custom2=");
Assert.Equal(0, headers.Pragma.Count());
Assert.Equal(1, headers.GetValues("Pragma").Count());
Assert.Equal("custom1, custom2=", headers.GetValues("Pragma").First());
}
#endregion
[Fact]
public void ToString_SeveralRequestHeaders_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
string expected = string.Empty;
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/xml"));
expected += HttpKnownHeaderNames.Accept + ": application/xml, */xml\r\n";
request.Headers.Authorization = new AuthenticationHeaderValue("Basic");
expected += HttpKnownHeaderNames.Authorization + ": Basic\r\n";
request.Headers.ExpectContinue = true;
expected += HttpKnownHeaderNames.Expect + ": 100-continue\r\n";
request.Headers.TransferEncodingChunked = true;
expected += HttpKnownHeaderNames.TransferEncoding + ": chunked\r\n";
Assert.Equal(expected, request.Headers.ToString());
}
[Fact]
public void CustomHeaders_ResponseHeadersAsCustomHeaders_Success()
{
// Header names reserved for response headers are permitted as custom request headers.
headers.Add("Accept-Ranges", "v");
headers.TryAddWithoutValidation("age", "v");
headers.Add("ETag", "v");
headers.Add("Location", "v");
headers.Add("Proxy-Authenticate", "v");
headers.Add("Retry-After", "v");
headers.Add("Server", "v");
headers.Add("Vary", "v");
headers.Add("WWW-Authenticate", "v");
}
[Fact]
public void InvalidHeaders_AddContentHeaders_Throw()
{
// Try adding content headers. Use different casing to make sure case-insensitive comparison
// is used.
Assert.Throws<InvalidOperationException>(() => { headers.Add("Allow", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Encoding", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Language", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("content-length", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Location", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-MD5", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Range", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("CONTENT-TYPE", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Expires", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Last-Modified", "v"); });
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmGRVPromotionList
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmGRVPromotionList() : base()
{
FormClosed += frmGRVPromotionList_FormClosed;
KeyPress += frmGRVPromotionList_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdNew;
public System.Windows.Forms.Button cmdNew {
get { return withEventsField_cmdNew; }
set {
if (withEventsField_cmdNew != null) {
withEventsField_cmdNew.Click -= cmdNew_Click;
}
withEventsField_cmdNew = value;
if (withEventsField_cmdNew != null) {
withEventsField_cmdNew.Click += cmdNew_Click;
}
}
}
private myDataGridView withEventsField_DataList1;
public myDataGridView DataList1 {
get { return withEventsField_DataList1; }
set {
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick -= DataList1_DblClick;
withEventsField_DataList1.KeyPress -= DataList1_KeyPress;
}
withEventsField_DataList1 = value;
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick += DataList1_DblClick;
withEventsField_DataList1.KeyPress += DataList1_KeyPress;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtSearch;
public System.Windows.Forms.TextBox txtSearch {
get { return withEventsField_txtSearch; }
set {
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter -= txtSearch_Enter;
withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress;
}
withEventsField_txtSearch = value;
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter += txtSearch_Enter;
withEventsField_txtSearch.KeyDown += txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress += txtSearch_KeyPress;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.Label lbl;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmGRVPromotionList));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.cmdNew = new System.Windows.Forms.Button();
this.DataList1 = new myDataGridView();
this.txtSearch = new System.Windows.Forms.TextBox();
this.cmdExit = new System.Windows.Forms.Button();
this.lbl = new System.Windows.Forms.Label();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit();
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Select a GRV Deal";
this.ClientSize = new System.Drawing.Size(259, 433);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmGRVPromotionList";
this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNew.Text = "&New";
this.cmdNew.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdNew.Size = new System.Drawing.Size(97, 52);
this.cmdNew.Location = new System.Drawing.Point(8, 376);
this.cmdNew.TabIndex = 4;
this.cmdNew.TabStop = false;
this.cmdNew.BackColor = System.Drawing.SystemColors.Control;
this.cmdNew.CausesValidation = true;
this.cmdNew.Enabled = true;
this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNew.Name = "cmdNew";
//'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State)
this.DataList1.Size = new System.Drawing.Size(244, 342);
this.DataList1.Location = new System.Drawing.Point(6, 27);
this.DataList1.TabIndex = 2;
this.DataList1.Name = "DataList1";
this.txtSearch.AutoSize = false;
this.txtSearch.Size = new System.Drawing.Size(199, 19);
this.txtSearch.Location = new System.Drawing.Point(51, 3);
this.txtSearch.TabIndex = 1;
this.txtSearch.AcceptsReturn = true;
this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtSearch.BackColor = System.Drawing.SystemColors.Window;
this.txtSearch.CausesValidation = true;
this.txtSearch.Enabled = true;
this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSearch.HideSelection = true;
this.txtSearch.ReadOnly = false;
this.txtSearch.MaxLength = 0;
this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSearch.Multiline = false;
this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtSearch.TabStop = true;
this.txtSearch.Visible = true;
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtSearch.Name = "txtSearch";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdExit.Size = new System.Drawing.Size(97, 52);
this.cmdExit.Location = new System.Drawing.Point(153, 375);
this.cmdExit.TabIndex = 3;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl.Text = "&Search :";
this.lbl.Size = new System.Drawing.Size(40, 13);
this.lbl.Location = new System.Drawing.Point(8, 6);
this.lbl.TabIndex = 0;
this.lbl.BackColor = System.Drawing.Color.Transparent;
this.lbl.Enabled = true;
this.lbl.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl.UseMnemonic = true;
this.lbl.Visible = true;
this.lbl.AutoSize = true;
this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl.Name = "lbl";
this.Controls.Add(cmdNew);
this.Controls.Add(DataList1);
this.Controls.Add(txtSearch);
this.Controls.Add(cmdExit);
this.Controls.Add(lbl);
((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using System.Data.SqlTypes;
using Inform.Tests.Common;
using Inform;
using Inform.Sql;
using NUnit.Framework;
namespace Inform.Tests.Common {
/// <summary>
/// Summary description for MappingTest.
/// </summary>
public abstract class MappingTest {
protected DataStore dataStore;
public abstract DataStore CreateDataStore();
[SetUp]
public void InitializeConnection() {
dataStore = CreateDataStore();
dataStore.Settings.AutoGenerate = true;
}
[Test]
public void TestCommonValueMappings(){
try{
dataStore.CreateStorage(typeof(CommonValueType));
CommonValueType cvt = new CommonValueType();
cvt.BoolValue = true;
cvt.ByteValue = byte.MaxValue;
cvt.CharValue = char.MaxValue;
cvt.Int16Value = short.MaxValue;
cvt.Int32Value = int.MaxValue;
cvt.Int64Value = long.MaxValue;
cvt.SingleValue = float.MaxValue;
cvt.DoubleValue = long.MaxValue;
dataStore.Insert(cvt);
CommonValueType ncvt = (CommonValueType)dataStore.FindByPrimaryKey(typeof(CommonValueType), cvt.ID);
Assert.AreEqual(cvt.BoolValue, ncvt.BoolValue, "BoolValue");
Assert.AreEqual(cvt.ByteValue, ncvt.ByteValue, "ByteValue");
Assert.AreEqual(cvt.CharValue, ncvt.CharValue, "CharValue");
Assert.AreEqual(cvt.Int16Value, ncvt.Int16Value, "Int16Value");
Assert.AreEqual(cvt.Int32Value, ncvt.Int32Value, "Int32Value");
Assert.AreEqual(cvt.Int64Value, ncvt.Int64Value, "Int64Value");
Assert.AreEqual(cvt.DoubleValue, ncvt.DoubleValue, "DoubleValue");
Assert.AreEqual(cvt.SingleValue, ncvt.SingleValue, "SingleValue");
cvt.BoolValue = false;
cvt.ByteValue = byte.MinValue;
cvt.CharValue = char.MinValue;
cvt.Int16Value = short.MinValue;
cvt.Int32Value = int.MinValue;
cvt.Int64Value = long.MinValue;
cvt.SingleValue = float.MinValue;
cvt.DoubleValue = long.MinValue;
dataStore.Update(cvt);
ncvt = (CommonValueType)dataStore.FindByPrimaryKey(typeof(CommonValueType), cvt.ID);
Assert.AreEqual(cvt.BoolValue, ncvt.BoolValue, "BoolValue");
Assert.AreEqual(cvt.ByteValue, ncvt.ByteValue, "ByteValue");
Assert.AreEqual(cvt.CharValue, ncvt.CharValue, "CharValue");
Assert.AreEqual(cvt.Int16Value, ncvt.Int16Value, "Int16Value");
Assert.AreEqual(cvt.Int32Value, ncvt.Int32Value, "Int32Value");
Assert.AreEqual(cvt.Int64Value, ncvt.Int64Value, "Int64Value");
Assert.AreEqual(cvt.DoubleValue, ncvt.DoubleValue, "DoubleValue");
Assert.AreEqual(cvt.SingleValue, ncvt.SingleValue, "SingleValue");
} finally {
dataStore.DeleteStorage(typeof(CommonValueType));
}
}
[Test]
public void TestCommonObjectsMappings(){
try{
dataStore.CreateStorage(typeof(CommonObjectType));
CommonObjectType cot = new CommonObjectType();
cot.DateTimeValue = SqlDateTime.MaxValue.Value;;
cot.DecimalValue = 99999999.9999M;
cot.GuidValue = Guid.NewGuid();
dataStore.Insert(cot);
CommonObjectType ncot = (CommonObjectType)dataStore.FindByPrimaryKey(typeof(CommonObjectType), cot.ID);
Assert.AreEqual(cot.DateTimeValue, ncot.DateTimeValue, "DateTimeValue");
Assert.AreEqual(cot.DecimalValue, ncot.DecimalValue, "DecimalValue");
Assert.AreEqual(cot.GuidValue, ncot.GuidValue, "GuidValue");
cot.DateTimeValue = SqlDateTime.MinValue.Value;
cot.DecimalValue = -99999999.9999M;
cot.GuidValue = Guid.NewGuid();
dataStore.Update(cot);
ncot = (CommonObjectType)dataStore.FindByPrimaryKey(typeof(CommonObjectType), cot.ID);
Assert.AreEqual(cot.DateTimeValue, ncot.DateTimeValue, "DateTimeValue");
Assert.AreEqual(cot.DecimalValue, ncot.DecimalValue, "DecimalValue");
Assert.AreEqual(cot.GuidValue, ncot.GuidValue, "GuidValue");
cot.DateTimeValue = DateTime.Parse("1/1/2004 5:35PM");
cot.DecimalValue = 12345.2392M;
cot.GuidValue = Guid.NewGuid();
dataStore.Update(cot);
ncot = (CommonObjectType)dataStore.FindByPrimaryKey(typeof(CommonObjectType), cot.ID);
Assert.AreEqual(cot.DateTimeValue, ncot.DateTimeValue, "DateTimeValue");
Assert.AreEqual(cot.DecimalValue, ncot.DecimalValue, "DecimalValue");
Assert.AreEqual(cot.GuidValue, ncot.GuidValue, "GuidValue");
} finally {
if(dataStore.ExistsStorage(typeof(CommonObjectType))){
dataStore.DeleteStorage(typeof(CommonObjectType));
}
}
}
[Test]
public void TestCommonSqlTypeMappings(){
try{
dataStore.CreateStorage(typeof(CommonSqlType));
CommonSqlType cst = new CommonSqlType();
cst.SqlBooleanValue = true;
cst.SqlByteValue = SqlByte.MaxValue;
cst.SqlDateTimeValue = new SqlDateTime (9999,12,31);
cst.SqlDecimalValue = 99999999.9999M;
cst.SqlDoubleValue = SqlDouble.MaxValue;
cst.SqlGuidValue = new SqlGuid(Guid.NewGuid());
cst.SqlInt16Value = SqlInt16.MaxValue;
cst.SqlInt32Value = SqlInt32.MaxValue;
cst.SqlInt64Value = SqlInt64.MaxValue;
cst.SqlMoneyValue = SqlMoney.MaxValue;
cst.SqlSingleValue = SqlSingle.MaxValue;
cst.SqlStringValue = "SqlStringTest";
dataStore.Insert(cst);
CommonSqlType ncst = (CommonSqlType)dataStore.FindByPrimaryKey(typeof(CommonSqlType), cst.ID);
Assert.AreEqual(cst.SqlBooleanValue, ncst.SqlBooleanValue, "SqlBooleanValue");
Assert.AreEqual(cst.SqlByteValue, ncst.SqlByteValue, "SqlByteValue");
Assert.AreEqual(cst.SqlDateTimeValue, ncst.SqlDateTimeValue, "SqlDateTimeValue");
Assert.AreEqual(cst.SqlDecimalValue, ncst.SqlDecimalValue, "SqlDecimalValue");
Assert.AreEqual(cst.SqlDoubleValue, ncst.SqlDoubleValue, "SqlDoubleValue");
Assert.AreEqual(cst.SqlGuidValue, ncst.SqlGuidValue, "SqlGuidValue");
Assert.AreEqual(cst.SqlInt16Value, ncst.SqlInt16Value, "SqlInt16Value");
Assert.AreEqual(cst.SqlInt32Value, ncst.SqlInt32Value, "SqlInt32Value");
Assert.AreEqual(cst.SqlInt64Value, ncst.SqlInt64Value, "SqlInt64Value");
Assert.AreEqual(cst.SqlMoneyValue, ncst.SqlMoneyValue, "SqlMoneyValue");
Assert.AreEqual(cst.SqlSingleValue, ncst.SqlSingleValue, "SqlSingleValue");
Assert.AreEqual(cst.SqlStringValue, ncst.SqlStringValue, "SqlStringValue");
cst.SqlBooleanValue = false;
cst.SqlByteValue = SqlByte.MinValue;
cst.SqlDateTimeValue = SqlDateTime.MinValue;
cst.SqlDecimalValue = -99999999.9999M;
cst.SqlDoubleValue = SqlDouble.MinValue;
cst.SqlGuidValue = new SqlGuid(Guid.NewGuid());
cst.SqlInt16Value = SqlInt16.MinValue;
cst.SqlInt32Value = SqlInt32.MinValue;
cst.SqlInt64Value = SqlInt64.MinValue;
cst.SqlMoneyValue = SqlMoney.MinValue;
cst.SqlSingleValue = SqlSingle.MinValue;
cst.SqlStringValue = "SqlStringTest2";
dataStore.Update(cst);
ncst = (CommonSqlType)dataStore.FindByPrimaryKey(typeof(CommonSqlType), cst.ID);
Assert.AreEqual(cst.SqlBooleanValue, ncst.SqlBooleanValue, "SqlBooleanValue");
Assert.AreEqual(cst.SqlByteValue, ncst.SqlByteValue, "SqlByteValue");
Assert.AreEqual(cst.SqlDateTimeValue, ncst.SqlDateTimeValue, "SqlDateTimeValue");
Assert.AreEqual(cst.SqlDecimalValue, ncst.SqlDecimalValue, "SqlDecimalValue");
Assert.AreEqual(cst.SqlDoubleValue, ncst.SqlDoubleValue, "SqlDoubleValue");
Assert.AreEqual(cst.SqlGuidValue, ncst.SqlGuidValue, "SqlGuidValue");
Assert.AreEqual(cst.SqlInt16Value, ncst.SqlInt16Value, "SqlInt16Value");
Assert.AreEqual(cst.SqlInt32Value, ncst.SqlInt32Value, "SqlInt32Value");
Assert.AreEqual(cst.SqlInt64Value, ncst.SqlInt64Value, "SqlInt64Value");
Assert.AreEqual(cst.SqlMoneyValue, ncst.SqlMoneyValue, "SqlMoneyValue");
Assert.AreEqual(cst.SqlSingleValue, ncst.SqlSingleValue, "SqlSingleValue");
Assert.AreEqual(cst.SqlStringValue, ncst.SqlStringValue, "SqlStringValue");
cst.SqlBooleanValue = SqlBoolean.Null;
cst.SqlByteValue = SqlByte.Null;
cst.SqlDateTimeValue = SqlDateTime.Null;
cst.SqlDecimalValue = SqlDecimal.Null;
cst.SqlDoubleValue = SqlDouble.Null;
cst.SqlGuidValue = SqlGuid.Null;
cst.SqlInt16Value = SqlInt16.Null;
cst.SqlInt32Value = SqlInt32.Null;
cst.SqlInt64Value = SqlInt64.Null;
cst.SqlMoneyValue = SqlMoney.Null;
cst.SqlSingleValue = SqlSingle.Null;
cst.SqlStringValue = SqlString.Null;
dataStore.Update(cst);
ncst = (CommonSqlType)dataStore.FindByPrimaryKey(typeof(CommonSqlType), cst.ID);
if(!(dataStore is Inform.OleDb.OleDbDataStore)){ // not supported in access
Assert.AreEqual(cst.SqlBooleanValue, ncst.SqlBooleanValue, "SqlBooleanValue");
}
Assert.AreEqual(cst.SqlByteValue, ncst.SqlByteValue, "SqlByteValue");
Assert.AreEqual(cst.SqlDateTimeValue, ncst.SqlDateTimeValue, "SqlDateTimeValue");
Assert.AreEqual(cst.SqlDecimalValue, ncst.SqlDecimalValue, "SqlDecimalValue");
Assert.AreEqual(cst.SqlDoubleValue, ncst.SqlDoubleValue, "SqlDoubleValue");
Assert.AreEqual(cst.SqlGuidValue, ncst.SqlGuidValue, "SqlGuidValue");
Assert.AreEqual(cst.SqlInt16Value, ncst.SqlInt16Value, "SqlInt16Value");
Assert.AreEqual(cst.SqlInt32Value, ncst.SqlInt32Value, "SqlInt32Value");
Assert.AreEqual(cst.SqlInt64Value, ncst.SqlInt64Value, "SqlInt64Value");
Assert.AreEqual(cst.SqlMoneyValue, ncst.SqlMoneyValue, "SqlMoneyValue");
Assert.AreEqual(cst.SqlSingleValue, ncst.SqlSingleValue, "SqlSingleValue");
Assert.AreEqual(cst.SqlStringValue, ncst.SqlStringValue, "SqlStringValue");
} finally {
if(dataStore.ExistsStorage(typeof(CommonSqlType))){
dataStore.DeleteStorage(typeof(CommonSqlType));
}
}
}
}
public class CommonValueType {
[MemberMapping(PrimaryKey=true,Identity=true)] public int ID;
[MemberMapping] public bool BoolValue;
[MemberMapping] public byte ByteValue;
[MemberMapping] public char CharValue;
[MemberMapping] public short Int16Value;
[MemberMapping] public int Int32Value;
[MemberMapping] public long Int64Value;
[MemberMapping] public double DoubleValue;
[MemberMapping] public float SingleValue;
}
public class CommonObjectType {
[MemberMapping(PrimaryKey=true,Identity=true)] public int ID;
[MemberMapping] public DateTime DateTimeValue;
[MemberMapping(Precision=12, Scale=4)] public decimal DecimalValue;
[MemberMapping] public Guid GuidValue;
}
public class CommonSqlType {
[MemberMapping(PrimaryKey=true,Identity=true)] public int ID;
[MemberMapping] public SqlBoolean SqlBooleanValue;
[MemberMapping] public SqlByte SqlByteValue;
[MemberMapping] public SqlDateTime SqlDateTimeValue;
[MemberMapping(Precision=12, Scale=4)] public SqlDecimal SqlDecimalValue;
[MemberMapping] public SqlDouble SqlDoubleValue;
[MemberMapping] public SqlGuid SqlGuidValue;
[MemberMapping] public SqlInt16 SqlInt16Value;
[MemberMapping] public SqlInt32 SqlInt32Value;
[MemberMapping] public SqlInt64 SqlInt64Value;
[MemberMapping] public SqlMoney SqlMoneyValue;
[MemberMapping] public SqlSingle SqlSingleValue;
[MemberMapping] public SqlString SqlStringValue;
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or 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.Xml;
using Spring.Core.TypeResolution;
//using TIBCO.EMS;
using Spring.Messaging.Ems.Listener;
using Spring.Messaging.Ems.Listener.Adapter;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
using Spring.Util;
namespace Spring.Messaging.Ems.Config
{
/// <summary>
/// Parser for the EMS <code><listener-container></code> element.
/// </summary>
/// <author>Mark Fisher</author>
/// <author>Juergen Hoeller</author>
/// <author>Mark Pollack (.NET)</author>
public class MessageListenerContainerObjectDefinitionParser : IObjectDefinitionParser
{
#region Fields
private readonly string LISTENER_ELEMENT = "listener";
private readonly string ID_ATTRIBUTE = "id";
private readonly string DESTINATION_ATTRIBUTE = "destination";
private readonly string SUBSCRIPTION_ATTRIBUTE = "subscription";
private readonly string SELECTOR_ATTRIBUTE = "selector";
private readonly string REF_ATTRIBUTE = "ref";
private readonly string METHOD_ATTRIBUTE = "method";
private readonly string DESTINATION_RESOLVER_ATTRIBUTE = "destination-resolver";
private readonly string MESSAGE_CONVERTER_ATTRIBUTE = "message-converter";
private readonly string RESPONSE_DESTINATION_ATTRIBUTE = "response-destination";
private readonly string DESTINATION_TYPE_ATTRIBUTE = "destination-type";
private readonly string DESTINATION_TYPE_QUEUE = "queue";
private readonly string DESTINATION_TYPE_TOPIC = "topic";
private readonly string DESTINATION_TYPE_DURABLE_TOPIC = "durableTopic";
private readonly string CLIENT_ID_ATTRIBUTE = "client-id";
private readonly string ACKNOWLEDGE_ATTRIBUTE = "acknowledge";
private readonly string ACKNOWLEDGE_AUTO = "auto";
private readonly string ACKNOWLEDGE_CLIENT = "client";
private readonly string ACKNOWLEDGE_DUPS_OK = "dups-ok";
private readonly string ACKNOWLEDGE_TRANSACTED = "transacted";
private readonly string CONCURRENCY_ATTRIBUTE = "concurrency";
private readonly string RECOVERY_INTERVAL_ATTRIBUTE = "recovery-interval";
private readonly string MAX_RECOVERY_TIME_ATTRIBUTE = "max-recovery-time";
private readonly string CONNECTION_FACTORY_ATTRIBUTE = "connection-factory";
private readonly string CONTAINER_CUSTOM_TYPE = "container-custom-type";
private readonly string PUBSUB_DOMAIN_ATTRIBUTE = "pubsub-domain";
private readonly string AUTO_STARTUP = "auto-startup";
private readonly string ERROR_HANDLER_ATTRIBUTE = "error-handler";
private readonly string EXCEPTION_LISTENER_ATTRIBUTE = "exception-listener";
#endregion
#region IObjectDefinitionParser Members
/// <summary>
/// Parse the specified XmlElement and register the resulting
/// ObjectDefinitions with the <see cref="ParserContext.Registry"/> IObjectDefinitionRegistry
/// embedded in the supplied <see cref="ParserContext"/>
/// </summary>
/// <param name="element">The element to be parsed.</param>
/// <param name="parserContext">The object encapsulating the current state of the parsing process.
/// Provides access to a IObjectDefinitionRegistry</param>
/// <returns>The primary object definition.</returns>
/// <remarks>
/// <p>
/// This method is never invoked if the parser is namespace aware
/// and was called to process the root node.
/// </p>
/// </remarks>
public IObjectDefinition ParseElement(XmlElement element, ParserContext parserContext)
{
XmlNodeList childNodes = element.ChildNodes;
foreach (XmlNode childNode in childNodes)
{
if (childNode.NodeType == XmlNodeType.Element)
{
string localName = childNode.LocalName;
if (LISTENER_ELEMENT.Equals(localName))
{
ParseListener((XmlElement) childNode, element, parserContext);
}
}
}
return null;
}
#endregion
private void ParseListener(XmlElement listenerElement, XmlElement containerElement, ParserContext parserContext)
{
ObjectDefinitionBuilder listenerDefBuilder =
parserContext.ParserHelper.CreateRootObjectDefinitionBuilder(typeof (MessageListenerAdapter));
string reference = listenerElement.GetAttribute(REF_ATTRIBUTE);
if (!StringUtils.HasText(reference))
{
parserContext.ReaderContext.ReportException(listenerElement, LISTENER_ELEMENT,
"Listener '" + REF_ATTRIBUTE +
"' attribute contains empty value.");
}
listenerDefBuilder.AddPropertyValue("HandlerObject", new RuntimeObjectReference(reference));
string handlerMethod = null;
if (listenerElement.HasAttribute(METHOD_ATTRIBUTE))
{
handlerMethod = listenerElement.GetAttribute(METHOD_ATTRIBUTE);
{
if (!StringUtils.HasText(handlerMethod))
{
parserContext.ReaderContext.ReportException(listenerElement, LISTENER_ELEMENT,
"Listener '" + METHOD_ATTRIBUTE +
"' attribute contains empty value.");
}
}
}
listenerDefBuilder.AddPropertyValue("DefaultHandlerMethod", handlerMethod);
if (containerElement.HasAttribute(MESSAGE_CONVERTER_ATTRIBUTE))
{
string messageConverter = containerElement.GetAttribute(MESSAGE_CONVERTER_ATTRIBUTE);
listenerDefBuilder.AddPropertyValue("MessageConverter", new RuntimeObjectReference(messageConverter));
}
ObjectDefinitionBuilder containerDefBuilder = ParseContainer(listenerElement, containerElement, parserContext);
if (listenerElement.HasAttribute(RESPONSE_DESTINATION_ATTRIBUTE))
{
string responseDestination = listenerElement.GetAttribute(RESPONSE_DESTINATION_ATTRIBUTE);
bool pubSubDomain = IndicatesPubSub(containerDefBuilder.RawObjectDefinition);
listenerDefBuilder.AddPropertyValue(pubSubDomain ? "DefaultResponseTopicName" : "DefaultResponseQueueName",
responseDestination);
if (containerDefBuilder.RawObjectDefinition.PropertyValues.Contains("DestinationResolver"))
{
listenerDefBuilder.AddPropertyValue("DestinationResolver",
containerDefBuilder.RawObjectDefinition.PropertyValues.GetPropertyValue
(
"DestinationResolver").Value);
}
}
containerDefBuilder.AddPropertyValue("MessageListener", listenerDefBuilder.ObjectDefinition);
string containerObjectName = listenerElement.GetAttribute(ID_ATTRIBUTE);
// If no object id is given auto generate one using the ReaderContext's ObjectNameGenerator
if (!StringUtils.HasText(containerObjectName))
{
containerObjectName =
parserContext.ReaderContext.GenerateObjectName(containerDefBuilder.RawObjectDefinition);
}
string pubsubDomain = listenerElement.GetAttribute(PUBSUB_DOMAIN_ATTRIBUTE);
containerDefBuilder.AddPropertyValue("PubSubDomain", pubsubDomain);
parserContext.Registry.RegisterObjectDefinition(containerObjectName, containerDefBuilder.ObjectDefinition);
}
private ObjectDefinitionBuilder ParseContainer(XmlElement listenerElement, XmlElement containerElement,
ParserContext parserContext)
{
//Only support SimpleMessageListenerContainer or container-custom-type
Type containerType = typeof(SimpleMessageListenerContainer);
if (containerElement.HasAttribute(CONTAINER_CUSTOM_TYPE))
{
string customType = containerElement.GetAttribute(CONTAINER_CUSTOM_TYPE);
if (!StringUtils.HasLength(customType))
{
parserContext.ReaderContext.ReportException(containerElement, CONTAINER_CUSTOM_TYPE,
"Listener container '" + CONTAINER_CUSTOM_TYPE +
"' attribute contains empty value.");
}
try
{
containerType = TypeResolutionUtils.ResolveType(customType);
}
catch (Exception ex)
{
parserContext.ReaderContext.ReportException(containerElement, CONTAINER_CUSTOM_TYPE,
"Invalid container-custom-type value [" + customType + "]", ex);
}
}
//Only support SimpleMessageListenerContainer
ObjectDefinitionBuilder containerDef =
parserContext.ParserHelper.CreateRootObjectDefinitionBuilder(containerType);
ParseListenerConfiguration(listenerElement, parserContext, containerDef);
ParseContainerConfiguration(containerElement, parserContext, containerDef);
if (containerElement.HasAttribute(AUTO_STARTUP))
{
string autoStartup = containerElement.GetAttribute(AUTO_STARTUP);
if (StringUtils.HasText(autoStartup))
{
containerDef.AddPropertyValue("AutoStartup", autoStartup);
}
}
string connectionFactoryObjectName = "connectionFactory";
if (containerElement.HasAttribute(CONNECTION_FACTORY_ATTRIBUTE))
{
connectionFactoryObjectName = containerElement.GetAttribute(CONNECTION_FACTORY_ATTRIBUTE);
if (!StringUtils.HasText(connectionFactoryObjectName))
{
parserContext.ReaderContext.ReportException(listenerElement, LISTENER_ELEMENT,
"Listener container '" + CONNECTION_FACTORY_ATTRIBUTE +
"' attribute contains empty value.");
}
}
containerDef.AddPropertyValue("ConnectionFactory", new RuntimeObjectReference(connectionFactoryObjectName));
string errorHandlerObjectName = containerElement.GetAttribute(ERROR_HANDLER_ATTRIBUTE);
if (StringUtils.HasText(errorHandlerObjectName))
{
containerDef.AddPropertyValue("ErrorHandler",
new RuntimeObjectReference(errorHandlerObjectName));
}
string exceptionListenerObjectName = containerElement.GetAttribute(EXCEPTION_LISTENER_ATTRIBUTE);
if (StringUtils.HasText(exceptionListenerObjectName))
{
containerDef.AddPropertyValue("ExceptionListener",
new RuntimeObjectReference(exceptionListenerObjectName));
}
string destinationResolverObjectName = containerElement.GetAttribute(DESTINATION_RESOLVER_ATTRIBUTE);
if (StringUtils.HasText(destinationResolverObjectName))
{
containerDef.AddPropertyValue("DestinationResolver",
new RuntimeObjectReference(destinationResolverObjectName));
}
string acknowledge = containerElement.GetAttribute(ACKNOWLEDGE_ATTRIBUTE);
if (StringUtils.HasText(acknowledge))
{
int acknowledgementMode = ParseAcknowledgementMode(containerElement, parserContext);
containerDef.AddPropertyValue("SessionAcknowledgeMode", acknowledgementMode);
}
string concurrency = ParseConcurrency(containerElement, parserContext);
if (concurrency != null)
{
containerDef.AddPropertyValue("ConcurrentConsumers", concurrency);
}
containerDef.AddPropertyValue("RecoveryInterval", ParseRecoveryInterval(containerElement, parserContext));
containerDef.AddPropertyValue("MaxRecoveryTime", ParseMaxRecoveryTime(containerElement, parserContext));
return containerDef;
}
private bool IndicatesPubSub(AbstractObjectDefinition configDef)
{
return (bool) configDef.PropertyValues.GetPropertyValue("PubSubDomain").Value;
}
private void ParseListenerConfiguration(XmlElement ele, ParserContext parserContext,
ObjectDefinitionBuilder containerDef)
{
string destination = ele.GetAttribute(DESTINATION_ATTRIBUTE);
if (!StringUtils.HasText(destination))
{
parserContext.ReaderContext.ReportException(ele, LISTENER_ELEMENT,
"Listener '" + DESTINATION_ATTRIBUTE +
"' attribute contains empty value.");
}
containerDef.AddPropertyValue("DestinationName", destination);
if (ele.HasAttribute(SUBSCRIPTION_ATTRIBUTE))
{
string subscription = ele.GetAttribute(SUBSCRIPTION_ATTRIBUTE);
if (!StringUtils.HasText(subscription))
{
parserContext.ReaderContext.ReportException(ele, SUBSCRIPTION_ATTRIBUTE,
"Listener '" + SUBSCRIPTION_ATTRIBUTE +
"' attribute contains empty value.");
}
containerDef.AddPropertyValue("DurableSubscriptionName", subscription);
}
if (ele.HasAttribute(SELECTOR_ATTRIBUTE))
{
string selector = ele.GetAttribute(SELECTOR_ATTRIBUTE);
if (!StringUtils.HasText(selector))
{
parserContext.ReaderContext.ReportException(ele, selector,
"Listener '" + SELECTOR_ATTRIBUTE +
"' attribute contains empty value.");
}
containerDef.AddPropertyValue("MessageSelector", selector);
}
}
private void ParseContainerConfiguration(XmlElement ele, ParserContext parserContext,
ObjectDefinitionBuilder containerDef)
{
string destinationType = ele.GetAttribute(DESTINATION_TYPE_ATTRIBUTE);
bool pubSubDomain = false;
bool subscriptionDurable = false;
if (DESTINATION_TYPE_DURABLE_TOPIC.Equals(destinationType))
{
pubSubDomain = true;
subscriptionDurable = true;
}
else if (DESTINATION_TYPE_TOPIC.Equals(destinationType))
{
pubSubDomain = true;
}
else if ("".Equals(destinationType) || DESTINATION_TYPE_QUEUE.Equals(destinationType))
{
// the default: queue
}
else
{
parserContext.ReaderContext.ReportException(ele, destinationType,
"Invalid listener container '" + DESTINATION_TYPE_ATTRIBUTE +
"': only 'queue', 'topic' and 'durableTopic' supported");
}
containerDef.AddPropertyValue("PubSubDomain", pubSubDomain);
containerDef.AddPropertyValue("SubscriptionDurable", subscriptionDurable);
if (ele.HasAttribute(CLIENT_ID_ATTRIBUTE))
{
string clientId = ele.GetAttribute(CLIENT_ID_ATTRIBUTE);
if (!StringUtils.HasText(clientId))
{
parserContext.ReaderContext.ReportException(ele, clientId,
"Listener '" + CLIENT_ID_ATTRIBUTE +
"' attribute contains empty value.");
}
containerDef.AddPropertyValue("ClientId", clientId);
}
}
private int ParseAcknowledgementMode(XmlElement element, ParserContext parserContext)
{
string acknowledge = element.GetAttribute(ACKNOWLEDGE_ATTRIBUTE);
if (acknowledge.Equals(ACKNOWLEDGE_TRANSACTED))
{
return TIBCO.EMS.Session.SESSION_TRANSACTED;
}
else if (acknowledge.Equals(ACKNOWLEDGE_DUPS_OK))
{
return TIBCO.EMS.Session.DUPS_OK_ACKNOWLEDGE;
}
else if (acknowledge.Equals(ACKNOWLEDGE_CLIENT))
{
return TIBCO.EMS.Session.CLIENT_ACKNOWLEDGE;
}
//TODO other ack modes.
else if (!acknowledge.Equals(ACKNOWLEDGE_AUTO))
{
parserContext.ReaderContext.ReportException(element, ACKNOWLEDGE_ATTRIBUTE,
"Invalid listener container 'acknowledge' setting ['" +
acknowledge +
"]: only \"auto\", \"client\", \"dups-ok\" and \"transacted\" supported.");
}
return TIBCO.EMS.Session.AUTO_ACKNOWLEDGE;
}
private string ParseConcurrency(XmlElement ele, ParserContext parserContext)
{
string concurrency = ele.GetAttribute(CONCURRENCY_ATTRIBUTE);
if (!StringUtils.HasText(concurrency))
{
return null;
}
else
{
return concurrency;
}
}
private string ParseRecoveryInterval(XmlElement ele, ParserContext parserContext)
{
string recoveryInterval = ele.GetAttribute(RECOVERY_INTERVAL_ATTRIBUTE);
if (StringUtils.HasText(recoveryInterval))
{
return recoveryInterval;
}
else
{
return SimpleMessageListenerContainer.DEFAULT_RECOVERY_INTERVAL;
}
}
private string ParseMaxRecoveryTime(XmlElement ele, ParserContext parserContext)
{
string recoverTime = ele.GetAttribute(MAX_RECOVERY_TIME_ATTRIBUTE);
if (StringUtils.HasText(recoverTime))
{
return recoverTime;
}
else
{
return SimpleMessageListenerContainer.DEFAULT_MAX_RECOVERY_TIME;
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: UserSetting.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 MyJiraWork.Core.Utils {
/// <summary>Holder for reflection information generated from UserSetting.proto</summary>
public static partial class UserSettingReflection {
#region Descriptor
/// <summary>File descriptor for UserSetting.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static UserSettingReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChFVc2VyU2V0dGluZy5wcm90bxIIdHV0b3JpYWwilwEKC1VzZXJTZXR0aW5n",
"EhkKEUppcmFTZXJ2ZXJBZGRyZXNzGAEgASgJEhQKDEppcmFVc2VyTmFtZRgC",
"IAEoCRIUCgxKaXJhUGFzc3dvcmQYAyABKAkSEwoLUHJveHlTZXJ2ZXIYBCAB",
"KAkSFQoNUHJveHlVc2VyTmFtZRgFIAEoCRIVCg1Qcm94eVBhc3N3b3JkGAYg",
"ASgJQhiqAhVNeUppcmFXb3JrLkNvcmUuVXRpbHNiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::MyJiraWork.Core.Utils.UserSetting), global::MyJiraWork.Core.Utils.UserSetting.Parser, new[]{ "JiraServerAddress", "JiraUserName", "JiraPassword", "ProxyServer", "ProxyUserName", "ProxyPassword" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// [START messages]
/// </summary>
public sealed partial class UserSetting : pb::IMessage<UserSetting> {
private static readonly pb::MessageParser<UserSetting> _parser = new pb::MessageParser<UserSetting>(() => new UserSetting());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UserSetting> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::MyJiraWork.Core.Utils.UserSettingReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UserSetting() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UserSetting(UserSetting other) : this() {
jiraServerAddress_ = other.jiraServerAddress_;
jiraUserName_ = other.jiraUserName_;
jiraPassword_ = other.jiraPassword_;
proxyServer_ = other.proxyServer_;
proxyUserName_ = other.proxyUserName_;
proxyPassword_ = other.proxyPassword_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UserSetting Clone() {
return new UserSetting(this);
}
/// <summary>Field number for the "JiraServerAddress" field.</summary>
public const int JiraServerAddressFieldNumber = 1;
private string jiraServerAddress_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JiraServerAddress {
get { return jiraServerAddress_; }
set {
jiraServerAddress_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "JiraUserName" field.</summary>
public const int JiraUserNameFieldNumber = 2;
private string jiraUserName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JiraUserName {
get { return jiraUserName_; }
set {
jiraUserName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "JiraPassword" field.</summary>
public const int JiraPasswordFieldNumber = 3;
private string jiraPassword_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JiraPassword {
get { return jiraPassword_; }
set {
jiraPassword_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "ProxyServer" field.</summary>
public const int ProxyServerFieldNumber = 4;
private string proxyServer_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProxyServer {
get { return proxyServer_; }
set {
proxyServer_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "ProxyUserName" field.</summary>
public const int ProxyUserNameFieldNumber = 5;
private string proxyUserName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProxyUserName {
get { return proxyUserName_; }
set {
proxyUserName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "ProxyPassword" field.</summary>
public const int ProxyPasswordFieldNumber = 6;
private string proxyPassword_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProxyPassword {
get { return proxyPassword_; }
set {
proxyPassword_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UserSetting);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UserSetting other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (JiraServerAddress != other.JiraServerAddress) return false;
if (JiraUserName != other.JiraUserName) return false;
if (JiraPassword != other.JiraPassword) return false;
if (ProxyServer != other.ProxyServer) return false;
if (ProxyUserName != other.ProxyUserName) return false;
if (ProxyPassword != other.ProxyPassword) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (JiraServerAddress.Length != 0) hash ^= JiraServerAddress.GetHashCode();
if (JiraUserName.Length != 0) hash ^= JiraUserName.GetHashCode();
if (JiraPassword.Length != 0) hash ^= JiraPassword.GetHashCode();
if (ProxyServer.Length != 0) hash ^= ProxyServer.GetHashCode();
if (ProxyUserName.Length != 0) hash ^= ProxyUserName.GetHashCode();
if (ProxyPassword.Length != 0) hash ^= ProxyPassword.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 (JiraServerAddress.Length != 0) {
output.WriteRawTag(10);
output.WriteString(JiraServerAddress);
}
if (JiraUserName.Length != 0) {
output.WriteRawTag(18);
output.WriteString(JiraUserName);
}
if (JiraPassword.Length != 0) {
output.WriteRawTag(26);
output.WriteString(JiraPassword);
}
if (ProxyServer.Length != 0) {
output.WriteRawTag(34);
output.WriteString(ProxyServer);
}
if (ProxyUserName.Length != 0) {
output.WriteRawTag(42);
output.WriteString(ProxyUserName);
}
if (ProxyPassword.Length != 0) {
output.WriteRawTag(50);
output.WriteString(ProxyPassword);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (JiraServerAddress.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JiraServerAddress);
}
if (JiraUserName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JiraUserName);
}
if (JiraPassword.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JiraPassword);
}
if (ProxyServer.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProxyServer);
}
if (ProxyUserName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProxyUserName);
}
if (ProxyPassword.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProxyPassword);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UserSetting other) {
if (other == null) {
return;
}
if (other.JiraServerAddress.Length != 0) {
JiraServerAddress = other.JiraServerAddress;
}
if (other.JiraUserName.Length != 0) {
JiraUserName = other.JiraUserName;
}
if (other.JiraPassword.Length != 0) {
JiraPassword = other.JiraPassword;
}
if (other.ProxyServer.Length != 0) {
ProxyServer = other.ProxyServer;
}
if (other.ProxyUserName.Length != 0) {
ProxyUserName = other.ProxyUserName;
}
if (other.ProxyPassword.Length != 0) {
ProxyPassword = other.ProxyPassword;
}
}
[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: {
JiraServerAddress = input.ReadString();
break;
}
case 18: {
JiraUserName = input.ReadString();
break;
}
case 26: {
JiraPassword = input.ReadString();
break;
}
case 34: {
ProxyServer = input.ReadString();
break;
}
case 42: {
ProxyUserName = input.ReadString();
break;
}
case 50: {
ProxyPassword = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections;
namespace Fonet.Pdf
{
/// <summary>
/// Class that defines a mapping between character codes (CIDs)
/// to a character selector (Identity-H encoding)
/// </summary>
public class PdfCMap : PdfContentStream
{
public const string DefaultName = "Adobe-Identity-UCS";
private PdfCIDSystemInfo systemInfo;
private SortedList ranges;
public PdfCMap(PdfObjectId id)
: base(id)
{
this.ranges = new SortedList();
}
public PdfCIDSystemInfo SystemInfo
{
set
{
this.systemInfo = value;
}
}
/// <summary>
/// Adds the supplied glyph -> unicode pairs.
/// </summary>
/// <remarks>
/// Both the key and value must be a ushort.
/// </remarks>
/// <param name="map"></param>
public void AddBfRanges(IDictionary map)
{
foreach (DictionaryEntry entry in map)
{
AddBfRange(
Convert.ToUInt16(entry.Key),
Convert.ToUInt16(entry.Value));
}
}
/// <summary>
/// Adds the supplied glyph index to unicode value mapping.
/// </summary>
/// <param name="glyphIndex"></param>
/// <param name="unicodeValue"></param>
public void AddBfRange(ushort glyphIndex, ushort unicodeValue)
{
ranges.Add(glyphIndex, unicodeValue);
}
/// <summary>
/// Overriden to create CMap content stream.
/// </summary>
/// <param name="writer"></param>
protected internal override void Write(PdfWriter writer)
{
WriteLine("/CIDInit /ProcSet findresource begin");
WriteLine("12 dict begin");
WriteLine("begincmap");
WriteLine("/CIDSystemInfo");
WriteLine(systemInfo);
WriteLine("def");
WriteLine(String.Format("/CMapName /{0} def", DefaultName));
WriteLine("/CMapType 2 def");
// No bfranges represents an error - we should really through an exception
if (ranges.Count > 0)
{
// Groups CMap entries into bfranges
BfEntryList groups = GroupCMapEntries();
// Write out the codespace ranges
WriteCodespaceRange(groups);
// Write out GID to Unicode mappings
WriteBfChars(groups);
WriteBfRanges(groups);
}
WriteLine("endcmap");
WriteLine("CMapName currentdict /CMap defineresource pop");
WriteLine("end");
Write("end");
base.Write(writer);
}
private void WriteCodespaceRange(BfEntryList entries)
{
BfEntry first = entries[0];
BfEntry last = entries[entries.Count - 1];
WriteLine("1 begincodespacerange");
WriteLine(String.Format("<{0:X4}> <{1:X4}>",
first.StartGlyphIndex, last.EndGlyphIndex));
WriteLine("endcodespacerange");
}
/// <summary>
/// Writes the bfchar entries to the content stream in groups of 100.
/// </summary>
/// <param name="entries"></param>
private void WriteBfChars(BfEntryList entries)
{
// bfchar entries must be grouped in blocks of 100
BfEntry[] charEntries = entries.Chars;
int numBlocks = (charEntries.Length / 100) + (((charEntries.Length % 100) > 0) ? 1 : 0);
for (int i = 0; i < numBlocks; i++)
{
int blockSize = 0;
if ((i + 1) == numBlocks)
{
blockSize = charEntries.Length - (i * 100);
}
else
{
blockSize = 100;
}
WriteLine(String.Format("{0} beginbfchar", blockSize));
for (int j = 0; j < blockSize; j++)
{
BfEntry entry = charEntries[(i * 100) + j];
WriteLine(String.Format("<{0:X4}> <{1:X4}>",
entry.StartGlyphIndex,
entry.UnicodeValue));
}
WriteLine("endbfchar");
}
}
/// <summary>
/// Writes the bfrange entries to the content stream in groups of 100.
/// </summary>
/// <param name="entries"></param>
private void WriteBfRanges(BfEntryList entries)
{
// bfrange entries must be grouped in blocks of 100
BfEntry[] rangeEntries = entries.Ranges;
int numBlocks = (rangeEntries.Length / 100) + (((rangeEntries.Length % 100) > 0) ? 1 : 0);
for (int i = 0; i < numBlocks; i++)
{
int blockSize = 0;
if ((i + 1) == numBlocks)
{
blockSize = rangeEntries.Length - (i * 100);
}
else
{
blockSize = 100;
}
WriteLine(String.Format("{0} beginbfrange", blockSize));
for (int j = 0; j < blockSize; j++)
{
BfEntry entry = rangeEntries[(i * 100) + j];
WriteLine(String.Format("<{0:X4}> <{1:X4}> <{2:X4}>",
entry.StartGlyphIndex,
entry.EndGlyphIndex,
entry.UnicodeValue));
}
WriteLine("endbfrange");
}
}
private BfEntryList GroupCMapEntries()
{
// List of grouped bfranges
BfEntryList groups = new BfEntryList();
ushort prevGlyphIndex = (ushort)ranges.GetKey(0);
ushort prevUnicodeValue = (ushort)ranges[prevGlyphIndex];
BfEntry range = new BfEntry(prevGlyphIndex, prevUnicodeValue);
groups.Add(range);
for (int i = 1; i < ranges.Count; i++)
{
ushort glyphIndex = (ushort)ranges.GetKey(i);
ushort unicodeValue = (ushort)ranges[glyphIndex];
if (unicodeValue == prevUnicodeValue + 1 &&
glyphIndex == prevGlyphIndex + 1)
{
// Contingous block - use existing range
range.IncrementEndIndex();
}
else
{
// Non-contiguous block - start new range
range = new BfEntry(glyphIndex, unicodeValue);
groups.Add(range);
}
prevGlyphIndex = glyphIndex;
prevUnicodeValue = unicodeValue;
}
return groups;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace RRLab.Utilities
{
public partial class DataSetHistogramControl : UserControl, INotifyPropertyChanged
{
public event EventHandler DataSetChanged;
private DataSet _DataSet;
[Bindable(true)]
public DataSet DataSet
{
get { return _DataSet; }
set {
if (DataSet != null && Table != null && DataSet.Tables.Contains(Table)) DataSet.Tables[Table].ColumnChanged -= new DataColumnChangeEventHandler(OnDataTableColumnChanged);
_DataSet = value;
if (DataSet != null && Table != null && DataSet.Tables.Contains(Table)) DataSet.Tables[Table].ColumnChanged -= new DataColumnChangeEventHandler(OnDataTableColumnChanged);
OnDataSetChanged(EventArgs.Empty);
NotifyPropertyChanged("DataSet");
}
}
public event EventHandler TableChanged;
private string _Table;
[Bindable(true)]
public string Table
{
get { return _Table; }
set {
if (DataSet != null && Table != null && DataSet.Tables.Contains(Table)) DataSet.Tables[Table].ColumnChanged -= new DataColumnChangeEventHandler(OnDataTableColumnChanged);
_Table = value;
if (DataSet != null && Table != null && DataSet.Tables.Contains(Table)) DataSet.Tables[Table].ColumnChanged += new DataColumnChangeEventHandler(OnDataTableColumnChanged);
OnTableChanged(EventArgs.Empty);
NotifyPropertyChanged("Table");
}
}
public event EventHandler ColumnChanged;
private string _Column;
[Bindable(true)]
public string Column
{
get { return _Column; }
set {
_Column = value;
OnColumnChanged(EventArgs.Empty);
NotifyPropertyChanged("XColumn");
}
}
public event EventHandler FilterChanged;
private string _Filter;
[Bindable(true)]
public string Filter
{
get { return _Filter; }
set {
_Filter = value;
OnFilterChanged(EventArgs.Empty);
NotifyPropertyChanged("Filter");
}
}
public event EventHandler TitleChanged;
private string _Title;
[Bindable(true)]
[SettingsBindable(true)]
public string Title
{
get { return _Title; }
set {
_Title = value;
OnTitleChanged(EventArgs.Empty);
NotifyPropertyChanged("Title");
}
}
private Color _GraphColor = Color.LightGoldenrodYellow;
[SettingsBindable(true)]
[Bindable(true)]
public Color GraphColor
{
get { return _GraphColor; }
set { _GraphColor = value; }
}
private Color _BarColor = Color.Crimson;
[SettingsBindable(true)]
[Bindable(true)]
public Color BarColor
{
get { return _BarColor; }
set { _BarColor = value; }
}
private ZedGraph.BarItem _BarPlot;
protected ZedGraph.BarItem BarPlot
{
get { return _BarPlot; }
set { _BarPlot = value; }
}
public DataSetHistogramControl()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
RefreshGraph();
base.OnLoad(e);
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string property)
{
if(PropertyChanged != null)
try {
PropertyChanged(this, new PropertyChangedEventArgs(property));
} catch(Exception e) { ; }
}
#endregion
protected virtual void OnTitleChanged(EventArgs e)
{
RefreshGraph();
if (TitleChanged != null) TitleChanged(this, e);
}
protected virtual void OnColumnChanged(EventArgs e)
{
CalculateHistogram();
if (ColumnChanged != null) ColumnChanged(this, e);
}
protected virtual void OnFilterChanged(EventArgs e)
{
CalculateHistogram();
if (FilterChanged != null) FilterChanged(this, e);
}
protected virtual void OnTableChanged(EventArgs e)
{
CalculateHistogram();
if (TableChanged != null) TableChanged(this, e);
}
protected virtual void OnDataSetChanged(EventArgs e)
{
CalculateHistogram();
if (DataSetChanged != null) DataSetChanged(this, e);
}
public virtual void RefreshGraph()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(RefreshGraph));
return;
}
if (_HistogramData == null) CalculateHistogram();
ConfigureGraph();
ConfigureAxes();
ConfigurePlots();
ConfigureCurves();
if (HistogramData.Count != 0)
try
{
GraphControl.AxisChange();
}
catch (Exception e) { ; }
GraphControl.Invalidate();
}
protected virtual void ResetGraph()
{
GraphControl.GraphPane.CurveList.Clear();
}
protected virtual void ConfigureGraph()
{
GraphControl.GraphPane.Title.Text = Title;
GraphControl.GraphPane.Title.FontSpec.Size = 30;
GraphControl.GraphPane.Legend.IsVisible = false;
GraphControl.GraphPane.Chart.Fill.Color = GraphColor;
GraphControl.GraphPane.Chart.Fill.Type = ZedGraph.FillType.GradientByY;
}
protected virtual void ConfigureAxes()
{
if (DataSet == null || Table == null || Column == null || Table == "" || Column == "") return;
if (CategorizeByDate)
{
GraphControl.GraphPane.XAxis.Type = ZedGraph.AxisType.Date;
}
else
{
GraphControl.GraphPane.XAxis.Type = ZedGraph.AxisType.Linear;
GraphControl.GraphPane.XAxis.Scale.FormatAuto = true;
}
GraphControl.GraphPane.XAxis.Title.Text = DataSet.Tables[Table].Columns[Column].Caption ?? Column;
GraphControl.GraphPane.XAxis.Title.FontSpec.Size = 20F;
GraphControl.GraphPane.XAxis.Scale.MinAuto = true;
GraphControl.GraphPane.XAxis.Scale.MaxAuto = true;
GraphControl.GraphPane.XAxis.Scale.FontSpec.Size = 20F;
GraphControl.GraphPane.YAxis.Title.Text = "Number";
GraphControl.GraphPane.YAxis.Title.FontSpec.Size = 20F;
GraphControl.GraphPane.YAxis.Scale.MinAuto = true;
GraphControl.GraphPane.YAxis.Scale.MaxAuto = true;
GraphControl.GraphPane.YAxis.Scale.FontSpec.Size = 20F;
GraphControl.GraphPane.YAxis.Scale.Format = "N0";
}
private ZedGraph.IPointList _Points;
protected ZedGraph.IPointList Points
{
get { return _Points; }
set { _Points = value; }
}
protected virtual void ConfigurePlots()
{
double[] x = new double[HistogramData.Keys.Count];
double[] y = new double[HistogramData.Keys.Count];
for (int i = 0; i < HistogramData.Keys.Count; i++)
{
x[i] = _HistogramData.Keys[i];
y[i] = (double) _HistogramData.Values[i];
}
Points = new ZedGraph.PointPairList(x, y);
}
protected virtual void ConfigureCurves()
{
if (BarPlot == null)
BarPlot = GraphControl.GraphPane.AddBar(Column, Points, BarColor);
else
{
BarPlot.Points = Points;
BarPlot.Label.Text = Column;
BarPlot.Color = BarColor;
}
}
private SortedList<double, int> _HistogramData = new SortedList<double,int>();
public IDictionary<double, int> HistogramData
{
get { return _HistogramData; }
}
protected bool CategorizeByDate
{
get
{
if (DataSet != null && Table != null && Column != null && Table != "" && Column != "")
return DataSet.Tables[Table].Columns[Column].DataType == typeof(DateTime);
else return false;
}
}
protected virtual void CalculateHistogram()
{
if (DataSet == null || Table == null || Column == null)
{
_HistogramData = new SortedList<double, int>();
RefreshGraph();
return;
}
if (CategorizeByDate)
{
CalculateHistogramByDateTime();
return;
}
_HistogramData = new SortedList<double, int>();
DataRow[] rows = DataSet.Tables[Table].Select(Filter);
List<double> values = new List<double>(rows.Length);
foreach (DataRow row in rows)
if (!row.IsNull(Column))
if (row[Column] is TimeSpan)
values.Add(((TimeSpan)row[Column]).TotalMinutes);
else values.Add(Convert.ToDouble(row[Column]));
values.TrimExcess();
values.Sort();
double min = values[0];
double max = values[values.Count-1];
int nBins = Convert.ToInt32(Math.Sqrt(values.Count));
double binWidth = Math.Abs(max - min) / ((double)nBins);
for (double i = min; i < max + binWidth; i += binWidth)
_HistogramData.Add(i, 0);
for (int i = 0; i < values.Count; i++)
{
int bin = Convert.ToInt32((values[i] - min) / binWidth);
_HistogramData[_HistogramData.Keys[bin]]++;
}
RefreshGraph();
}
protected virtual void CalculateHistogramByDateTime()
{
_HistogramData = new SortedList<double, int>();
DataRow[] rows = DataSet.Tables[Table].Select(Filter);
List<DateTime> values = new List<DateTime>(rows.Length);
foreach (DataRow row in rows)
if (!row.IsNull(Column))
values.Add((DateTime)row[Column]);
values.TrimExcess();
values.Sort();
DateTime min = values[0];
DateTime max = values[values.Count - 1];
TimeSpan span = max - min;
int nBins = Convert.ToInt32(Math.Sqrt(values.Count));
int nExtraBins_Dates = Convert.ToInt32(Math.Abs(nBins - span.TotalDays));
int nExtraBins_Hours = Convert.ToInt32(Math.Abs(nBins - span.TotalHours));
int nExtraBins_Minutes = Convert.ToInt32(Math.Abs(nBins - span.TotalMinutes));
bool useDates = nExtraBins_Dates < nExtraBins_Hours && nExtraBins_Dates < nExtraBins_Minutes;
bool useHours = nExtraBins_Hours < nExtraBins_Dates && nExtraBins_Hours < nExtraBins_Minutes;
for (ZedGraph.XDate i = min.ToOADate(); i < max.ToOADate();)
{
DateTime dateTime = DateTime.FromOADate(i);
ZedGraph.XDate x;
if (useDates) x = new ZedGraph.XDate(dateTime.Year, dateTime.Month, dateTime.Day);
else if (useHours) x = new ZedGraph.XDate(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0);
else x = new ZedGraph.XDate(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0);
_HistogramData.Add(x, 0);
if (useDates) i.AddDays(1);
else if (useHours) i.AddHours(1);
else i.AddMinutes(1);
}
if (useDates) GraphControl.GraphPane.XAxis.Scale.Format = "d";
else if (useHours) GraphControl.GraphPane.XAxis.Scale.Format = "g";
else GraphControl.GraphPane.XAxis.Scale.Format = "g";
for (int i = 0; i < values.Count; i++)
{
DateTime dateTime = (DateTime) rows[i][Column];
_HistogramData[new ZedGraph.XDate(dateTime.Year, dateTime.Month, dateTime.Day)]++;
}
RefreshGraph();
}
protected virtual void OnDataTableColumnChanged(object sender, DataColumnChangeEventArgs e)
{
if (e.Column.ColumnName == Column) CalculateHistogram();
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace PackageEditor
{
/// <summary>
/// Inherited ListView to allow in-place editing of subitems
/// </summary>
public class ListViewEx : System.Windows.Forms.ListView
{
#region Interop structs, imports and constants
#pragma warning disable 649 // Disable compiler message "Field X is never assigned to"
/// <summary>
/// MessageHeader for WM_NOTIFY
/// </summary>
private struct NMHDR
{
public IntPtr hwndFrom;
public Int32 idFrom;
public Int32 code;
}
#pragma warning restore 649
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wPar, IntPtr lPar);
[DllImport("user32.dll", CharSet=CharSet.Ansi)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, int len, ref int [] order);
// ListView messages
private const int LVM_FIRST = 0x1000;
private const int LVM_GETCOLUMNORDERARRAY = (LVM_FIRST + 59);
// Windows Messages that will abort editing
private const int WM_HSCROLL = 0x114;
private const int WM_VSCROLL = 0x115;
private const int WM_SIZE = 0x05;
private const int WM_NOTIFY = 0x4E;
private const int HDN_FIRST = -300;
private const int HDN_BEGINDRAG = (HDN_FIRST-10);
private const int HDN_ITEMCHANGINGA = (HDN_FIRST-0);
private const int HDN_ITEMCHANGINGW = (HDN_FIRST-20);
#endregion
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public event SubItemEventHandler SubItemClicked;
public event SubItemEventHandler SubItemBeginEditing;
public event SubItemEndEditingEventHandler SubItemEndEditing;
public ListViewEx()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
base.FullRowSelect = true;
base.View = View.Details;
base.AllowColumnReorder = true;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
private bool _doubleClickActivation = false;
/// <summary>
/// Is a double click required to start editing a cell?
/// </summary>
public bool DoubleClickActivation
{
get { return _doubleClickActivation; }
set { _doubleClickActivation = value; }
}
/// <summary>
/// Retrieve the order in which columns appear
/// </summary>
/// <returns>Current display order of column indices</returns>
public int[] GetColumnOrder()
{
IntPtr lPar = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Columns.Count);
IntPtr res = SendMessage(Handle, LVM_GETCOLUMNORDERARRAY, new IntPtr(Columns.Count), lPar);
if (res.ToInt32() == 0) // Something went wrong
{
Marshal.FreeHGlobal(lPar);
return null;
}
int [] order = new int[Columns.Count];
Marshal.Copy(lPar, order, 0, Columns.Count);
Marshal.FreeHGlobal(lPar);
return order;
}
/// <summary>
/// Find ListViewItem and SubItem Index at position (x,y)
/// </summary>
/// <param name="x">relative to ListView</param>
/// <param name="y">relative to ListView</param>
/// <param name="item">Item at position (x,y)</param>
/// <returns>SubItem index</returns>
public int GetSubItemAt(int x, int y, out ListViewItem item)
{
item = this.GetItemAt(x, y);
if (item != null)
{
int[] order = GetColumnOrder();
Rectangle lviBounds;
int subItemX;
lviBounds = item.GetBounds(ItemBoundsPortion.Entire);
subItemX = lviBounds.Left;
for (int i=0; i<order.Length; i++)
{
ColumnHeader h = this.Columns[order[i]];
if (x < subItemX+h.Width)
{
return h.Index;
}
subItemX += h.Width;
}
}
return -1;
}
/// <summary>
/// Get bounds for a SubItem
/// </summary>
/// <param name="Item">Target ListViewItem</param>
/// <param name="SubItem">Target SubItem index</param>
/// <returns>Bounds of SubItem (relative to ListView)</returns>
public Rectangle GetSubItemBounds(ListViewItem Item, int SubItem)
{
int[] order = GetColumnOrder();
Rectangle subItemRect = Rectangle.Empty;
if (SubItem >= order.Length)
throw new IndexOutOfRangeException("SubItem "+SubItem+" out of range");
if (Item == null)
throw new ArgumentNullException("Item");
Rectangle lviBounds = Item.GetBounds(ItemBoundsPortion.Entire);
int subItemX = lviBounds.Left;
ColumnHeader col;
int i;
for (i=0; i<order.Length; i++)
{
col = this.Columns[order[i]];
if (col.Index == SubItem)
break;
subItemX += col.Width;
}
subItemRect = new Rectangle(subItemX, lviBounds.Top, this.Columns[order[i]].Width, lviBounds.Height);
return subItemRect;
}
protected override void WndProc(ref Message msg)
{
switch (msg.Msg)
{
// Look for WM_VSCROLL,WM_HSCROLL or WM_SIZE messages.
case WM_VSCROLL:
case WM_HSCROLL:
case WM_SIZE:
EndEditing(false);
break;
case WM_NOTIFY:
// Look for WM_NOTIFY of events that might also change the
// editor's position/size: Column reordering or resizing
NMHDR h = (NMHDR)Marshal.PtrToStructure(msg.LParam, typeof(NMHDR));
if (h.code == HDN_BEGINDRAG ||
h.code == HDN_ITEMCHANGINGA ||
h.code == HDN_ITEMCHANGINGW)
EndEditing(false);
break;
}
base.WndProc(ref msg);
}
#region Initialize editing depending of DoubleClickActivation property
protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e)
{
base.OnMouseUp(e);
if (DoubleClickActivation)
{
return;
}
EditSubitemAt(new Point(e.X, e.Y));
}
protected override void OnDoubleClick(EventArgs e)
{
base.OnDoubleClick (e);
if (!DoubleClickActivation)
{
return;
}
Point pt = this.PointToClient(Cursor.Position);
EditSubitemAt(pt);
}
///<summary>
/// Fire SubItemClicked
///</summary>
///<param name="p">Point of click/doubleclick</param>
private void EditSubitemAt(Point p)
{
ListViewItem item;
int idx = GetSubItemAt(p.X, p.Y, out item);
if (idx >= 0)
{
OnSubItemClicked(new SubItemEventArgs(item, idx));
}
}
#endregion
#region In-place editing functions
// The control performing the actual editing
private Control _editingControl;
// The LVI being edited
private ListViewItem _editItem;
// The SubItem being edited
private int _editSubItem;
protected void OnSubItemBeginEditing(SubItemEventArgs e)
{
if (SubItemBeginEditing != null)
SubItemBeginEditing(this, e);
}
protected void OnSubItemEndEditing(SubItemEndEditingEventArgs e)
{
if (SubItemEndEditing != null)
SubItemEndEditing(this, e);
}
protected void OnSubItemClicked(SubItemEventArgs e)
{
if (SubItemClicked != null)
SubItemClicked(this, e);
}
/// <summary>
/// Begin in-place editing of given cell
/// </summary>
/// <param name="c">Control used as cell editor</param>
/// <param name="Item">ListViewItem to edit</param>
/// <param name="SubItem">SubItem index to edit</param>
public void StartEditing(Control c, ListViewItem Item, int SubItem)
{
OnSubItemBeginEditing(new SubItemEventArgs(Item, SubItem));
Rectangle rcSubItem = GetSubItemBounds(Item, SubItem);
if (rcSubItem.X < 0)
{
// Left edge of SubItem not visible - adjust rectangle position and width
rcSubItem.Width += rcSubItem.X;
rcSubItem.X=0;
}
if (rcSubItem.X+rcSubItem.Width > this.Width)
{
// Right edge of SubItem not visible - adjust rectangle width
rcSubItem.Width = this.Width-rcSubItem.Left;
}
// Subitem bounds are relative to the location of the ListView!
rcSubItem.Offset(Left, Top);
// In case the editing control and the listview are on different parents,
// account for different origins
Point origin = new Point(0,0);
Point lvOrigin = this.Parent.PointToScreen(origin);
Point ctlOrigin = c.Parent.PointToScreen(origin);
rcSubItem.Offset(lvOrigin.X-ctlOrigin.X, lvOrigin.Y-ctlOrigin.Y);
// Position and show editor
c.Bounds = rcSubItem;
c.Text = Item.SubItems[SubItem].Text;
c.Visible = true;
c.BringToFront();
c.Focus();
_editingControl = c;
_editingControl.Leave += new EventHandler(_editControl_Leave);
_editingControl.KeyPress += new KeyPressEventHandler(_editControl_KeyPress);
_editItem = Item;
_editSubItem = SubItem;
}
private void _editControl_Leave(object sender, EventArgs e)
{
// cell editor losing focus
EndEditing(true);
}
private void _editControl_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
switch (e.KeyChar)
{
case (char)(int)Keys.Escape:
{
EndEditing(false);
break;
}
case (char)(int)Keys.Enter:
{
EndEditing(true);
break;
}
}
}
/// <summary>
/// Accept or discard current value of cell editor control
/// </summary>
/// <param name="AcceptChanges">Use the _editingControl's Text as new SubItem text or discard changes?</param>
public void EndEditing(bool AcceptChanges)
{
if (_editingControl == null)
return;
SubItemEndEditingEventArgs e = new SubItemEndEditingEventArgs(
_editItem, // The item being edited
_editSubItem, // The subitem index being edited
AcceptChanges ?
_editingControl.Text : // Use editControl text if changes are accepted
_editItem.SubItems[_editSubItem].Text, // or the original subitem's text, if changes are discarded
!AcceptChanges // Cancel?
);
OnSubItemEndEditing(e);
_editItem.SubItems[_editSubItem].Text = e.DisplayText;
_editingControl.Leave -= new EventHandler(_editControl_Leave);
_editingControl.KeyPress -= new KeyPressEventHandler(_editControl_KeyPress);
_editingControl.Visible = false;
_editingControl = null;
_editItem = null;
_editSubItem = -1;
}
#endregion
}
/// <summary>
/// Event Handler for SubItem events
/// </summary>
public delegate void SubItemEventHandler(object sender, SubItemEventArgs e);
/// <summary>
/// Event Handler for SubItemEndEditing events
/// </summary>
public delegate void SubItemEndEditingEventHandler(object sender, SubItemEndEditingEventArgs e);
/// <summary>
/// Event Args for SubItemClicked event
/// </summary>
public class SubItemEventArgs : EventArgs
{
public SubItemEventArgs(ListViewItem item, int subItem)
{
_subItemIndex = subItem;
_item = item;
}
private int _subItemIndex = -1;
private ListViewItem _item = null;
public int SubItem
{
get { return _subItemIndex; }
}
public ListViewItem Item
{
get { return _item; }
}
}
/// <summary>
/// Event Args for SubItemEndEditingClicked event
/// </summary>
public class SubItemEndEditingEventArgs : SubItemEventArgs
{
private string _text = string.Empty;
private bool _cancel = true;
public SubItemEndEditingEventArgs(ListViewItem item, int subItem, string display, bool cancel) :
base(item, subItem)
{
_text = display;
_cancel = cancel;
}
public string DisplayText
{
get { return _text; }
set { _text = value; }
}
public bool Cancel
{
get { return _cancel; }
set { _cancel = value; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.FindSymbols;
namespace RefactoringEssentials.CSharp
{
/// <summary>
/// Converts an instance method to a static method adding an additional parameter as "this" replacement.
/// </summary>
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert instance to static method")]
public class ConvertInstanceToStaticMethodCodeRefactoringProvider : SpecializedCodeRefactoringProvider<MethodDeclarationSyntax>
{
protected override IEnumerable<CodeAction> GetActions(Document document, SemanticModel semanticModel, SyntaxNode root, TextSpan span, MethodDeclarationSyntax node, CancellationToken cancellationToken)
{
TypeDeclarationSyntax enclosingTypeDeclaration = node.Ancestors().OfType<TypeDeclarationSyntax>().FirstOrDefault();
if (enclosingTypeDeclaration == null)
yield break;
if (node.Modifiers.Any(SyntaxKind.StaticKeyword))
yield break;
var declaringTypeSymbol = semanticModel.GetDeclaredSymbol(enclosingTypeDeclaration);
var methodSymbol = semanticModel.GetDeclaredSymbol(node);
yield return CodeActionFactory.Create(span, DiagnosticSeverity.Info, GettextCatalog.GetString("Convert to static method"), t2 =>
{
return PerformAction(document, semanticModel, root, enclosingTypeDeclaration, declaringTypeSymbol, node, methodSymbol, cancellationToken);
});
}
class MethodReferencesInDocument
{
public readonly Document Document;
public readonly IEnumerable<ReferencingInvocationExpression> References;
public MethodReferencesInDocument(Document document, IEnumerable<ReferencingInvocationExpression> references)
{
this.Document = document;
this.References = references;
}
}
class ReferencingInvocationExpression
{
public readonly bool IsInChangedMethod;
public readonly InvocationExpressionSyntax InvocationExpression;
public ReferencingInvocationExpression(bool isInChangedMethod, InvocationExpressionSyntax invocationExpression)
{
this.IsInChangedMethod = isInChangedMethod;
this.InvocationExpression = invocationExpression;
}
}
async Task<Solution> PerformAction(Document document, SemanticModel model, SyntaxNode root, TypeDeclarationSyntax enclosingTypeDeclaration, INamedTypeSymbol declaringTypeSymbol, MethodDeclarationSyntax methodDeclaration, IMethodSymbol methodSymbol, CancellationToken cancellationToken)
{
// Collect all invocations of changed method
var methodReferencesVisitor = new MethodReferencesVisitor(document.Project.Solution, methodSymbol, methodDeclaration, cancellationToken);
await methodReferencesVisitor.Collect();
// Collect all references to type members and "this" expressions inside of changed method
var memberReferencesVisitor = new MemberReferencesVisitor(model, declaringTypeSymbol.GetMembers().Where(m => m != methodSymbol), cancellationToken);
memberReferencesVisitor.Collect(methodDeclaration.Body);
Solution solution = document.Project.Solution;
List<SyntaxNode> trackedNodesInMainDoc = new List<SyntaxNode>();
trackedNodesInMainDoc.Add(methodDeclaration);
var methodReferencesInMainDocument = methodReferencesVisitor.NodesToChange.FirstOrDefault(n => n.Document.Id == document.Id);
if (methodReferencesInMainDocument != null)
{
trackedNodesInMainDoc.AddRange(methodReferencesInMainDocument.References.Select(r => r.InvocationExpression));
}
trackedNodesInMainDoc.AddRange(memberReferencesVisitor.NodesToChange);
var newMainRoot = root.TrackNodes(trackedNodesInMainDoc);
foreach (var invocationsInDocument in methodReferencesVisitor.NodesToChange)
{
SyntaxNode thisDocRoot = null;
var thisDocumentId = invocationsInDocument.Document.Id;
if (document.Id == thisDocumentId)
{
// We are in same document as changed method declaration, reuse new root from outside
thisDocRoot = newMainRoot;
}
else
{
thisDocRoot = await invocationsInDocument.Document.GetSyntaxRootAsync();
if (thisDocRoot == null)
continue;
thisDocRoot = thisDocRoot.TrackNodes(invocationsInDocument.References.Select(r => r.InvocationExpression));
}
foreach (var referencingInvocation in invocationsInDocument.References)
{
// Change this method invocation to invocation of a static method with instance parameter
var thisInvocation = thisDocRoot.GetCurrentNode(referencingInvocation.InvocationExpression);
ExpressionSyntax invocationExpressionPart = null;
SimpleNameSyntax methodName = null;
var memberAccessExpr = thisInvocation.Expression as MemberAccessExpressionSyntax;
if (memberAccessExpr != null)
{
invocationExpressionPart = memberAccessExpr.Expression;
methodName = memberAccessExpr.Name;
}
if (invocationExpressionPart == null)
{
var identifier = thisInvocation.Expression as IdentifierNameSyntax;
if (identifier != null)
{
// If changed method references itself, use "instance" as additional parameter! In other methods of affected class, use "this"!
if (referencingInvocation.IsInChangedMethod)
invocationExpressionPart = SyntaxFactory.IdentifierName("instance").WithLeadingTrivia(identifier.GetLeadingTrivia());
else
invocationExpressionPart = SyntaxFactory.ThisExpression().WithLeadingTrivia(identifier.GetLeadingTrivia());
methodName = identifier;
}
}
if (invocationExpressionPart == null)
continue;
List<ArgumentSyntax> invocationArguments = new List<ArgumentSyntax>();
invocationArguments.Add(SyntaxFactory.Argument(invocationExpressionPart.WithoutLeadingTrivia()));
invocationArguments.AddRange(referencingInvocation.InvocationExpression.ArgumentList.Arguments);
thisDocRoot = thisDocRoot.ReplaceNode(
thisInvocation,
SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName(enclosingTypeDeclaration.Identifier.WithoutTrivia()).WithLeadingTrivia(invocationExpressionPart.GetLeadingTrivia()),
methodName.WithoutLeadingTrivia()
),
SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(invocationArguments)).WithAdditionalAnnotations(Formatter.Annotation)
));
}
if (document.Id == thisDocumentId)
{
// Write new root back to outside
newMainRoot = thisDocRoot;
}
else
{
// Another document, replace it with modified version in solution
solution = solution.WithDocumentSyntaxRoot(thisDocumentId, thisDocRoot);
}
}
foreach (var changedNode in memberReferencesVisitor.NodesToChange)
{
var trackedNode = newMainRoot.GetCurrentNode(changedNode);
var thisExpression = trackedNode as ThisExpressionSyntax;
if (thisExpression != null)
{
// Replace "this" with instance parameter name
newMainRoot = newMainRoot.ReplaceNode(
thisExpression,
SyntaxFactory.IdentifierName("instance").WithLeadingTrivia(thisExpression.GetLeadingTrivia())
);
}
var memberIdentifier = trackedNode as IdentifierNameSyntax;
if (memberIdentifier != null)
{
newMainRoot = newMainRoot.ReplaceNode(
memberIdentifier,
SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName("instance").WithLeadingTrivia(memberIdentifier.GetLeadingTrivia()),
memberIdentifier.WithoutLeadingTrivia())
);
}
}
List<ParameterSyntax> parameters = new List<ParameterSyntax>();
parameters.Add(SyntaxFactory.Parameter(
SyntaxFactory.List<AttributeListSyntax>(),
SyntaxFactory.TokenList(),
SyntaxFactory.ParseTypeName(enclosingTypeDeclaration.Identifier.ValueText),
SyntaxFactory.Identifier("instance"), null)
.WithAdditionalAnnotations(Formatter.Annotation));
parameters.AddRange(methodDeclaration.ParameterList.Parameters);
var staticModifierLeadingTrivia =
methodDeclaration.Modifiers.Any() ? SyntaxFactory.TriviaList() : methodDeclaration.GetLeadingTrivia();
var methodDeclarationLeadingTrivia =
methodDeclaration.Modifiers.Any() ? methodDeclaration.GetLeadingTrivia() : SyntaxFactory.TriviaList();
var trackedMethodDeclaration = newMainRoot.GetCurrentNode(methodDeclaration);
newMainRoot = newMainRoot.ReplaceNode((SyntaxNode)trackedMethodDeclaration, trackedMethodDeclaration
.WithLeadingTrivia(methodDeclarationLeadingTrivia)
.WithModifiers(trackedMethodDeclaration.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword).WithLeadingTrivia(staticModifierLeadingTrivia).WithTrailingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.Whitespace(" ")))))
.WithParameterList(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)).WithTrailingTrivia(trackedMethodDeclaration.ParameterList.GetTrailingTrivia())));
return solution.WithDocumentSyntaxRoot(document.Id, newMainRoot);
}
class MethodReferencesVisitor
{
readonly Solution solution;
readonly MethodDeclarationSyntax changedMethodDeclaration;
readonly ISymbol methodSymbol;
readonly CancellationToken cancellationToken;
public readonly List<MethodReferencesInDocument> NodesToChange = new List<MethodReferencesInDocument>();
public MethodReferencesVisitor(Solution solution, ISymbol methodSymbol, MethodDeclarationSyntax changedMethodDeclaration, CancellationToken cancellationToken)
{
this.solution = solution;
this.methodSymbol = methodSymbol;
this.changedMethodDeclaration = changedMethodDeclaration;
this.cancellationToken = cancellationToken;
}
public async Task Collect()
{
var invocations = await SymbolFinder.FindCallersAsync(methodSymbol, solution);
var invocationsPerDocument = from invocation in invocations
from location in invocation.Locations
where location.SourceTree != null
group location by location.SourceTree into locationGroup
select locationGroup;
foreach (var locationsInDocument in invocationsPerDocument)
{
var document = solution.GetDocument(locationsInDocument.Key);
if (document == null)
continue;
var root = await document.GetSyntaxRootAsync(cancellationToken);
if (root == null)
continue;
NodesToChange.Add(new MethodReferencesInDocument(
document,
locationsInDocument.Select(loc =>
{
if (!loc.IsInSource)
return null;
var node = root.FindNode(loc.SourceSpan);
if (node == null)
return null;
var invocationExpression = node.AncestorsAndSelf().OfType<InvocationExpressionSyntax>().FirstOrDefault();
if (invocationExpression == null)
return null;
return new ReferencingInvocationExpression(invocationExpression.Ancestors().Contains(changedMethodDeclaration), invocationExpression);
})
.Where(r => r != null)));
}
}
}
class MemberReferencesVisitor : CSharpSyntaxWalker
{
readonly SemanticModel semanticModel;
readonly IEnumerable<ISymbol> referenceSymbols;
readonly CancellationToken cancellationToken;
public readonly List<SyntaxNode> NodesToChange = new List<SyntaxNode>();
public MemberReferencesVisitor(SemanticModel semanticModel, IEnumerable<ISymbol> referenceSymbols, CancellationToken cancellationToken)
{
this.semanticModel = semanticModel;
this.referenceSymbols = referenceSymbols;
this.cancellationToken = cancellationToken;
}
public void Collect(SyntaxNode root)
{
this.Visit(root);
}
public override void VisitIdentifierName(IdentifierNameSyntax node)
{
cancellationToken.ThrowIfCancellationRequested();
if (!(node.Parent is MemberAccessExpressionSyntax))
{
var thisSymbolInfo = semanticModel.GetSymbolInfo(node);
if (referenceSymbols.Contains(thisSymbolInfo.Symbol))
{
NodesToChange.Add(node);
}
}
base.VisitIdentifierName(node);
}
public override void VisitThisExpression(ThisExpressionSyntax node)
{
cancellationToken.ThrowIfCancellationRequested();
NodesToChange.Add(node);
base.VisitThisExpression(node);
}
}
}
}
| |
// 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 class is primarily used to test buffer boundary integrity of readers.
/// This class constructs a memory stream from the given buffer boundary length such that
/// the required tag completely lies exactly on the start and end of buffer boundary.
/// The class makes up the additional bytes by filling in whitespace if so.
/// The first buffer length consists of the XML Decl and the Root Start (done by PrepareStream() )
/// The next buffer length consists of the actual start and end text with the variable content stretched
/// out to end at the buffer boundary.
///
using System;
using System.Xml;
using System.Text;
using System.IO;
using OLEDB.Test.ModuleCore;
using System.Collections.Generic;
namespace XmlCoreTest.Common
{
/// <summary>
/// This class contains helper methods for Readers.
/// ConvertToBinaryStream : Converts the given xml string to the binary equivalent of the string and returns it
/// using a memory stream.
/// Common usage pattern would be something like :
/// XmlReader.Create( new MemoryStream(ReaderHelper.ConvertToBinaryStream("<elem>abc</elem>", true, false)), "baseUri", readerSettings );
/// </summary>
public static partial class ReaderHelper
{
//All possible enum strings are listed here.
//Some of them are duplicates reader types for legacy readers.
public enum ReaderType
{
COREREADER,
COREVALIDATINGREADER,
CUSTOMREADER,
CHARCHECKINGREADER,
SUBTREEREADER,
WRAPPEDREADER
}
public enum ReadOverload
{
String,
TextReader,
Stream,
URL,
XmlReader
}
public class CreateReaderParams
{
public ReaderType readerType;
public string BaseUri = null;
public ReadOverload InputType;
public object Input;
public XmlParserContext ParserContext = null;
public XmlNameTable NT = null;
public bool EnableNormalization = true;
public bool IsFragment = false;
public XmlReaderSettings Settings;
public CreateReaderParams(ReaderType type)
{
readerType = type;
}
public CreateReaderParams(
ReaderType type,
ReadOverload inputType,
object input,
string baseUri,
bool isFragment,
bool enableNormalization,
XmlReaderSettings readerSettings)
{
readerType = type;
BaseUri = baseUri;
Input = input;
InputType = inputType;
IsFragment = isFragment;
EnableNormalization = enableNormalization;
Settings = readerSettings;
}
public CreateReaderParams(
ReaderType type,
ReadOverload inputType,
object input,
XmlReaderSettings readerSettings)
{
readerType = type;
Input = input;
InputType = inputType;
Settings = readerSettings;
}
}
//Using these overloads with external entities may not work because there is no evidence or baseuri used.
public static XmlReader CreateReader(ReaderType readerType, TextReader stringReader, bool enableNormalization)
{
return CreateReader(readerType.ToString(), stringReader, enableNormalization, null, null);
}
public static XmlReader CreateReader(string readerType, TextReader stringReader, bool enableNormalization)
{
return CreateReader(readerType, stringReader, enableNormalization, null, null); //use default eventhandler
}
public static XmlReader CreateReader(string readerType, TextReader stringReader, bool enableNormalization, object eventHndlr, XmlReaderSettings settings)
{
return CreateReader(readerType, stringReader, enableNormalization, eventHndlr, settings, false);
}
public static XmlReader CreateReader(string readerType, TextReader stringReader, bool enableNormalization, object eventHndlr, XmlReaderSettings settings, bool isFragment)
{
CError.WriteLineIgnore(readerType);
ReaderType type = (ReaderType)Enum.Parse(typeof(ReaderType), readerType.ToUpperInvariant());
CreateReaderParams readerParams = new CreateReaderParams(type);
readerParams.InputType = ReadOverload.TextReader;
readerParams.Input = stringReader;
readerParams.EnableNormalization = enableNormalization;
readerParams.IsFragment = isFragment;
readerParams.Settings = settings;
return CreateReader(readerParams);
}
//This API doesn't attach a default validation event handler.
public static XmlReader CreateReader(ReaderType readerType, Stream stream, string baseUri, bool enableNormalization)
{
return CreateReader(readerType.ToString(), stream, baseUri, enableNormalization, null, null, false);
}
public static XmlReader CreateReader(string readerType, Stream stream, string baseUri, bool enableNormalization)
{
return CreateReader(readerType, stream, baseUri, enableNormalization, null, null, false); //use default eventhandler
}
public static XmlReader CreateReader(string readerType, Stream stream, string baseUri, bool enableNormalization, object eventHndlr, XmlReaderSettings settings, bool isFragment)
{
CError.WriteLineIgnore(readerType);
ReaderType type = (ReaderType)Enum.Parse(typeof(ReaderType), readerType.ToUpperInvariant());
CreateReaderParams readerParams = new CreateReaderParams(type);
readerParams.InputType = ReadOverload.Stream;
readerParams.Input = stream;
readerParams.BaseUri = baseUri;
readerParams.EnableNormalization = enableNormalization;
readerParams.IsFragment = isFragment;
readerParams.Settings = settings;
return CreateReader(readerParams);
}
//This API attaches a default validation event handler.
public static XmlReader CreateReader(ReaderType readerType, string url, bool enableNormalization)
{
return CreateReader(readerType.ToString(), url, enableNormalization, null, null);
}
public static XmlReader CreateReader(string readerType, string url, bool enableNormalization)
{
return CreateReader(readerType, url, enableNormalization, null, null); //use default eventhandler
}
public static XmlReader CreateReader(string readerType, string url, bool enableNormalization, object eventHndlr, XmlReaderSettings settings)
{
return CreateReader(readerType, url, enableNormalization, eventHndlr, settings, false);
}
public static XmlReader CreateReader(string readerType, string url, bool enableNormalization, object eventHndlr, XmlReaderSettings settings, bool isFragment)
{
CError.WriteLineIgnore(readerType);
ReaderType type = (ReaderType)Enum.Parse(typeof(ReaderType), readerType.ToUpperInvariant());
CreateReaderParams readerParams = new CreateReaderParams(type);
readerParams.InputType = ReadOverload.URL;
readerParams.Input = url;
readerParams.EnableNormalization = enableNormalization;
readerParams.IsFragment = isFragment;
readerParams.Settings = settings;
return CreateReader(readerParams);
}
public static XmlReader CreateReader(ReaderType readerType, XmlReader underlyingReader, bool enableNormalization)
{
return CreateReader(readerType.ToString(), underlyingReader, enableNormalization, null, null);
}
public static XmlReader CreateReader(string readerType, XmlReader underlyingReader, bool enableNormalization)
{
return CreateReader(readerType, underlyingReader, enableNormalization, null, null); //use default eventhandler
}
public static XmlReader CreateReader(string readerType, XmlReader underlyingReader, bool enableNormalization, object eventHndlr, XmlReaderSettings settings)
{
return CreateReader(readerType, underlyingReader, enableNormalization, eventHndlr, settings, false);
}
public static XmlReader CreateReader(string readerType, XmlReader underlyingReader, bool enableNormalization, object eventHndlr, XmlReaderSettings settings, bool isFragment)
{
CError.WriteLineIgnore(readerType);
ReaderType type = (ReaderType)Enum.Parse(typeof(ReaderType), readerType.ToUpperInvariant());
CreateReaderParams readerParams = new CreateReaderParams(type);
readerParams.InputType = ReadOverload.XmlReader;
readerParams.Input = underlyingReader;
readerParams.EnableNormalization = enableNormalization;
readerParams.IsFragment = isFragment;
readerParams.Settings = settings;
return CreateReader(readerParams);
}
public static void CreateXSLTStyleSheetWCopyTestFile(string strFileName)
{
}
public static XmlReader CreateReader(CreateReaderParams createParams)
{
switch (createParams.readerType)
{
case ReaderType.COREREADER:
case ReaderType.COREVALIDATINGREADER:
return CreateFactoryReader(createParams);
case ReaderType.CHARCHECKINGREADER:
return CreateCharCheckingReader(createParams);
case ReaderType.SUBTREEREADER:
return CreateSubtreeReader(createParams);
case ReaderType.WRAPPEDREADER:
return CreateWrappedReader(createParams);
default:
throw new CTestFailedException("Unsupported ReaderType");
}
}
public static XmlReader CreateCharCheckingReader(CreateReaderParams createParams)
{
XmlReaderSettings settings = GetSettings(createParams);
XmlParserContext parserContext = GetParserContext(createParams);
XmlReader r = null;
settings.CheckCharacters = false;
XmlReaderSettings rs = settings.Clone();
rs.CheckCharacters = true;
switch (createParams.InputType)
{
case ReadOverload.String:
r = Create(new StringReader((string)createParams.Input), settings, parserContext);
return Create(r, rs);
case ReadOverload.URL:
r = Create((string)createParams.Input, settings);
return Create(r, rs);
case ReadOverload.Stream:
r = Create((Stream)createParams.Input, settings, parserContext);
return Create(r, rs);
case ReadOverload.TextReader:
r = Create((TextReader)createParams.Input, settings, parserContext);
return Create(r, rs);
case ReadOverload.XmlReader:
r = Create((XmlReader)createParams.Input, settings);
return Create(r, rs);
default:
throw new CTestFailedException("Unknown ReadOverload");
}
}
public static XmlReader CreateSubtreeReader(CreateReaderParams createParams)
{
XmlReaderSettings settings = GetSettings(createParams);
XmlParserContext parserContext = GetParserContext(createParams);
XmlReader r = null;
switch (createParams.InputType)
{
case ReadOverload.String:
r = Create(new StringReader((string)createParams.Input), settings, parserContext);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
break;
}
return r.ReadSubtree();
case ReadOverload.URL:
r = Create((string)createParams.Input, settings);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
break;
}
return r.ReadSubtree();
case ReadOverload.Stream:
r = Create((Stream)createParams.Input, settings, parserContext);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
break;
}
return r.ReadSubtree();
case ReadOverload.TextReader:
r = Create((TextReader)createParams.Input, settings, parserContext);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
break;
}
return r.ReadSubtree();
case ReadOverload.XmlReader:
r = Create((XmlReader)createParams.Input, settings);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
break;
}
return r.ReadSubtree();
default:
throw new CTestFailedException("Unknown ReadOverload");
}
}
public static XmlReader CreateWrappedReader(CreateReaderParams createParams)
{
XmlReaderSettings settings = GetSettings(createParams);
XmlParserContext parserContext = GetParserContext(createParams);
XmlReader r = null;
switch (createParams.InputType)
{
case ReadOverload.String:
r = Create(new StringReader((string)createParams.Input), settings, parserContext);
return Create(r, settings);
case ReadOverload.URL:
r = Create((string)createParams.Input, settings);
return Create(r, settings);
case ReadOverload.Stream:
r = Create((Stream)createParams.Input, settings, parserContext);
return Create(r, settings);
case ReadOverload.TextReader:
r = Create((TextReader)createParams.Input, settings, parserContext);
return Create(r, settings);
case ReadOverload.XmlReader:
r = Create((XmlReader)createParams.Input, settings);
return Create(r, settings);
default:
throw new CTestFailedException("Unknown ReadOverload");
}
}
public static XmlReaderSettings GetSettings(CreateReaderParams createParams)
{
XmlReaderSettings settings = new XmlReaderSettings();
if (createParams.Settings != null)
{
settings = createParams.Settings;
}
else
{
if (createParams.IsFragment)
settings.ConformanceLevel = ConformanceLevel.Fragment;
}
return settings;
}
public static XmlParserContext GetParserContext(CreateReaderParams createParams)
{
if (createParams.ParserContext != null)
return createParams.ParserContext;
else
{
if (createParams.BaseUri != null)
{
XmlParserContext parserContext = new XmlParserContext(null, null, null, null, null, null, createParams.BaseUri, null, XmlSpace.None);
return parserContext;
}
else
{
return null;
}
}
}
public static XmlReader CreateFactoryReader(CreateReaderParams createParams)
{
XmlReaderSettings settings = GetSettings(createParams);
XmlParserContext parserContext = GetParserContext(createParams);
switch (createParams.InputType)
{
case ReadOverload.String:
return Create(new StringReader((string)createParams.Input), settings, parserContext);
case ReadOverload.URL:
return Create((string)createParams.Input, settings, parserContext);
case ReadOverload.Stream:
return Create((Stream)createParams.Input, settings, parserContext);
case ReadOverload.TextReader:
return Create((TextReader)createParams.Input, settings, parserContext);
case ReadOverload.XmlReader:
return Create((XmlReader)createParams.Input, settings);
default:
throw new CTestFailedException("Unknown ReadOverload");
}
}
private static Random s_rand = new Random((int)DateTime.Now.Ticks);
public static IEnumerable<string> GenerateNames(int count, bool isValid, CharType charType)
{
Func<CharType, string> generator = isValid ? (Func<CharType, string>)UnicodeCharHelper.GetValidCharacters : (Func<CharType, string>)UnicodeCharHelper.GetInvalidCharacters;
string chars = generator(charType);
for (int i = 0; i < count; i++)
{
char c = chars[s_rand.Next(chars.Length)];
yield return GetNameWithChar(c, charType);
}
}
public static string GetNameWithChar(char c, CharType charType)
{
switch (charType)
{
case CharType.NameStartChar:
return new string(new char[] { c, 'a', 'b' });
case CharType.NameChar:
return new string(new char[] { 'a', c, 'b' });
case CharType.NameStartSurrogateHighChar:
return new string(new char[] { c, '\udc00', 'a', 'b' });
case CharType.NameStartSurrogateLowChar:
return new string(new char[] { '\udb7f', c, 'a', 'b' });
case CharType.NameSurrogateHighChar:
return new string(new char[] { 'a', 'b', c, '\udc00' });
case CharType.NameSurrogateLowChar:
return new string(new char[] { 'a', 'b', '\udb7f', c });
default:
throw new CTestFailedException("TEST ISSUE: CharType FAILURE!");
}
}
public static XmlReader Create(string inputUri)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(FilePathUtil.getStream(inputUri));
}
else
{
return XmlReader.Create(FilePathUtil.getStream(inputUri));
}
}
public static XmlReader Create(string inputUri, XmlReaderSettings settings)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(FilePathUtil.getStream(inputUri), settings);
}
else
{
return XmlReader.Create(FilePathUtil.getStream(inputUri), settings);
}
}
public static XmlReader Create(string inputUri, XmlReaderSettings settings, XmlParserContext inputContext)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(FilePathUtil.getStream(inputUri), settings, inputContext);
}
else
{
return XmlReader.Create(FilePathUtil.getStream(inputUri));//, settings, inputContext);
}
}
public static XmlReader Create(Stream input)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input);
}
else
{
return XmlReader.Create(input);
}
}
public static XmlReader Create(Stream input, XmlReaderSettings settings)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings);
}
else
{
return XmlReader.Create(input, settings);
}
}
public static XmlReader Create(Stream input, XmlReaderSettings settings, string baseUri)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings, baseUri);
}
else
{
return XmlReader.Create(input, settings);//, baseUri);
}
}
public static XmlReader Create(Stream input, XmlReaderSettings settings, XmlParserContext inputContext)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings, inputContext);
}
else
{
return XmlReader.Create(input, settings, inputContext);
}
}
public static XmlReader Create(TextReader input)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input);
}
else
{
return XmlReader.Create(input);
}
}
public static XmlReader Create(TextReader input, XmlReaderSettings settings)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings);
}
else
{
return XmlReader.Create(input, settings);
}
}
public static XmlReader Create(TextReader input, XmlReaderSettings settings, string baseUri)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings, baseUri);
}
else
{
return XmlReader.Create(input, settings);//, baseUri);
}
}
public static XmlReader Create(TextReader input, XmlReaderSettings settings, XmlParserContext inputContext)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings, inputContext);
}
else
{
return XmlReader.Create(input, settings, inputContext);
}
}
public static XmlReader Create(XmlReader reader, XmlReaderSettings settings)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(reader, settings);
}
else
{
return XmlReader.Create(reader, settings);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32;
namespace System.Security
{
public sealed partial class SecureString
{
internal SecureString(SecureString str)
{
Debug.Assert(str != null, "Expected non-null SecureString");
Debug.Assert(str._buffer != null, "Expected other SecureString's buffer to be non-null");
Debug.Assert(str._encrypted, "Expected to be used only on encrypted SecureStrings");
AllocateBuffer(str._buffer.Length);
SafeBSTRHandle.Copy(str._buffer, _buffer, str._buffer.Length * sizeof(char));
_decryptedLength = str._decryptedLength;
_encrypted = str._encrypted;
}
private unsafe void InitializeSecureString(char* value, int length)
{
Debug.Assert(length >= 0, $"Expected non-negative length, got {length}");
AllocateBuffer((uint)length);
_decryptedLength = length;
byte* bufferPtr = null;
try
{
_buffer.AcquirePointer(ref bufferPtr);
Buffer.MemoryCopy((byte*)value, bufferPtr, (long)_buffer.ByteLength, length * sizeof(char));
}
finally
{
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
ProtectMemory();
}
private void AppendCharCore(char c)
{
UnprotectMemory();
try
{
EnsureCapacity(_decryptedLength + 1);
_buffer.Write<char>((uint)_decryptedLength * sizeof(char), c);
_decryptedLength++;
}
finally
{
ProtectMemory();
}
}
private void ClearCore()
{
_decryptedLength = 0;
_buffer.ClearBuffer();
}
private void DisposeCore()
{
if (_buffer != null)
{
_buffer.Dispose();
_buffer = null;
}
}
private unsafe void InsertAtCore(int index, char c)
{
byte* bufferPtr = null;
UnprotectMemory();
try
{
EnsureCapacity(_decryptedLength + 1);
_buffer.AcquirePointer(ref bufferPtr);
char* pBuffer = (char*)bufferPtr;
for (int i = _decryptedLength; i > index; i--)
{
pBuffer[i] = pBuffer[i - 1];
}
pBuffer[index] = c;
++_decryptedLength;
}
finally
{
ProtectMemory();
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
}
private unsafe void RemoveAtCore(int index)
{
byte* bufferPtr = null;
UnprotectMemory();
try
{
_buffer.AcquirePointer(ref bufferPtr);
char* pBuffer = (char*)bufferPtr;
for (int i = index; i < _decryptedLength - 1; i++)
{
pBuffer[i] = pBuffer[i + 1];
}
pBuffer[--_decryptedLength] = (char)0;
}
finally
{
ProtectMemory();
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
}
private void SetAtCore(int index, char c)
{
UnprotectMemory();
try
{
_buffer.Write<char>((uint)index * sizeof(char), c);
}
finally
{
ProtectMemory();
}
}
internal unsafe IntPtr MarshalToBSTR()
{
int length = _decryptedLength;
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
byte* bufferPtr = null;
UnprotectMemory();
try
{
_buffer.AcquirePointer(ref bufferPtr);
int resultByteLength = (length + 1) * sizeof(char);
ptr = Interop.OleAut32.SysAllocStringLen(null, length);
if (ptr == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char));
result = ptr;
}
finally
{
ProtectMemory();
// If we failed for any reason, free the new buffer
if (result == IntPtr.Zero && ptr != IntPtr.Zero)
{
Interop.NtDll.ZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
Interop.OleAut32.SysFreeString(ptr);
}
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
return result;
}
internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode)
{
int length = _decryptedLength;
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
byte* bufferPtr = null;
UnprotectMemory();
try
{
_buffer.AcquirePointer(ref bufferPtr);
if (unicode)
{
int resultByteLength = (length + 1) * sizeof(char);
ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength);
Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char));
*(length + (char*)ptr) = '\0';
}
else
{
uint defaultChar = '?';
int resultByteLength = 1 + Interop.Kernel32.WideCharToMultiByte(
Interop.Kernel32.CP_ACP, Interop.Kernel32.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, null, 0, (IntPtr)(&defaultChar), IntPtr.Zero);
ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength);
Interop.Kernel32.WideCharToMultiByte(
Interop.Kernel32.CP_ACP, Interop.Kernel32.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, (byte*)ptr, resultByteLength - 1, (IntPtr)(&defaultChar), IntPtr.Zero);
*(resultByteLength - 1 + (byte*)ptr) = 0;
}
result = ptr;
}
finally
{
ProtectMemory();
// If we failed for any reason, free the new buffer
if (result == IntPtr.Zero && ptr != IntPtr.Zero)
{
Interop.NtDll.ZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
MarshalFree(ptr, globalAlloc);
}
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
return result;
}
private void EnsureNotDisposed()
{
if (_buffer == null)
{
throw new ObjectDisposedException(GetType().Name);
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private const int BlockSize = (int)Interop.Crypt32.CRYPTPROTECTMEMORY_BLOCK_SIZE / sizeof(char);
private SafeBSTRHandle _buffer;
private bool _encrypted;
private void AllocateBuffer(uint size)
{
_buffer = SafeBSTRHandle.Allocate(GetAlignedSize(size));
}
private static uint GetAlignedSize(uint size) =>
size == 0 || size % BlockSize != 0 ?
BlockSize + ((size / BlockSize) * BlockSize) :
size;
private void EnsureCapacity(int capacity)
{
if (capacity > MaxLength)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity);
}
if (((uint)capacity * sizeof(char)) <= _buffer.ByteLength)
{
return;
}
var oldBuffer = _buffer;
SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(GetAlignedSize((uint)capacity));
SafeBSTRHandle.Copy(oldBuffer, newBuffer, (uint)_decryptedLength * sizeof(char));
_buffer = newBuffer;
oldBuffer.Dispose();
}
private void ProtectMemory()
{
Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!");
if (_decryptedLength != 0 &&
!_encrypted &&
!Interop.Crypt32.CryptProtectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS))
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
_encrypted = true;
}
private void UnprotectMemory()
{
Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!");
if (_decryptedLength != 0 &&
_encrypted &&
!Interop.Crypt32.CryptUnprotectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS))
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
_encrypted = false;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/common.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 Google.Cloud.Monitoring.V3 {
/// <summary>Holder for reflection information generated from google/monitoring/v3/common.proto</summary>
public static partial class CommonReflection {
#region Descriptor
/// <summary>File descriptor for google/monitoring/v3/common.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CommonReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiFnb29nbGUvbW9uaXRvcmluZy92My9jb21tb24ucHJvdG8SFGdvb2dsZS5t",
"b25pdG9yaW5nLnYzGh1nb29nbGUvYXBpL2Rpc3RyaWJ1dGlvbi5wcm90bxoe",
"Z29vZ2xlL3Byb3RvYnVmL2R1cmF0aW9uLnByb3RvGh9nb29nbGUvcHJvdG9i",
"dWYvdGltZXN0YW1wLnByb3RvIqoBCgpUeXBlZFZhbHVlEhQKCmJvb2xfdmFs",
"dWUYASABKAhIABIVCgtpbnQ2NF92YWx1ZRgCIAEoA0gAEhYKDGRvdWJsZV92",
"YWx1ZRgDIAEoAUgAEhYKDHN0cmluZ192YWx1ZRgEIAEoCUgAEjYKEmRpc3Ry",
"aWJ1dGlvbl92YWx1ZRgFIAEoCzIYLmdvb2dsZS5hcGkuRGlzdHJpYnV0aW9u",
"SABCBwoFdmFsdWUibAoMVGltZUludGVydmFsEiwKCGVuZF90aW1lGAIgASgL",
"MhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIuCgpzdGFydF90aW1lGAEg",
"ASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCLkBgoLQWdncmVnYXRp",
"b24SMwoQYWxpZ25tZW50X3BlcmlvZBgBIAEoCzIZLmdvb2dsZS5wcm90b2J1",
"Zi5EdXJhdGlvbhJFChJwZXJfc2VyaWVzX2FsaWduZXIYAiABKA4yKS5nb29n",
"bGUubW9uaXRvcmluZy52My5BZ2dyZWdhdGlvbi5BbGlnbmVyEkcKFGNyb3Nz",
"X3Nlcmllc19yZWR1Y2VyGAQgASgOMikuZ29vZ2xlLm1vbml0b3JpbmcudjMu",
"QWdncmVnYXRpb24uUmVkdWNlchIXCg9ncm91cF9ieV9maWVsZHMYBSADKAki",
"2gIKB0FsaWduZXISDgoKQUxJR05fTk9ORRAAEg8KC0FMSUdOX0RFTFRBEAES",
"DgoKQUxJR05fUkFURRACEhUKEUFMSUdOX0lOVEVSUE9MQVRFEAMSFAoQQUxJ",
"R05fTkVYVF9PTERFUhAEEg0KCUFMSUdOX01JThAKEg0KCUFMSUdOX01BWBAL",
"Eg4KCkFMSUdOX01FQU4QDBIPCgtBTElHTl9DT1VOVBANEg0KCUFMSUdOX1NV",
"TRAOEhAKDEFMSUdOX1NURERFVhAPEhQKEEFMSUdOX0NPVU5UX1RSVUUQEBIX",
"ChNBTElHTl9GUkFDVElPTl9UUlVFEBESFwoTQUxJR05fUEVSQ0VOVElMRV85",
"ORASEhcKE0FMSUdOX1BFUkNFTlRJTEVfOTUQExIXChNBTElHTl9QRVJDRU5U",
"SUxFXzUwEBQSFwoTQUxJR05fUEVSQ0VOVElMRV8wNRAVIpkCCgdSZWR1Y2Vy",
"Eg8KC1JFRFVDRV9OT05FEAASDwoLUkVEVUNFX01FQU4QARIOCgpSRURVQ0Vf",
"TUlOEAISDgoKUkVEVUNFX01BWBADEg4KClJFRFVDRV9TVU0QBBIRCg1SRURV",
"Q0VfU1REREVWEAUSEAoMUkVEVUNFX0NPVU5UEAYSFQoRUkVEVUNFX0NPVU5U",
"X1RSVUUQBxIYChRSRURVQ0VfRlJBQ1RJT05fVFJVRRAIEhgKFFJFRFVDRV9Q",
"RVJDRU5USUxFXzk5EAkSGAoUUkVEVUNFX1BFUkNFTlRJTEVfOTUQChIYChRS",
"RURVQ0VfUEVSQ0VOVElMRV81MBALEhgKFFJFRFVDRV9QRVJDRU5USUxFXzA1",
"EAxChgEKGGNvbS5nb29nbGUubW9uaXRvcmluZy52M0ILQ29tbW9uUHJvdG9Q",
"AVo+Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9tb25p",
"dG9yaW5nL3YzO21vbml0b3JpbmeqAhpHb29nbGUuQ2xvdWQuTW9uaXRvcmlu",
"Zy5WM2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.DistributionReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.TypedValue), global::Google.Cloud.Monitoring.V3.TypedValue.Parser, new[]{ "BoolValue", "Int64Value", "DoubleValue", "StringValue", "DistributionValue" }, new[]{ "Value" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.TimeInterval), global::Google.Cloud.Monitoring.V3.TimeInterval.Parser, new[]{ "EndTime", "StartTime" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.Aggregation), global::Google.Cloud.Monitoring.V3.Aggregation.Parser, new[]{ "AlignmentPeriod", "PerSeriesAligner", "CrossSeriesReducer", "GroupByFields" }, null, new[]{ typeof(global::Google.Cloud.Monitoring.V3.Aggregation.Types.Aligner), typeof(global::Google.Cloud.Monitoring.V3.Aggregation.Types.Reducer) }, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A single strongly-typed value.
/// </summary>
public sealed partial class TypedValue : pb::IMessage<TypedValue> {
private static readonly pb::MessageParser<TypedValue> _parser = new pb::MessageParser<TypedValue>(() => new TypedValue());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TypedValue> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.CommonReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TypedValue() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TypedValue(TypedValue other) : this() {
switch (other.ValueCase) {
case ValueOneofCase.BoolValue:
BoolValue = other.BoolValue;
break;
case ValueOneofCase.Int64Value:
Int64Value = other.Int64Value;
break;
case ValueOneofCase.DoubleValue:
DoubleValue = other.DoubleValue;
break;
case ValueOneofCase.StringValue:
StringValue = other.StringValue;
break;
case ValueOneofCase.DistributionValue:
DistributionValue = other.DistributionValue.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TypedValue Clone() {
return new TypedValue(this);
}
/// <summary>Field number for the "bool_value" field.</summary>
public const int BoolValueFieldNumber = 1;
/// <summary>
/// A Boolean value: `true` or `false`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool BoolValue {
get { return valueCase_ == ValueOneofCase.BoolValue ? (bool) value_ : false; }
set {
value_ = value;
valueCase_ = ValueOneofCase.BoolValue;
}
}
/// <summary>Field number for the "int64_value" field.</summary>
public const int Int64ValueFieldNumber = 2;
/// <summary>
/// A 64-bit integer. Its range is approximately &plusmn;9.2x10<sup>18</sup>.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Int64Value {
get { return valueCase_ == ValueOneofCase.Int64Value ? (long) value_ : 0L; }
set {
value_ = value;
valueCase_ = ValueOneofCase.Int64Value;
}
}
/// <summary>Field number for the "double_value" field.</summary>
public const int DoubleValueFieldNumber = 3;
/// <summary>
/// A 64-bit double-precision floating-point number. Its magnitude
/// is approximately &plusmn;10<sup>&plusmn;300</sup> and it has 16
/// significant digits of precision.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double DoubleValue {
get { return valueCase_ == ValueOneofCase.DoubleValue ? (double) value_ : 0D; }
set {
value_ = value;
valueCase_ = ValueOneofCase.DoubleValue;
}
}
/// <summary>Field number for the "string_value" field.</summary>
public const int StringValueFieldNumber = 4;
/// <summary>
/// A variable-length string value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string StringValue {
get { return valueCase_ == ValueOneofCase.StringValue ? (string) value_ : ""; }
set {
value_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
valueCase_ = ValueOneofCase.StringValue;
}
}
/// <summary>Field number for the "distribution_value" field.</summary>
public const int DistributionValueFieldNumber = 5;
/// <summary>
/// A distribution value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.Distribution DistributionValue {
get { return valueCase_ == ValueOneofCase.DistributionValue ? (global::Google.Api.Distribution) value_ : null; }
set {
value_ = value;
valueCase_ = value == null ? ValueOneofCase.None : ValueOneofCase.DistributionValue;
}
}
private object value_;
/// <summary>Enum of possible cases for the "value" oneof.</summary>
public enum ValueOneofCase {
None = 0,
BoolValue = 1,
Int64Value = 2,
DoubleValue = 3,
StringValue = 4,
DistributionValue = 5,
}
private ValueOneofCase valueCase_ = ValueOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ValueOneofCase ValueCase {
get { return valueCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearValue() {
valueCase_ = ValueOneofCase.None;
value_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TypedValue);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TypedValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (BoolValue != other.BoolValue) return false;
if (Int64Value != other.Int64Value) return false;
if (DoubleValue != other.DoubleValue) return false;
if (StringValue != other.StringValue) return false;
if (!object.Equals(DistributionValue, other.DistributionValue)) return false;
if (ValueCase != other.ValueCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (valueCase_ == ValueOneofCase.BoolValue) hash ^= BoolValue.GetHashCode();
if (valueCase_ == ValueOneofCase.Int64Value) hash ^= Int64Value.GetHashCode();
if (valueCase_ == ValueOneofCase.DoubleValue) hash ^= DoubleValue.GetHashCode();
if (valueCase_ == ValueOneofCase.StringValue) hash ^= StringValue.GetHashCode();
if (valueCase_ == ValueOneofCase.DistributionValue) hash ^= DistributionValue.GetHashCode();
hash ^= (int) valueCase_;
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 (valueCase_ == ValueOneofCase.BoolValue) {
output.WriteRawTag(8);
output.WriteBool(BoolValue);
}
if (valueCase_ == ValueOneofCase.Int64Value) {
output.WriteRawTag(16);
output.WriteInt64(Int64Value);
}
if (valueCase_ == ValueOneofCase.DoubleValue) {
output.WriteRawTag(25);
output.WriteDouble(DoubleValue);
}
if (valueCase_ == ValueOneofCase.StringValue) {
output.WriteRawTag(34);
output.WriteString(StringValue);
}
if (valueCase_ == ValueOneofCase.DistributionValue) {
output.WriteRawTag(42);
output.WriteMessage(DistributionValue);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (valueCase_ == ValueOneofCase.BoolValue) {
size += 1 + 1;
}
if (valueCase_ == ValueOneofCase.Int64Value) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Int64Value);
}
if (valueCase_ == ValueOneofCase.DoubleValue) {
size += 1 + 8;
}
if (valueCase_ == ValueOneofCase.StringValue) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(StringValue);
}
if (valueCase_ == ValueOneofCase.DistributionValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(DistributionValue);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TypedValue other) {
if (other == null) {
return;
}
switch (other.ValueCase) {
case ValueOneofCase.BoolValue:
BoolValue = other.BoolValue;
break;
case ValueOneofCase.Int64Value:
Int64Value = other.Int64Value;
break;
case ValueOneofCase.DoubleValue:
DoubleValue = other.DoubleValue;
break;
case ValueOneofCase.StringValue:
StringValue = other.StringValue;
break;
case ValueOneofCase.DistributionValue:
DistributionValue = other.DistributionValue;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
BoolValue = input.ReadBool();
break;
}
case 16: {
Int64Value = input.ReadInt64();
break;
}
case 25: {
DoubleValue = input.ReadDouble();
break;
}
case 34: {
StringValue = input.ReadString();
break;
}
case 42: {
global::Google.Api.Distribution subBuilder = new global::Google.Api.Distribution();
if (valueCase_ == ValueOneofCase.DistributionValue) {
subBuilder.MergeFrom(DistributionValue);
}
input.ReadMessage(subBuilder);
DistributionValue = subBuilder;
break;
}
}
}
}
}
/// <summary>
/// A time interval extending just after a start time through an end time.
/// If the start time is the same as the end time, then the interval
/// represents a single point in time.
/// </summary>
public sealed partial class TimeInterval : pb::IMessage<TimeInterval> {
private static readonly pb::MessageParser<TimeInterval> _parser = new pb::MessageParser<TimeInterval>(() => new TimeInterval());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TimeInterval> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.CommonReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeInterval() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeInterval(TimeInterval other) : this() {
EndTime = other.endTime_ != null ? other.EndTime.Clone() : null;
StartTime = other.startTime_ != null ? other.StartTime.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeInterval Clone() {
return new TimeInterval(this);
}
/// <summary>Field number for the "end_time" field.</summary>
public const int EndTimeFieldNumber = 2;
private global::Google.Protobuf.WellKnownTypes.Timestamp endTime_;
/// <summary>
/// Required. The end of the time interval.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp EndTime {
get { return endTime_; }
set {
endTime_ = value;
}
}
/// <summary>Field number for the "start_time" field.</summary>
public const int StartTimeFieldNumber = 1;
private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_;
/// <summary>
/// Optional. The beginning of the time interval. The default value
/// for the start time is the end time. The start time must not be
/// later than the end time.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime {
get { return startTime_; }
set {
startTime_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TimeInterval);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TimeInterval other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(EndTime, other.EndTime)) return false;
if (!object.Equals(StartTime, other.StartTime)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (endTime_ != null) hash ^= EndTime.GetHashCode();
if (startTime_ != null) hash ^= StartTime.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 (startTime_ != null) {
output.WriteRawTag(10);
output.WriteMessage(StartTime);
}
if (endTime_ != null) {
output.WriteRawTag(18);
output.WriteMessage(EndTime);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (endTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime);
}
if (startTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TimeInterval other) {
if (other == null) {
return;
}
if (other.endTime_ != null) {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
EndTime.MergeFrom(other.EndTime);
}
if (other.startTime_ != null) {
if (startTime_ == null) {
startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
StartTime.MergeFrom(other.StartTime);
}
}
[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: {
if (startTime_ == null) {
startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(startTime_);
break;
}
case 18: {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(endTime_);
break;
}
}
}
}
}
/// <summary>
/// Describes how to combine multiple time series to provide different views of
/// the data. Aggregation consists of an alignment step on individual time
/// series (`per_series_aligner`) followed by an optional reduction of the data
/// across different time series (`cross_series_reducer`). For more details, see
/// [Aggregation](/monitoring/api/learn_more#aggregation).
/// </summary>
public sealed partial class Aggregation : pb::IMessage<Aggregation> {
private static readonly pb::MessageParser<Aggregation> _parser = new pb::MessageParser<Aggregation>(() => new Aggregation());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Aggregation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.CommonReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Aggregation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Aggregation(Aggregation other) : this() {
AlignmentPeriod = other.alignmentPeriod_ != null ? other.AlignmentPeriod.Clone() : null;
perSeriesAligner_ = other.perSeriesAligner_;
crossSeriesReducer_ = other.crossSeriesReducer_;
groupByFields_ = other.groupByFields_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Aggregation Clone() {
return new Aggregation(this);
}
/// <summary>Field number for the "alignment_period" field.</summary>
public const int AlignmentPeriodFieldNumber = 1;
private global::Google.Protobuf.WellKnownTypes.Duration alignmentPeriod_;
/// <summary>
/// The alignment period for per-[time series][google.monitoring.v3.TimeSeries]
/// alignment. If present, `alignmentPeriod` must be at least 60
/// seconds. After per-time series alignment, each time series will
/// contain data points only on the period boundaries. If
/// `perSeriesAligner` is not specified or equals `ALIGN_NONE`, then
/// this field is ignored. If `perSeriesAligner` is specified and
/// does not equal `ALIGN_NONE`, then this field must be defined;
/// otherwise an error is returned.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Duration AlignmentPeriod {
get { return alignmentPeriod_; }
set {
alignmentPeriod_ = value;
}
}
/// <summary>Field number for the "per_series_aligner" field.</summary>
public const int PerSeriesAlignerFieldNumber = 2;
private global::Google.Cloud.Monitoring.V3.Aggregation.Types.Aligner perSeriesAligner_ = 0;
/// <summary>
/// The approach to be used to align individual time series. Not all
/// alignment functions may be applied to all time series, depending
/// on the metric type and value type of the original time
/// series. Alignment may change the metric type or the value type of
/// the time series.
///
/// Time series data must be aligned in order to perform cross-time
/// series reduction. If `crossSeriesReducer` is specified, then
/// `perSeriesAligner` must be specified and not equal `ALIGN_NONE`
/// and `alignmentPeriod` must be specified; otherwise, an error is
/// returned.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Monitoring.V3.Aggregation.Types.Aligner PerSeriesAligner {
get { return perSeriesAligner_; }
set {
perSeriesAligner_ = value;
}
}
/// <summary>Field number for the "cross_series_reducer" field.</summary>
public const int CrossSeriesReducerFieldNumber = 4;
private global::Google.Cloud.Monitoring.V3.Aggregation.Types.Reducer crossSeriesReducer_ = 0;
/// <summary>
/// The approach to be used to combine time series. Not all reducer
/// functions may be applied to all time series, depending on the
/// metric type and the value type of the original time
/// series. Reduction may change the metric type of value type of the
/// time series.
///
/// Time series data must be aligned in order to perform cross-time
/// series reduction. If `crossSeriesReducer` is specified, then
/// `perSeriesAligner` must be specified and not equal `ALIGN_NONE`
/// and `alignmentPeriod` must be specified; otherwise, an error is
/// returned.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Monitoring.V3.Aggregation.Types.Reducer CrossSeriesReducer {
get { return crossSeriesReducer_; }
set {
crossSeriesReducer_ = value;
}
}
/// <summary>Field number for the "group_by_fields" field.</summary>
public const int GroupByFieldsFieldNumber = 5;
private static readonly pb::FieldCodec<string> _repeated_groupByFields_codec
= pb::FieldCodec.ForString(42);
private readonly pbc::RepeatedField<string> groupByFields_ = new pbc::RepeatedField<string>();
/// <summary>
/// The set of fields to preserve when `crossSeriesReducer` is
/// specified. The `groupByFields` determine how the time series are
/// partitioned into subsets prior to applying the aggregation
/// function. Each subset contains time series that have the same
/// value for each of the grouping fields. Each individual time
/// series is a member of exactly one subset. The
/// `crossSeriesReducer` is applied to each subset of time series.
/// It is not possible to reduce across different resource types, so
/// this field implicitly contains `resource.type`. Fields not
/// specified in `groupByFields` are aggregated away. If
/// `groupByFields` is not specified and all the time series have
/// the same resource type, then the time series are aggregated into
/// a single output time series. If `crossSeriesReducer` is not
/// defined, this field is ignored.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> GroupByFields {
get { return groupByFields_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Aggregation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Aggregation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(AlignmentPeriod, other.AlignmentPeriod)) return false;
if (PerSeriesAligner != other.PerSeriesAligner) return false;
if (CrossSeriesReducer != other.CrossSeriesReducer) return false;
if(!groupByFields_.Equals(other.groupByFields_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (alignmentPeriod_ != null) hash ^= AlignmentPeriod.GetHashCode();
if (PerSeriesAligner != 0) hash ^= PerSeriesAligner.GetHashCode();
if (CrossSeriesReducer != 0) hash ^= CrossSeriesReducer.GetHashCode();
hash ^= groupByFields_.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 (alignmentPeriod_ != null) {
output.WriteRawTag(10);
output.WriteMessage(AlignmentPeriod);
}
if (PerSeriesAligner != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) PerSeriesAligner);
}
if (CrossSeriesReducer != 0) {
output.WriteRawTag(32);
output.WriteEnum((int) CrossSeriesReducer);
}
groupByFields_.WriteTo(output, _repeated_groupByFields_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (alignmentPeriod_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(AlignmentPeriod);
}
if (PerSeriesAligner != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) PerSeriesAligner);
}
if (CrossSeriesReducer != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) CrossSeriesReducer);
}
size += groupByFields_.CalculateSize(_repeated_groupByFields_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Aggregation other) {
if (other == null) {
return;
}
if (other.alignmentPeriod_ != null) {
if (alignmentPeriod_ == null) {
alignmentPeriod_ = new global::Google.Protobuf.WellKnownTypes.Duration();
}
AlignmentPeriod.MergeFrom(other.AlignmentPeriod);
}
if (other.PerSeriesAligner != 0) {
PerSeriesAligner = other.PerSeriesAligner;
}
if (other.CrossSeriesReducer != 0) {
CrossSeriesReducer = other.CrossSeriesReducer;
}
groupByFields_.Add(other.groupByFields_);
}
[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: {
if (alignmentPeriod_ == null) {
alignmentPeriod_ = new global::Google.Protobuf.WellKnownTypes.Duration();
}
input.ReadMessage(alignmentPeriod_);
break;
}
case 16: {
perSeriesAligner_ = (global::Google.Cloud.Monitoring.V3.Aggregation.Types.Aligner) input.ReadEnum();
break;
}
case 32: {
crossSeriesReducer_ = (global::Google.Cloud.Monitoring.V3.Aggregation.Types.Reducer) input.ReadEnum();
break;
}
case 42: {
groupByFields_.AddEntriesFrom(input, _repeated_groupByFields_codec);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the Aggregation message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The Aligner describes how to bring the data points in a single
/// time series into temporal alignment.
/// </summary>
public enum Aligner {
/// <summary>
/// No alignment. Raw data is returned. Not valid if cross-time
/// series reduction is requested. The value type of the result is
/// the same as the value type of the input.
/// </summary>
[pbr::OriginalName("ALIGN_NONE")] AlignNone = 0,
/// <summary>
/// Align and convert to delta metric type. This alignment is valid
/// for cumulative metrics and delta metrics. Aligning an existing
/// delta metric to a delta metric requires that the alignment
/// period be increased. The value type of the result is the same
/// as the value type of the input.
/// </summary>
[pbr::OriginalName("ALIGN_DELTA")] AlignDelta = 1,
/// <summary>
/// Align and convert to a rate. This alignment is valid for
/// cumulative metrics and delta metrics with numeric values. The output is a
/// gauge metric with value type
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("ALIGN_RATE")] AlignRate = 2,
/// <summary>
/// Align by interpolating between adjacent points around the
/// period boundary. This alignment is valid for gauge
/// metrics with numeric values. The value type of the result is the same
/// as the value type of the input.
/// </summary>
[pbr::OriginalName("ALIGN_INTERPOLATE")] AlignInterpolate = 3,
/// <summary>
/// Align by shifting the oldest data point before the period
/// boundary to the boundary. This alignment is valid for gauge
/// metrics. The value type of the result is the same as the
/// value type of the input.
/// </summary>
[pbr::OriginalName("ALIGN_NEXT_OLDER")] AlignNextOlder = 4,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the minimum of all data points in the
/// period. This alignment is valid for gauge and delta metrics with numeric
/// values. The value type of the result is the same as the value
/// type of the input.
/// </summary>
[pbr::OriginalName("ALIGN_MIN")] AlignMin = 10,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the maximum of all data points in the
/// period. This alignment is valid for gauge and delta metrics with numeric
/// values. The value type of the result is the same as the value
/// type of the input.
/// </summary>
[pbr::OriginalName("ALIGN_MAX")] AlignMax = 11,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the average or arithmetic mean of all
/// data points in the period. This alignment is valid for gauge and delta
/// metrics with numeric values. The value type of the output is
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("ALIGN_MEAN")] AlignMean = 12,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the count of all data points in the
/// period. This alignment is valid for gauge and delta metrics with numeric
/// or Boolean values. The value type of the output is
/// [INT64][google.api.MetricDescriptor.ValueType.INT64].
/// </summary>
[pbr::OriginalName("ALIGN_COUNT")] AlignCount = 13,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the sum of all data points in the
/// period. This alignment is valid for gauge and delta metrics with numeric
/// and distribution values. The value type of the output is the
/// same as the value type of the input.
/// </summary>
[pbr::OriginalName("ALIGN_SUM")] AlignSum = 14,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the standard deviation of all data
/// points in the period. This alignment is valid for gauge and delta metrics
/// with numeric values. The value type of the output is
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("ALIGN_STDDEV")] AlignStddev = 15,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the count of True-valued data points in the
/// period. This alignment is valid for gauge metrics with
/// Boolean values. The value type of the output is
/// [INT64][google.api.MetricDescriptor.ValueType.INT64].
/// </summary>
[pbr::OriginalName("ALIGN_COUNT_TRUE")] AlignCountTrue = 16,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the fraction of True-valued data points in the
/// period. This alignment is valid for gauge metrics with Boolean values.
/// The output value is in the range [0, 1] and has value type
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("ALIGN_FRACTION_TRUE")] AlignFractionTrue = 17,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the 99th percentile of all data
/// points in the period. This alignment is valid for gauge and delta metrics
/// with distribution values. The output is a gauge metric with value type
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("ALIGN_PERCENTILE_99")] AlignPercentile99 = 18,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the 95th percentile of all data
/// points in the period. This alignment is valid for gauge and delta metrics
/// with distribution values. The output is a gauge metric with value type
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("ALIGN_PERCENTILE_95")] AlignPercentile95 = 19,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the 50th percentile of all data
/// points in the period. This alignment is valid for gauge and delta metrics
/// with distribution values. The output is a gauge metric with value type
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("ALIGN_PERCENTILE_50")] AlignPercentile50 = 20,
/// <summary>
/// Align time series via aggregation. The resulting data point in
/// the alignment period is the 5th percentile of all data
/// points in the period. This alignment is valid for gauge and delta metrics
/// with distribution values. The output is a gauge metric with value type
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("ALIGN_PERCENTILE_05")] AlignPercentile05 = 21,
}
/// <summary>
/// A Reducer describes how to aggregate data points from multiple
/// time series into a single time series.
/// </summary>
public enum Reducer {
/// <summary>
/// No cross-time series reduction. The output of the aligner is
/// returned.
/// </summary>
[pbr::OriginalName("REDUCE_NONE")] ReduceNone = 0,
/// <summary>
/// Reduce by computing the mean across time series for each
/// alignment period. This reducer is valid for delta and
/// gauge metrics with numeric or distribution values. The value type of the
/// output is [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("REDUCE_MEAN")] ReduceMean = 1,
/// <summary>
/// Reduce by computing the minimum across time series for each
/// alignment period. This reducer is valid for delta and
/// gauge metrics with numeric values. The value type of the output
/// is the same as the value type of the input.
/// </summary>
[pbr::OriginalName("REDUCE_MIN")] ReduceMin = 2,
/// <summary>
/// Reduce by computing the maximum across time series for each
/// alignment period. This reducer is valid for delta and
/// gauge metrics with numeric values. The value type of the output
/// is the same as the value type of the input.
/// </summary>
[pbr::OriginalName("REDUCE_MAX")] ReduceMax = 3,
/// <summary>
/// Reduce by computing the sum across time series for each
/// alignment period. This reducer is valid for delta and
/// gauge metrics with numeric and distribution values. The value type of
/// the output is the same as the value type of the input.
/// </summary>
[pbr::OriginalName("REDUCE_SUM")] ReduceSum = 4,
/// <summary>
/// Reduce by computing the standard deviation across time series
/// for each alignment period. This reducer is valid for delta
/// and gauge metrics with numeric or distribution values. The value type of
/// the output is [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("REDUCE_STDDEV")] ReduceStddev = 5,
/// <summary>
/// Reduce by computing the count of data points across time series
/// for each alignment period. This reducer is valid for delta
/// and gauge metrics of numeric, Boolean, distribution, and string value
/// type. The value type of the output is
/// [INT64][google.api.MetricDescriptor.ValueType.INT64].
/// </summary>
[pbr::OriginalName("REDUCE_COUNT")] ReduceCount = 6,
/// <summary>
/// Reduce by computing the count of True-valued data points across time
/// series for each alignment period. This reducer is valid for delta
/// and gauge metrics of Boolean value type. The value type of
/// the output is [INT64][google.api.MetricDescriptor.ValueType.INT64].
/// </summary>
[pbr::OriginalName("REDUCE_COUNT_TRUE")] ReduceCountTrue = 7,
/// <summary>
/// Reduce by computing the fraction of True-valued data points across time
/// series for each alignment period. This reducer is valid for delta
/// and gauge metrics of Boolean value type. The output value is in the
/// range [0, 1] and has value type
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE].
/// </summary>
[pbr::OriginalName("REDUCE_FRACTION_TRUE")] ReduceFractionTrue = 8,
/// <summary>
/// Reduce by computing 99th percentile of data points across time series
/// for each alignment period. This reducer is valid for gauge and delta
/// metrics of numeric and distribution type. The value of the output is
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]
/// </summary>
[pbr::OriginalName("REDUCE_PERCENTILE_99")] ReducePercentile99 = 9,
/// <summary>
/// Reduce by computing 95th percentile of data points across time series
/// for each alignment period. This reducer is valid for gauge and delta
/// metrics of numeric and distribution type. The value of the output is
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]
/// </summary>
[pbr::OriginalName("REDUCE_PERCENTILE_95")] ReducePercentile95 = 10,
/// <summary>
/// Reduce by computing 50th percentile of data points across time series
/// for each alignment period. This reducer is valid for gauge and delta
/// metrics of numeric and distribution type. The value of the output is
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]
/// </summary>
[pbr::OriginalName("REDUCE_PERCENTILE_50")] ReducePercentile50 = 11,
/// <summary>
/// Reduce by computing 5th percentile of data points across time series
/// for each alignment period. This reducer is valid for gauge and delta
/// metrics of numeric and distribution type. The value of the output is
/// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]
/// </summary>
[pbr::OriginalName("REDUCE_PERCENTILE_05")] ReducePercentile05 = 12,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
// 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.Xml.Serialization
{
using System;
using System.Xml;
using System.Globalization;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Xml.Serialization.Configuration;
/// <summary>
/// The <see cref="XmlCustomFormatter"/> class provides a set of static methods for converting
/// primitive type values to and from their XML string representations.</summary>
internal class XmlCustomFormatter
{
private static DateTimeSerializationSection.DateTimeSerializationMode s_mode;
private static DateTimeSerializationSection.DateTimeSerializationMode Mode
{
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
get
{
if (s_mode == DateTimeSerializationSection.DateTimeSerializationMode.Default)
{
s_mode = DateTimeSerializationSection.DateTimeSerializationMode.Roundtrip;
}
return s_mode;
}
}
private XmlCustomFormatter() { }
internal static string FromDefaultValue(object value, string formatter)
{
if (value == null) return null;
Type type = value.GetType();
if (type == typeof(DateTime))
{
if (formatter == "DateTime")
{
return FromDateTime((DateTime)value);
}
if (formatter == "Date")
{
return FromDate((DateTime)value);
}
if (formatter == "Time")
{
return FromTime((DateTime)value);
}
}
else if (type == typeof(string))
{
if (formatter == "XmlName")
{
return FromXmlName((string)value);
}
if (formatter == "XmlNCName")
{
return FromXmlNCName((string)value);
}
if (formatter == "XmlNmToken")
{
return FromXmlNmToken((string)value);
}
if (formatter == "XmlNmTokens")
{
return FromXmlNmTokens((string)value);
}
}
throw new Exception(SR.Format(SR.XmlUnsupportedDefaultType, type.FullName));
}
internal static string FromDate(DateTime value)
{
return XmlConvert.ToString(value, "yyyy-MM-dd");
}
internal static string FromTime(DateTime value)
{
if (!LocalAppContextSwitches.IgnoreKindInUtcTimeSerialization && value.Kind == DateTimeKind.Utc)
{
return XmlConvert.ToString(DateTime.MinValue + value.TimeOfDay, "HH:mm:ss.fffffffZ");
}
else
{
return XmlConvert.ToString(DateTime.MinValue + value.TimeOfDay, "HH:mm:ss.fffffffzzzzzz");
}
}
internal static string FromDateTime(DateTime value)
{
if (Mode == DateTimeSerializationSection.DateTimeSerializationMode.Local)
{
return XmlConvert.ToString(value, "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz");
}
else
{
// for mode DateTimeSerializationMode.Roundtrip and DateTimeSerializationMode.Default
return XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind);
}
}
internal static string FromChar(char value)
{
return XmlConvert.ToString((UInt16)value);
}
internal static string FromXmlName(string name)
{
return XmlConvert.EncodeName(name);
}
internal static string FromXmlNCName(string ncName)
{
return XmlConvert.EncodeLocalName(ncName);
}
internal static string FromXmlNmToken(string nmToken)
{
return XmlConvert.EncodeNmToken(nmToken);
}
internal static string FromXmlNmTokens(string nmTokens)
{
if (nmTokens == null)
return null;
if (nmTokens.IndexOf(' ') < 0)
return FromXmlNmToken(nmTokens);
else
{
string[] toks = nmTokens.Split(new char[] { ' ' });
StringBuilder sb = new StringBuilder();
for (int i = 0; i < toks.Length; i++)
{
if (i > 0) sb.Append(' ');
sb.Append(FromXmlNmToken(toks[i]));
}
return sb.ToString();
}
}
internal static void WriteArrayBase64(XmlWriter writer, byte[] inData, int start, int count)
{
if (inData == null || count == 0)
{
return;
}
writer.WriteBase64(inData, start, count);
}
internal static string FromByteArrayHex(byte[] value)
{
if (value == null)
return null;
if (value.Length == 0)
return "";
return XmlConvert.ToBinHexString(value);
}
internal static string FromEnum(long val, string[] vals, long[] ids, string typeName)
{
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (ids.Length != vals.Length) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Invalid enum"));
#endif
long originalValue = val;
StringBuilder sb = new StringBuilder();
int iZero = -1;
for (int i = 0; i < ids.Length; i++)
{
if (ids[i] == 0)
{
iZero = i;
continue;
}
if (val == 0)
{
break;
}
if ((ids[i] & originalValue) == ids[i])
{
if (sb.Length != 0)
sb.Append(" ");
sb.Append(vals[i]);
val &= ~ids[i];
}
}
if (val != 0)
{
// failed to parse the enum value
throw new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, originalValue, typeName == null ? "enum" : typeName));
}
if (sb.Length == 0 && iZero >= 0)
{
sb.Append(vals[iZero]);
}
return sb.ToString();
}
internal static object ToDefaultValue(string value, string formatter)
{
if (formatter == "DateTime")
{
return ToDateTime(value);
}
if (formatter == "Date")
{
return ToDate(value);
}
if (formatter == "Time")
{
return ToTime(value);
}
if (formatter == "XmlName")
{
return ToXmlName(value);
}
if (formatter == "XmlNCName")
{
return ToXmlNCName(value);
}
if (formatter == "XmlNmToken")
{
return ToXmlNmToken(value);
}
if (formatter == "XmlNmTokens")
{
return ToXmlNmTokens(value);
}
throw new Exception(SR.Format(SR.XmlUnsupportedDefaultValue, formatter));
// Debug.WriteLineIf(CompModSwitches.XmlSerialization.TraceVerbose, "XmlSerialization::Unhandled default value " + value + " formatter " + formatter);
// return DBNull.Value;
}
private static string[] s_allDateTimeFormats = new string[] {
"yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz",
"yyyy",
"---dd",
"---ddZ",
"---ddzzzzzz",
"--MM-dd",
"--MM-ddZ",
"--MM-ddzzzzzz",
"--MM--",
"--MM--Z",
"--MM--zzzzzz",
"yyyy-MM",
"yyyy-MMZ",
"yyyy-MMzzzzzz",
"yyyyzzzzzz",
"yyyy-MM-dd",
"yyyy-MM-ddZ",
"yyyy-MM-ddzzzzzz",
"HH:mm:ss",
"HH:mm:ss.f",
"HH:mm:ss.ff",
"HH:mm:ss.fff",
"HH:mm:ss.ffff",
"HH:mm:ss.fffff",
"HH:mm:ss.ffffff",
"HH:mm:ss.fffffff",
"HH:mm:ssZ",
"HH:mm:ss.fZ",
"HH:mm:ss.ffZ",
"HH:mm:ss.fffZ",
"HH:mm:ss.ffffZ",
"HH:mm:ss.fffffZ",
"HH:mm:ss.ffffffZ",
"HH:mm:ss.fffffffZ",
"HH:mm:sszzzzzz",
"HH:mm:ss.fzzzzzz",
"HH:mm:ss.ffzzzzzz",
"HH:mm:ss.fffzzzzzz",
"HH:mm:ss.ffffzzzzzz",
"HH:mm:ss.fffffzzzzzz",
"HH:mm:ss.ffffffzzzzzz",
"HH:mm:ss.fffffffzzzzzz",
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:ss.f",
"yyyy-MM-ddTHH:mm:ss.ff",
"yyyy-MM-ddTHH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ss.ffff",
"yyyy-MM-ddTHH:mm:ss.fffff",
"yyyy-MM-ddTHH:mm:ss.ffffff",
"yyyy-MM-ddTHH:mm:ss.fffffff",
"yyyy-MM-ddTHH:mm:ssZ",
"yyyy-MM-ddTHH:mm:ss.fZ",
"yyyy-MM-ddTHH:mm:ss.ffZ",
"yyyy-MM-ddTHH:mm:ss.fffZ",
"yyyy-MM-ddTHH:mm:ss.ffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffZ",
"yyyy-MM-ddTHH:mm:ss.ffffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffffZ",
"yyyy-MM-ddTHH:mm:sszzzzzz",
"yyyy-MM-ddTHH:mm:ss.fzzzzzz",
"yyyy-MM-ddTHH:mm:ss.ffzzzzzz",
"yyyy-MM-ddTHH:mm:ss.fffzzzzzz",
"yyyy-MM-ddTHH:mm:ss.ffffzzzzzz",
"yyyy-MM-ddTHH:mm:ss.fffffzzzzzz",
"yyyy-MM-ddTHH:mm:ss.ffffffzzzzzz",
};
private static string[] s_allDateFormats = new string[] {
"yyyy-MM-ddzzzzzz",
"yyyy-MM-dd",
"yyyy-MM-ddZ",
"yyyy",
"---dd",
"---ddZ",
"---ddzzzzzz",
"--MM-dd",
"--MM-ddZ",
"--MM-ddzzzzzz",
"--MM--",
"--MM--Z",
"--MM--zzzzzz",
"yyyy-MM",
"yyyy-MMZ",
"yyyy-MMzzzzzz",
"yyyyzzzzzz",
};
private static string[] s_allTimeFormats = new string[] {
"HH:mm:ss.fffffffzzzzzz",
"HH:mm:ss",
"HH:mm:ss.f",
"HH:mm:ss.ff",
"HH:mm:ss.fff",
"HH:mm:ss.ffff",
"HH:mm:ss.fffff",
"HH:mm:ss.ffffff",
"HH:mm:ss.fffffff",
"HH:mm:ssZ",
"HH:mm:ss.fZ",
"HH:mm:ss.ffZ",
"HH:mm:ss.fffZ",
"HH:mm:ss.ffffZ",
"HH:mm:ss.fffffZ",
"HH:mm:ss.ffffffZ",
"HH:mm:ss.fffffffZ",
"HH:mm:sszzzzzz",
"HH:mm:ss.fzzzzzz",
"HH:mm:ss.ffzzzzzz",
"HH:mm:ss.fffzzzzzz",
"HH:mm:ss.ffffzzzzzz",
"HH:mm:ss.fffffzzzzzz",
"HH:mm:ss.ffffffzzzzzz",
};
internal static DateTime ToDateTime(string value)
{
if (Mode == DateTimeSerializationSection.DateTimeSerializationMode.Local)
{
return ToDateTime(value, s_allDateTimeFormats);
}
else
{
// for mode DateTimeSerializationMode.Roundtrip and DateTimeSerializationMode.Default
return XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind);
}
}
internal static DateTime ToDateTime(string value, string[] formats)
{
return XmlConvert.ToDateTime(value, formats);
}
internal static DateTime ToDate(string value)
{
return ToDateTime(value, s_allDateFormats);
}
internal static DateTime ToTime(string value)
{
if (!LocalAppContextSwitches.IgnoreKindInUtcTimeSerialization)
{
return DateTime.ParseExact(value, s_allTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite | DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.RoundtripKind);
}
else
{
return DateTime.ParseExact(value, s_allTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite | DateTimeStyles.NoCurrentDateDefault);
}
}
internal static char ToChar(string value)
{
return (char)XmlConvert.ToUInt16(value);
}
internal static string ToXmlName(string value)
{
return XmlConvert.DecodeName(CollapseWhitespace(value));
}
internal static string ToXmlNCName(string value)
{
return XmlConvert.DecodeName(CollapseWhitespace(value));
}
internal static string ToXmlNmToken(string value)
{
return XmlConvert.DecodeName(CollapseWhitespace(value));
}
internal static string ToXmlNmTokens(string value)
{
return XmlConvert.DecodeName(CollapseWhitespace(value));
}
internal static byte[] ToByteArrayBase64(string value)
{
if (value == null) return null;
value = value.Trim();
if (value.Length == 0)
return Array.Empty<byte>();
return Convert.FromBase64String(value);
}
internal static byte[] ToByteArrayHex(string value)
{
if (value == null) return null;
value = value.Trim();
return XmlConvert.FromBinHexString(value);
}
internal static long ToEnum(string val, Hashtable vals, string typeName, bool validate)
{
long value = 0;
string[] parts = val.Split(null);
for (int i = 0; i < parts.Length; i++)
{
object id = vals[parts[i]];
if (id != null)
value |= (long)id;
else if (validate && parts[i].Length > 0)
throw new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, parts[i], typeName));
}
return value;
}
private static string CollapseWhitespace(string value)
{
if (value == null)
return null;
return value.Trim();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
// This implementation uses the System.Net.Http.WinHttpHandler class on Windows. Other platforms will need to use
// their own platform specific implementation.
public class HttpClientHandler : HttpMessageHandler
{
#region Properties
public virtual bool SupportsAutomaticDecompression
{
get { return true; }
}
public virtual bool SupportsProxy
{
get { return true; }
}
public virtual bool SupportsRedirectConfiguration
{
get { return true; }
}
public bool UseCookies
{
get { return (_winHttpHandler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer); }
set { _winHttpHandler.CookieUsePolicy = value ? CookieUsePolicy.UseSpecifiedCookieContainer : CookieUsePolicy.IgnoreCookies; }
}
public CookieContainer CookieContainer
{
get { return _winHttpHandler.CookieContainer; }
set { _winHttpHandler.CookieContainer = value; }
}
public ClientCertificateOption ClientCertificateOptions
{
get { return _winHttpHandler.ClientCertificateOption; }
set { _winHttpHandler.ClientCertificateOption = value; }
}
public DecompressionMethods AutomaticDecompression
{
get { return _winHttpHandler.AutomaticDecompression; }
set { _winHttpHandler.AutomaticDecompression = value; }
}
public bool UseProxy
{
get { return _useProxy; }
set { _useProxy = value; }
}
public IWebProxy Proxy
{
get { return _winHttpHandler.Proxy; }
set { _winHttpHandler.Proxy = value; }
}
public bool PreAuthenticate
{
get { return _winHttpHandler.PreAuthenticate; }
set { _winHttpHandler.PreAuthenticate = value; }
}
public bool UseDefaultCredentials
{
// WinHttpHandler doesn't have a separate UseDefaultCredentials property. There
// is just a ServerCredentials property. So, we need to map the behavior.
get { return (_winHttpHandler.ServerCredentials == CredentialCache.DefaultCredentials); }
set
{
if (value)
{
_winHttpHandler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
_winHttpHandler.ServerCredentials = CredentialCache.DefaultCredentials;
}
else
{
_winHttpHandler.DefaultProxyCredentials = null;
if (_winHttpHandler.ServerCredentials == CredentialCache.DefaultCredentials)
{
// Only clear out the ServerCredentials property if it was a DefaultCredentials.
_winHttpHandler.ServerCredentials = null;
}
}
}
}
public ICredentials Credentials
{
get { return _winHttpHandler.ServerCredentials; }
set { _winHttpHandler.ServerCredentials = value; }
}
public bool AllowAutoRedirect
{
get
{
return _winHttpHandler.AutomaticRedirection;
}
set
{
_winHttpHandler.AutomaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get { return _winHttpHandler.MaxAutomaticRedirections; }
set { _winHttpHandler.MaxAutomaticRedirections = value; }
}
public long MaxRequestContentBufferSize
{
// This property has been deprecated. In the .NET Desktop it was only used when the handler needed to
// automatically buffer the request content. That only happened if neither 'Content-Length' nor
// 'Transfer-Encoding: chunked' request headers were specified. So, the handler thus needed to buffer
// in the request content to determine its length and then would choose 'Content-Length' semantics when
// POST'ing. In CoreCLR and .NETNative, the handler will resolve the ambiguity by always choosing
// 'Transfer-Encoding: chunked'. The handler will never automatically buffer in the request content.
get { return 0; }
// TODO (#7879): Add message/link to exception explaining the deprecation.
// Update corresponding exception in HttpClientHandler.Unix.cs if/when this is updated.
set { throw new PlatformNotSupportedException(); }
}
public X509CertificateCollection ClientCertificates
{
get { return _winHttpHandler.ClientCertificates; }
}
public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback
{
get { return _winHttpHandler.ServerCertificateValidationCallback; }
set { _winHttpHandler.ServerCertificateValidationCallback = value; }
}
public bool CheckCertificateRevocationList
{
get { return _winHttpHandler.CheckCertificateRevocationList; }
set { _winHttpHandler.CheckCertificateRevocationList = value; }
}
#endregion Properties
#region De/Constructors
public HttpClientHandler()
{
_winHttpHandler = new WinHttpHandler();
// Adjust defaults to match current .NET Desktop HttpClientHandler (based on HWR stack).
AllowAutoRedirect = true;
UseProxy = true;
UseCookies = true;
CookieContainer = new CookieContainer();
// The existing .NET Desktop HttpClientHandler based on the HWR stack uses only WinINet registry
// settings for the proxy. This also includes supporting the "Automatic Detect a proxy" using
// WPAD protocol and PAC file. So, for app-compat, we will do the same for the default proxy setting.
_winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
_winHttpHandler.Proxy = null;
// Since the granular WinHttpHandler timeout properties are not exposed via the HttpClientHandler API,
// we need to set them to infinite and allow the HttpClient.Timeout property to have precedence.
_winHttpHandler.ConnectTimeout = Timeout.InfiniteTimeSpan;
_winHttpHandler.ReceiveHeadersTimeout = Timeout.InfiniteTimeSpan;
_winHttpHandler.ReceiveDataTimeout = Timeout.InfiniteTimeSpan;
_winHttpHandler.SendTimeout = Timeout.InfiniteTimeSpan;
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
// Release WinHttp session handle.
_winHttpHandler.Dispose();
}
base.Dispose(disposing);
}
#endregion De/Constructors
#region Request Execution
protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
// Get current value of WindowsProxyUsePolicy. Only call its WinHttpHandler
// property setter if the value needs to change.
var oldProxyUsePolicy = _winHttpHandler.WindowsProxyUsePolicy;
if (_useProxy)
{
if (_winHttpHandler.Proxy == null)
{
if (oldProxyUsePolicy != WindowsProxyUsePolicy.UseWinInetProxy)
{
_winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
}
}
else
{
if (oldProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
_winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
}
}
}
else
{
if (oldProxyUsePolicy != WindowsProxyUsePolicy.DoNotUseProxy)
{
_winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;
}
}
return _winHttpHandler.SendAsync(request, cancellationToken);
}
#endregion Request Execution
#region Private
private WinHttpHandler _winHttpHandler;
private bool _useProxy;
private volatile bool _disposed;
#endregion Private
}
}
| |
// 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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private abstract partial class CSharpCodeGenerator
{
private class CallSiteContainerRewriter : CSharpSyntaxRewriter
{
private readonly SyntaxNode _outmostCallSiteContainer;
private readonly IEnumerable<SyntaxNode> _statementsOrFieldToInsert;
private readonly HashSet<SyntaxAnnotation> _variableToRemoveMap;
private readonly SyntaxNode _firstStatementOrFieldToReplace;
private readonly SyntaxNode _lastStatementOrFieldToReplace;
public CallSiteContainerRewriter(
SyntaxNode outmostCallSiteContainer,
HashSet<SyntaxAnnotation> variableToRemoveMap,
SyntaxNode firstStatementOrFieldToReplace,
SyntaxNode lastStatementOrFieldToReplace,
IEnumerable<SyntaxNode> statementsOrFieldToInsert)
{
Contract.ThrowIfNull(outmostCallSiteContainer);
Contract.ThrowIfNull(variableToRemoveMap);
Contract.ThrowIfNull(firstStatementOrFieldToReplace);
Contract.ThrowIfNull(lastStatementOrFieldToReplace);
Contract.ThrowIfNull(statementsOrFieldToInsert);
Contract.ThrowIfTrue(statementsOrFieldToInsert.IsEmpty());
_outmostCallSiteContainer = outmostCallSiteContainer;
_variableToRemoveMap = variableToRemoveMap;
_statementsOrFieldToInsert = statementsOrFieldToInsert;
_firstStatementOrFieldToReplace = firstStatementOrFieldToReplace;
_lastStatementOrFieldToReplace = lastStatementOrFieldToReplace;
Contract.ThrowIfFalse(_firstStatementOrFieldToReplace.Parent == _lastStatementOrFieldToReplace.Parent);
}
public SyntaxNode Generate()
{
return Visit(_outmostCallSiteContainer);
}
private SyntaxNode ContainerOfStatementsOrFieldToReplace => _firstStatementOrFieldToReplace.Parent;
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);
var list = new List<VariableDeclaratorSyntax>();
var triviaList = new List<SyntaxTrivia>();
// go through each var decls in decl statement
foreach (var variable in node.Declaration.Variables)
{
if (_variableToRemoveMap.HasSyntaxAnnotation(variable))
{
// if it had initialization, it shouldn't reach here.
Contract.ThrowIfFalse(variable.Initializer == null);
// we don't remove trivia around tokens we remove
triviaList.AddRange(variable.GetLeadingTrivia());
triviaList.AddRange(variable.GetTrailingTrivia());
continue;
}
if (triviaList.Count > 0)
{
list.Add(variable.WithPrependedLeadingTrivia(triviaList));
triviaList.Clear();
continue;
}
list.Add(variable);
}
if (list.Count == 0)
{
// nothing has survived. remove this from the list
if (triviaList.Count == 0)
{
return null;
}
// well, there are trivia associated with the node.
// we can't just delete the node since then, we will lose
// the trivia. unfortunately, it is not easy to attach the trivia
// to next token. for now, create an empty statement and associate the
// trivia to the statement
// TODO : think about a way to move the trivia to next token.
return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)));
}
if (list.Count == node.Declaration.Variables.Count)
{
// nothing has changed, return as it is
return node;
}
// TODO : fix how it manipulate trivia later
// if there is left over syntax trivia, it will be attached to leading trivia
// of semicolon
return
SyntaxFactory.LocalDeclarationStatement(
node.Modifiers,
SyntaxFactory.VariableDeclaration(
node.Declaration.Type,
SyntaxFactory.SeparatedList(list)),
node.SemicolonToken.WithPrependedLeadingTrivia(triviaList));
}
// for every kind of extract methods
public override SyntaxNode VisitBlock(BlockSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
// make sure we visit nodes under the block
return base.VisitBlock(node);
}
return node.WithStatements(VisitList(ReplaceStatements(node.Statements)).ToSyntaxList());
}
public override SyntaxNode VisitSwitchSection(SwitchSectionSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
// make sure we visit nodes under the switch section
return base.VisitSwitchSection(node);
}
return node.WithStatements(VisitList(ReplaceStatements(node.Statements)).ToSyntaxList());
}
// only for single statement or expression
public override SyntaxNode VisitLabeledStatement(LabeledStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitLabeledStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitElseClause(ElseClauseSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitElseClause(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitIfStatement(IfStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitIfStatement(node);
}
return node.WithCondition(VisitNode(node.Condition))
.WithStatement(ReplaceStatementIfNeeded(node.Statement))
.WithElse(VisitNode(node.Else));
}
public override SyntaxNode VisitLockStatement(LockStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitLockStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitFixedStatement(FixedStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitFixedStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitUsingStatement(UsingStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitUsingStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForEachStatement(ForEachStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForEachStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForEachVariableStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForStatement(ForStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithInitializers(VisitList(node.Initializers))
.WithCondition(VisitNode(node.Condition))
.WithIncrementors(VisitList(node.Incrementors))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitDoStatement(DoStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitDoStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement))
.WithCondition(VisitNode(node.Condition));
}
public override SyntaxNode VisitWhileStatement(WhileStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitWhileStatement(node);
}
return node.WithCondition(VisitNode(node.Condition))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
private TNode VisitNode<TNode>(TNode node) where TNode : SyntaxNode
{
return (TNode)Visit(node);
}
private StatementSyntax ReplaceStatementIfNeeded(StatementSyntax statement)
{
Contract.ThrowIfNull(statement);
// if all three same
if ((statement != _firstStatementOrFieldToReplace) || (_firstStatementOrFieldToReplace != _lastStatementOrFieldToReplace))
{
return statement;
}
// replace one statement with another
if (_statementsOrFieldToInsert.Count() == 1)
{
return _statementsOrFieldToInsert.Cast<StatementSyntax>().Single();
}
// replace one statement with multiple statements (see bug # 6310)
return SyntaxFactory.Block(SyntaxFactory.List(_statementsOrFieldToInsert.Cast<StatementSyntax>()));
}
private SyntaxList<StatementSyntax> ReplaceStatements(SyntaxList<StatementSyntax> statements)
{
// okay, this visit contains the statement
var newStatements = new List<StatementSyntax>(statements);
var firstStatementIndex = newStatements.FindIndex(s => s == _firstStatementOrFieldToReplace);
Contract.ThrowIfFalse(firstStatementIndex >= 0);
var lastStatementIndex = newStatements.FindIndex(s => s == _lastStatementOrFieldToReplace);
Contract.ThrowIfFalse(lastStatementIndex >= 0);
Contract.ThrowIfFalse(firstStatementIndex <= lastStatementIndex);
// remove statement that must be removed
newStatements.RemoveRange(firstStatementIndex, lastStatementIndex - firstStatementIndex + 1);
// add new statements to replace
newStatements.InsertRange(firstStatementIndex, _statementsOrFieldToInsert.Cast<StatementSyntax>());
return newStatements.ToSyntaxList();
}
private SyntaxList<MemberDeclarationSyntax> ReplaceMembers(SyntaxList<MemberDeclarationSyntax> members, bool global)
{
// okay, this visit contains the statement
var newMembers = new List<MemberDeclarationSyntax>(members);
var firstMemberIndex = newMembers.FindIndex(s => s == (global ? _firstStatementOrFieldToReplace.Parent : _firstStatementOrFieldToReplace));
Contract.ThrowIfFalse(firstMemberIndex >= 0);
var lastMemberIndex = newMembers.FindIndex(s => s == (global ? _lastStatementOrFieldToReplace.Parent : _lastStatementOrFieldToReplace));
Contract.ThrowIfFalse(lastMemberIndex >= 0);
Contract.ThrowIfFalse(firstMemberIndex <= lastMemberIndex);
// remove statement that must be removed
newMembers.RemoveRange(firstMemberIndex, lastMemberIndex - firstMemberIndex + 1);
// add new statements to replace
newMembers.InsertRange(firstMemberIndex,
_statementsOrFieldToInsert.Select(s => global ? SyntaxFactory.GlobalStatement((StatementSyntax)s) : (MemberDeclarationSyntax)s));
return newMembers.ToSyntaxList();
}
public override SyntaxNode VisitGlobalStatement(GlobalStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitGlobalStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitConstructorDeclaration(node);
}
Contract.ThrowIfFalse(_firstStatementOrFieldToReplace == _lastStatementOrFieldToReplace);
return node.WithInitializer((ConstructorInitializerSyntax)_statementsOrFieldToInsert.Single());
}
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitClassDeclaration(node);
}
var newMembers = VisitList(ReplaceMembers(node.Members, global: false));
return node.WithMembers(newMembers);
}
public override SyntaxNode VisitStructDeclaration(StructDeclarationSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitStructDeclaration(node);
}
var newMembers = VisitList(ReplaceMembers(node.Members, global: false));
return node.WithMembers(newMembers);
}
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace.Parent)
{
// make sure we visit nodes under the block
return base.VisitCompilationUnit(node);
}
var newMembers = VisitList(ReplaceMembers(node.Members, global: true));
return node.WithMembers(newMembers);
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using Signum.Utilities;
using Signum.Entities;
namespace Signum.Engine.SchemaInfoTables
{
#pragma warning disable 649
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
[TableName("sys.objects")]
public class SysObjects : IView
{
[ViewPrimaryKey]
public int object_id;
public int schema_id;
public string type;
public string type_desc;
public string name;
}
[TableName("sys.servers")]
public class SysServers : IView
{
[ViewPrimaryKey]
public int server_id;
public string name;
}
[TableName("sys.databases")]
public class SysDatabases : IView
{
[ViewPrimaryKey]
public int database_id;
public string name;
public byte[] owner_sid;
public string collation_name;
public bool is_broker_enabled;
public bool snapshot_isolation_state;
public bool is_read_committed_snapshot_on;
}
[TableName("sys.server_principals")]
public class SysServerPrincipals : IView
{
[ViewPrimaryKey]
public int principal_id;
public string name;
public byte[] sid;
public string type_desc;
}
[TableName("sys.database_principals")]
public class SysDatabasePrincipals : IView
{
[ViewPrimaryKey]
public int principal_id;
public string name;
public byte[] sid;
public string type_desc;
}
[TableName("sys.schemas")]
public class SysSchemas : IView
{
[ViewPrimaryKey]
public int schema_id;
public string name;
[AutoExpressionField]
public IQueryable<SysTables> Tables() =>
As.Expression(() => Database.View<SysTables>().Where(t => t.schema_id == this.schema_id));
}
[TableName("sys.periods")]
public class SysPeriods : IView
{
[ViewPrimaryKey]
public int object_id;
public int start_column_id;
public int end_column_id;
}
[TableName("sys.tables")]
public class SysTables : IView
{
public string name;
[ViewPrimaryKey]
public int object_id;
public int schema_id;
[ColumnName("temporal_type")]
public SysTableTemporalType temporal_type;
public int? history_table_id;
[AutoExpressionField]
public IQueryable<SysColumns> Columns() =>
As.Expression(() => Database.View<SysColumns>().Where(c => c.object_id == this.object_id));
public IQueryable<SysColumns> ColumnsOriginal() =>
As.Expression(() => Database.View<SysColumns>().Where(c => c.object_id == this.object_id));
static Expression<Func<SysTables, IQueryable<SysColumns>>> ColumnsGood;
static void ColumnsGoodInit()
{
ColumnsGood = @this => Database.View<SysColumns>().Where(c => c.object_id == @this.object_id);
}
[AutoExpressionField]
public IQueryable<SysForeignKeys> ForeignKeys() =>
As.Expression(() => Database.View<SysForeignKeys>().Where(fk => fk.parent_object_id == this.object_id));
[AutoExpressionField]
public IQueryable<SysForeignKeys> IncommingForeignKeys() =>
As.Expression(() => Database.View<SysForeignKeys>().Where(fk => fk.referenced_object_id == this.object_id));
[AutoExpressionField]
public IQueryable<SysKeyConstraints> KeyConstraints() =>
As.Expression(() => Database.View<SysKeyConstraints>().Where(fk => fk.parent_object_id == this.object_id));
[AutoExpressionField]
public IQueryable<SysIndexes> Indices() =>
As.Expression(() => Database.View<SysIndexes>().Where(ix => ix.object_id == this.object_id));
[AutoExpressionField]
public IQueryable<SysStats> Stats() =>
As.Expression(() => Database.View<SysStats>().Where(ix => ix.object_id == this.object_id));
[AutoExpressionField]
public IQueryable<SysExtendedProperties> ExtendedProperties() =>
As.Expression(() => Database.View<SysExtendedProperties>().Where(ep => ep.major_id == this.object_id));
[AutoExpressionField]
public IQueryable<SysForeignKeyColumns> ForeignKeyColumns() =>
As.Expression(() => Database.View<SysForeignKeyColumns>().Where(fkc => fkc.parent_object_id == this.object_id));
[AutoExpressionField]
public IQueryable<SysPeriods> Periods() =>
As.Expression(() => Database.View<SysPeriods>().Where(p => p.object_id == this.object_id));
[AutoExpressionField]
public SysSchemas Schema() =>
As.Expression(() => Database.View<SysSchemas>().Single(a => a.schema_id == this.schema_id));
}
[TableName("sys.views")]
public class SysViews : IView
{
public string name;
[ViewPrimaryKey]
public int object_id;
public int schema_id;
[AutoExpressionField]
public IQueryable<SysIndexes> Indices() =>
As.Expression(() => Database.View<SysIndexes>().Where(ix => ix.object_id == this.object_id));
[AutoExpressionField]
public IQueryable<SysColumns> Columns() =>
As.Expression(() => Database.View<SysColumns>().Where(c => c.object_id == this.object_id));
}
[TableName("sys.columns")]
public class SysColumns : IView
{
public string name;
[ViewPrimaryKey]
public int object_id;
public int column_id;
public int default_object_id;
public string collation_name;
public bool is_nullable;
public int user_type_id;
public int system_type_id;
public int max_length;
public int precision;
public int scale;
public bool is_identity;
[ColumnName("generated_always_type")]
public GeneratedAlwaysType generated_always_type;
[AutoExpressionField]
public SysTypes? Type() =>
As.Expression(() => Database.View<SysTypes>().SingleOrDefaultEx(a => a.system_type_id == this.system_type_id && a.user_type_id == this.user_type_id));
}
[TableName("sys.default_constraints")]
public class SysDefaultConstraints : IView
{
public string name;
public int object_id;
public int parent_object_id;
public int parent_column_id;
public string definition;
public bool is_system_named;
}
[TableName("sys.types")]
public class SysTypes : IView
{
[ViewPrimaryKey]
public int system_type_id;
public int user_type_id;
public string name;
}
[TableName("sys.key_constraints")]
public class SysKeyConstraints : IView
{
public string name;
[ViewPrimaryKey]
public int object_id;
public int schema_id;
public int parent_object_id;
public string type;
[AutoExpressionField]
public SysSchemas Schema() =>
As.Expression(() => Database.View<SysSchemas>().Single(a => a.schema_id == this.schema_id));
}
[TableName("sys.foreign_keys")]
public class SysForeignKeys : IView
{
[ViewPrimaryKey]
public int object_id;
public int schema_id;
public string name;
public int parent_object_id;
public int referenced_object_id;
public bool is_disabled;
public bool is_not_trusted;
[AutoExpressionField]
public IQueryable<SysForeignKeyColumns> ForeignKeyColumns() =>
As.Expression(() => Database.View<SysForeignKeyColumns>().Where(fkc => fkc.constraint_object_id == this.object_id));
[AutoExpressionField]
public SysSchemas Schema() =>
As.Expression(() => Database.View<SysSchemas>().Single(a => a.schema_id == this.schema_id));
[AutoExpressionField]
public SysTables ParentTable() =>
As.Expression(() => Database.View<SysTables>().Single(a => a.object_id == this.parent_object_id));
[AutoExpressionField]
public SysTables ReferencedTable() =>
As.Expression(() => Database.View<SysTables>().Single(a => a.object_id == this.referenced_object_id));
}
[TableName("sys.foreign_key_columns")]
public class SysForeignKeyColumns : IView
{
public int constraint_object_id;
public int constraint_column_id;
public int parent_object_id;
public int parent_column_id;
public int referenced_object_id;
public int referenced_column_id;
}
[TableName("sys.indexes")]
public class SysIndexes : IView
{
[ViewPrimaryKey]
public int index_id;
public string name;
public int object_id;
public bool is_unique;
public bool is_primary_key;
public int type;
public string filter_definition;
[AutoExpressionField]
public IQueryable<SysIndexColumn> IndexColumns() =>
As.Expression(() => Database.View<SysIndexColumn>().Where(ixc => ixc.index_id == this.index_id && ixc.object_id == this.object_id));
[AutoExpressionField]
public SysTables Table() =>
As.Expression(() => Database.View<SysTables>().Single(a => a.object_id == this.object_id));
[AutoExpressionField]
public SysPartitions Partition() =>
As.Expression(() => Database.View<SysPartitions>().SingleOrDefault(au => au.object_id == this.object_id && au.index_id == this.index_id));
}
[TableName("sys.index_columns")]
public class SysIndexColumn : IView
{
public int object_id;
public int index_id;
public int column_id;
public int index_column_id;
public int key_ordinal;
public bool is_included_column;
public bool is_descending_key;
}
[TableName("sys.stats")]
public class SysStats : IView
{
[ViewPrimaryKey]
public int object_id;
public int stats_id;
public string name;
public bool auto_created;
public bool user_created;
public bool no_recompute;
[AutoExpressionField]
public IQueryable<SysStatsColumn> StatsColumns() =>
As.Expression(() => Database.View<SysStatsColumn>().Where(ixc => ixc.stats_id == this.stats_id && ixc.object_id == this.object_id));
}
[TableName("sys.stats_columns")]
public class SysStatsColumn : IView
{
public int object_id;
public int stats_id;
public int stats_column_id;
public int column_id;
}
[TableName("sys.extended_properties")]
public class SysExtendedProperties : IView
{
public int major_id;
public string name;
}
[TableName("sys.sql_modules")]
public class SysSqlModules : IView
{
[ViewPrimaryKey]
public int object_id;
public string definition;
}
[TableName("sys.procedures")]
public class SysProcedures : IView
{
[ViewPrimaryKey]
public int object_id;
public int schema_id;
public string name;
[AutoExpressionField]
public SysSchemas Schema() =>
As.Expression(() => Database.View<SysSchemas>().Single(a => a.schema_id == this.schema_id));
}
[TableName("sys.service_queues")]
public class SysServiceQueues : IView
{
[ViewPrimaryKey]
public int object_id;
public int schema_id;
public string name;
public string activation_procedure;
[AutoExpressionField]
public SysSchemas Schema() =>
As.Expression(() => Database.View<SysSchemas>().Single(a => a.schema_id == this.schema_id));
}
[TableName("sys.partitions")]
public class SysPartitions : IView
{
[ViewPrimaryKey]
public int partition_id;
public int object_id;
public int index_id;
public int rows;
[AutoExpressionField]
public IQueryable<SysAllocationUnits> AllocationUnits() =>
As.Expression(() => Database.View<SysAllocationUnits>().Where(au => au.container_id == this.partition_id));
}
[TableName("sys.allocation_units")]
public class SysAllocationUnits : IView
{
[ViewPrimaryKey]
public int container_id;
public int total_pages;
}
#pragma warning restore 649
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class GridServicesConnector : IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
public GridServicesConnector()
{
}
public GridServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public GridServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[GRID CONNECTOR]: GridService missing from OpenSim.ini");
throw new Exception("Grid connector init error");
}
string serviceURI = gridConfig.GetString("GridServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[GRID CONNECTOR]: No Server URI named in section GridService");
throw new Exception("Grid connector init error");
}
m_ServerURI = serviceURI;
}
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
Dictionary<string, object> rinfo = regionInfo.ToKeyValuePairs();
Dictionary<string, object> sendData = new Dictionary<string,object>();
foreach (KeyValuePair<string, object> kvp in rinfo)
sendData[kvp.Key] = (string)kvp.Value;
sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "register";
string reqString = ServerUtils.BuildQueryString(sendData);
string uri = m_ServerURI + "/grid";
// m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString);
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "success"))
{
return String.Empty;
}
else if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "failure"))
{
m_log.ErrorFormat(
"[GRID CONNECTOR]: Registration failed: {0} when contacting {1}", replyData["Message"], uri);
return replyData["Message"].ToString();
}
else if (!replyData.ContainsKey("Result"))
{
m_log.ErrorFormat(
"[GRID CONNECTOR]: reply data does not contain result field when contacting {0}", uri);
}
else
{
m_log.ErrorFormat(
"[GRID CONNECTOR]: unexpected result {0} when contacting {1}", replyData["Result"], uri);
return "Unexpected result " + replyData["Result"].ToString();
}
}
else
{
m_log.ErrorFormat(
"[GRID CONNECTOR]: RegisterRegion received null reply when contacting grid server at {0}", uri);
}
}
catch (Exception e)
{
m_log.ErrorFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
}
return string.Format("Error communicating with the grid service at {0}", uri);
}
public bool DeregisterRegion(UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "deregister";
string uri = m_ServerURI + "/grid";
try
{
string reply
= SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData));
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData["Result"] != null) && (replyData["Result"].ToString().ToLower() == "success"))
return true;
}
else
m_log.DebugFormat("[GRID CONNECTOR]: DeregisterRegion received null reply");
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
}
return false;
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_neighbours";
List<GridRegion> rinfos = new List<GridRegion>();
string reqString = ServerUtils.BuildQueryString(sendData);
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
//m_log.DebugFormat("[GRID CONNECTOR]: get neighbours returned {0} elements", rinfosList.Count);
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received null response",
scopeID, regionID);
return rinfos;
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_region_by_uuid";
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
// scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID received null reply");
return rinfo;
}
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["X"] = x.ToString();
sendData["Y"] = y.ToString();
sendData["METHOD"] = "get_region_by_position";
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received no region",
// scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received null response",
scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition received null reply");
return rinfo;
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["NAME"] = regionName;
sendData["METHOD"] = "get_region_by_name";
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1} received null response",
scopeID, regionName);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByName received null reply");
return rinfo;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["NAME"] = name;
sendData["MAX"] = maxNumber.ToString();
sendData["METHOD"] = "get_regions_by_name";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received null response",
scopeID, name, maxNumber);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName received null reply");
return rinfos;
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["XMIN"] = xmin.ToString();
sendData["XMAX"] = xmax.ToString();
sendData["YMIN"] = ymin.ToString();
sendData["YMAX"] = ymax.ToString();
sendData["METHOD"] = "get_region_range";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange {0}, {1}-{2} {3}-{4} received null response",
scopeID, xmin, xmax, ymin, ymax);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange received null reply");
return rinfos;
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["METHOD"] = "get_default_regions";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions {0} received null response",
scopeID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions received null reply");
return rinfos;
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["METHOD"] = "get_default_hypergrid_regions";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultHypergridRegions {0} received null response",
scopeID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultHypergridRegions received null reply");
return rinfos;
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["X"] = x.ToString();
sendData["Y"] = y.ToString();
sendData["METHOD"] = "get_fallback_regions";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions {0}, {1}-{2} received null response",
scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions received null reply");
return rinfos;
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["METHOD"] = "get_hyperlinks";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks {0} received null response",
scopeID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks received null reply");
return rinfos;
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_region_flags";
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return -1;
}
int flags = -1;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null))
{
Int32.TryParse((string)replyData["result"], out flags);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags {0}, {1} received wrong type {2}",
// scopeID, regionID, replyData["result"].GetType());
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags {0}, {1} received null response",
scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags received null reply");
return flags;
}
#endregion
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
/// <summary>
/// Represents a user configuration's Dictionary property.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class UserConfigurationDictionary : ComplexProperty, IEnumerable
{
// TODO: Consider implementing IsDirty mechanism in ComplexProperty.
private Dictionary<object, object> dictionary;
private bool isDirty = false;
/// <summary>
/// Initializes a new instance of <see cref="UserConfigurationDictionary"/> class.
/// </summary>
internal UserConfigurationDictionary()
: base()
{
this.dictionary = new Dictionary<object, object>();
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key of the element to get or set.</param>
/// <returns>The element with the specified key.</returns>
public object this[object key]
{
get
{
return this.dictionary[key];
}
set
{
this.ValidateEntry(key, value);
this.dictionary[key] = value;
this.Changed();
}
}
/// <summary>
/// Adds an element with the provided key and value to the user configuration dictionary.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
public void Add(object key, object value)
{
this.ValidateEntry(key, value);
this.dictionary.Add(key, value);
this.Changed();
}
/// <summary>
/// Determines whether the user configuration dictionary contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the user configuration dictionary.</param>
/// <returns>true if the user configuration dictionary contains an element with the key; otherwise false.</returns>
public bool ContainsKey(object key)
{
return this.dictionary.ContainsKey(key);
}
/// <summary>
/// Removes the element with the specified key from the user configuration dictionary.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>true if the element is successfully removed; otherwise false.</returns>
public bool Remove(object key)
{
bool isRemoved = this.dictionary.Remove(key);
if (isRemoved)
{
this.Changed();
}
return isRemoved;
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, null.</param>
/// <returns>true if the user configuration dictionary contains the key; otherwise false.</returns>
public bool TryGetValue(object key, out object value)
{
return this.dictionary.TryGetValue(key, out value);
}
/// <summary>
/// Gets the number of elements in the user configuration dictionary.
/// </summary>
public int Count
{
get
{
return this.dictionary.Count;
}
}
/// <summary>
/// Removes all items from the user configuration dictionary.
/// </summary>
public void Clear()
{
if (this.dictionary.Count != 0)
{
this.dictionary.Clear();
this.Changed();
}
}
#region IEnumerable members
/// <summary>
/// Returns an enumerator that iterates through the user configuration dictionary.
/// </summary>
/// <returns>An IEnumerator that can be used to iterate through the user configuration dictionary.</returns>
public IEnumerator GetEnumerator()
{
return this.dictionary.GetEnumerator();
}
#endregion
/// <summary>
/// Gets or sets the isDirty flag.
/// </summary>
internal bool IsDirty
{
get
{
return this.isDirty;
}
set
{
this.isDirty = value;
}
}
/// <summary>
/// Instance was changed.
/// </summary>
internal override void Changed()
{
base.Changed();
this.isDirty = true;
}
/// <summary>
/// Writes elements to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
EwsUtilities.Assert(
writer != null,
"UserConfigurationDictionary.WriteElementsToXml",
"writer is null");
foreach (KeyValuePair<object, object> dictionaryEntry in this.dictionary)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.DictionaryEntry);
this.WriteObjectToXml(
writer,
XmlElementNames.DictionaryKey,
dictionaryEntry.Key);
this.WriteObjectToXml(
writer,
XmlElementNames.DictionaryValue,
dictionaryEntry.Value);
writer.WriteEndElement();
}
}
/// <summary>
/// Gets the type code.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="dictionaryObject">The dictionary object.</param>
/// <param name="dictionaryObjectType">Type of the dictionary object.</param>
/// <param name="valueAsString">The value as string.</param>
private static void GetTypeCode(ExchangeServiceBase service, object dictionaryObject, ref UserConfigurationDictionaryObjectType dictionaryObjectType, ref string valueAsString)
{
// Handle all other types by TypeCode
switch (Type.GetTypeCode(dictionaryObject.GetType()))
{
case TypeCode.Boolean:
dictionaryObjectType = UserConfigurationDictionaryObjectType.Boolean;
valueAsString = EwsUtilities.BoolToXSBool((bool)dictionaryObject);
break;
case TypeCode.Byte:
dictionaryObjectType = UserConfigurationDictionaryObjectType.Byte;
valueAsString = ((byte)dictionaryObject).ToString();
break;
case TypeCode.DateTime:
dictionaryObjectType = UserConfigurationDictionaryObjectType.DateTime;
valueAsString = service.ConvertDateTimeToUniversalDateTimeString((DateTime)dictionaryObject);
break;
case TypeCode.Int32:
dictionaryObjectType = UserConfigurationDictionaryObjectType.Integer32;
valueAsString = ((int)dictionaryObject).ToString();
break;
case TypeCode.Int64:
dictionaryObjectType = UserConfigurationDictionaryObjectType.Integer64;
valueAsString = ((long)dictionaryObject).ToString();
break;
case TypeCode.String:
dictionaryObjectType = UserConfigurationDictionaryObjectType.String;
valueAsString = (string)dictionaryObject;
break;
case TypeCode.UInt32:
dictionaryObjectType = UserConfigurationDictionaryObjectType.UnsignedInteger32;
valueAsString = ((uint)dictionaryObject).ToString();
break;
case TypeCode.UInt64:
dictionaryObjectType = UserConfigurationDictionaryObjectType.UnsignedInteger64;
valueAsString = ((ulong)dictionaryObject).ToString();
break;
default:
EwsUtilities.Assert(
false,
"UserConfigurationDictionary.WriteObjectValueToXml",
"Unsupported type: " + dictionaryObject.GetType().ToString());
break;
}
}
/// <summary>
/// Gets the type of the object.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private static UserConfigurationDictionaryObjectType GetObjectType(string type)
{
return (UserConfigurationDictionaryObjectType)Enum.Parse(typeof(UserConfigurationDictionaryObjectType), type, false);
}
/// <summary>
/// Writes a dictionary object (key or value) to Xml.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="xmlElementName">The Xml element name.</param>
/// <param name="dictionaryObject">The object to write.</param>
private void WriteObjectToXml(
EwsServiceXmlWriter writer,
string xmlElementName,
object dictionaryObject)
{
EwsUtilities.Assert(
writer != null,
"UserConfigurationDictionary.WriteObjectToXml",
"writer is null");
EwsUtilities.Assert(
xmlElementName != null,
"UserConfigurationDictionary.WriteObjectToXml",
"xmlElementName is null");
writer.WriteStartElement(XmlNamespace.Types, xmlElementName);
if (dictionaryObject == null)
{
EwsUtilities.Assert(
xmlElementName != XmlElementNames.DictionaryKey,
"UserConfigurationDictionary.WriteObjectToXml",
"Key is null");
writer.WriteAttributeValue(
EwsUtilities.EwsXmlSchemaInstanceNamespacePrefix,
XmlAttributeNames.Nil,
EwsUtilities.XSTrue);
}
else
{
this.WriteObjectValueToXml(writer, dictionaryObject);
}
writer.WriteEndElement();
}
/// <summary>
/// Writes a dictionary Object's value to Xml.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="dictionaryObject">The dictionary object to write.</param>
private void WriteObjectValueToXml(EwsServiceXmlWriter writer, object dictionaryObject)
{
EwsUtilities.Assert(
writer != null,
"UserConfigurationDictionary.WriteObjectValueToXml",
"writer is null");
EwsUtilities.Assert(
dictionaryObject != null,
"UserConfigurationDictionary.WriteObjectValueToXml",
"dictionaryObject is null");
// This logic is based on Microsoft.Exchange.Services.Core.GetUserConfiguration.ConstructDictionaryObject().
//
// Object values are either:
// . an array of strings
// . a single value
//
// Single values can be:
// . base64 string (from a byte array)
// . datetime, boolean, byte, short, int, long, string, ushort, unint, ulong
//
// First check for a string array
string[] dictionaryObjectAsStringArray = dictionaryObject as string[];
if (dictionaryObjectAsStringArray != null)
{
this.WriteEntryTypeToXml(writer, UserConfigurationDictionaryObjectType.StringArray);
foreach (string arrayElement in dictionaryObjectAsStringArray)
{
this.WriteEntryValueToXml(writer, arrayElement);
}
}
else
{
// if not a string array, all other object values are returned as a single element
UserConfigurationDictionaryObjectType dictionaryObjectType = UserConfigurationDictionaryObjectType.String;
string valueAsString = null;
byte[] dictionaryObjectAsByteArray = dictionaryObject as byte[];
if (dictionaryObjectAsByteArray != null)
{
// Convert byte array to base64 string
dictionaryObjectType = UserConfigurationDictionaryObjectType.ByteArray;
valueAsString = Convert.ToBase64String(dictionaryObjectAsByteArray);
}
else
{
GetTypeCode(writer.Service, dictionaryObject, ref dictionaryObjectType, ref valueAsString);
}
this.WriteEntryTypeToXml(writer, dictionaryObjectType);
this.WriteEntryValueToXml(writer, valueAsString);
}
}
/// <summary>
/// Writes a dictionary entry type to Xml.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="dictionaryObjectType">Type to write.</param>
private void WriteEntryTypeToXml(EwsServiceXmlWriter writer, UserConfigurationDictionaryObjectType dictionaryObjectType)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Type);
writer.WriteValue(dictionaryObjectType.ToString(), XmlElementNames.Type);
writer.WriteEndElement();
}
/// <summary>
/// Writes a dictionary entry value to Xml.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="value">Value to write.</param>
private void WriteEntryValueToXml(EwsServiceXmlWriter writer, string value)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Value);
// While an entry value can't be null, if the entry is an array, an element of the array can be null.
if (value != null)
{
writer.WriteValue(value, XmlElementNames.Value);
}
writer.WriteEndElement();
}
/// <summary>
/// Loads this dictionary from the specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="xmlNamespace">The dictionary's XML namespace.</param>
/// <param name="xmlElementName">Name of the XML element representing the dictionary.</param>
internal override void LoadFromXml(
EwsServiceXmlReader reader,
XmlNamespace xmlNamespace,
string xmlElementName)
{
base.LoadFromXml(
reader,
xmlNamespace,
xmlElementName);
this.isDirty = false;
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
reader.EnsureCurrentNodeIsStartElement(this.Namespace, XmlElementNames.DictionaryEntry);
this.LoadEntry(reader);
return true;
}
/// <summary>
/// Loads an entry, consisting of a key value pair, into this dictionary from the specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
private void LoadEntry(EwsServiceXmlReader reader)
{
EwsUtilities.Assert(
reader != null,
"UserConfigurationDictionary.LoadEntry",
"reader is null");
object key;
object value = null;
// Position at DictionaryKey
reader.ReadStartElement(this.Namespace, XmlElementNames.DictionaryKey);
key = this.GetDictionaryObject(reader);
// Position at DictionaryValue
reader.ReadStartElement(this.Namespace, XmlElementNames.DictionaryValue);
string nil = reader.ReadAttributeValue(XmlNamespace.XmlSchemaInstance, XmlAttributeNames.Nil);
bool hasValue = (nil == null) || (! Convert.ToBoolean(nil));
if (hasValue)
{
value = this.GetDictionaryObject(reader);
}
this.dictionary.Add(key, value);
}
/// <summary>
/// Gets the object value.
/// </summary>
/// <param name="valueArray">The value array.</param>
///
/// <returns></returns>
private List<string> GetObjectValue(object[] valueArray)
{
List<string> stringArray = new List<string>();
foreach (object value in valueArray)
{
stringArray.Add(value as string);
}
return stringArray;
}
/// <summary>
/// Extracts a dictionary object (key or entry value) from the specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>Dictionary object.</returns>
private object GetDictionaryObject(EwsServiceXmlReader reader)
{
EwsUtilities.Assert(
reader != null,
"UserConfigurationDictionary.LoadFromXml",
"reader is null");
UserConfigurationDictionaryObjectType type = this.GetObjectType(reader);
List<string> values = this.GetObjectValue(reader, type);
return this.ConstructObject(type, values, reader.Service);
}
/// <summary>
/// Extracts a dictionary object (key or entry value) as a string list from the
/// specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="type">The object type.</param>
/// <returns>String list representing a dictionary object.</returns>
private List<string> GetObjectValue(EwsServiceXmlReader reader, UserConfigurationDictionaryObjectType type)
{
EwsUtilities.Assert(
reader != null,
"UserConfigurationDictionary.LoadFromXml",
"reader is null");
List<string> values = new List<string>();
reader.ReadStartElement(this.Namespace, XmlElementNames.Value);
do
{
string value = null;
if (reader.IsEmptyElement)
{
// Only string types can be represented with empty values.
switch (type)
{
case UserConfigurationDictionaryObjectType.String:
case UserConfigurationDictionaryObjectType.StringArray:
value = string.Empty;
break;
default:
EwsUtilities.Assert(
false,
"UserConfigurationDictionary.GetObjectValue",
"Empty element passed for type: " + type.ToString());
break;
}
}
else
{
value = reader.ReadElementValue();
}
values.Add(value);
reader.Read(); // Position at next element or DictionaryKey/DictionaryValue end element
}
while (reader.IsStartElement(this.Namespace, XmlElementNames.Value));
return values;
}
/// <summary>
/// Extracts the dictionary object (key or entry value) type from the specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>Dictionary object type.</returns>
private UserConfigurationDictionaryObjectType GetObjectType(EwsServiceXmlReader reader)
{
EwsUtilities.Assert(
reader != null,
"UserConfigurationDictionary.LoadFromXml",
"reader is null");
reader.ReadStartElement(this.Namespace, XmlElementNames.Type);
string type = reader.ReadElementValue();
return GetObjectType(type);
}
/// <summary>
/// Constructs a dictionary object (key or entry value) from the specified type and string list.
/// </summary>
/// <param name="type">Object type to construct.</param>
/// <param name="value">Value of the dictionary object as a string list</param>
/// <param name="service">The service.</param>
/// <returns>Dictionary object.</returns>
private object ConstructObject(
UserConfigurationDictionaryObjectType type,
List<string> value,
ExchangeService service)
{
EwsUtilities.Assert(
value != null,
"UserConfigurationDictionary.ConstructObject",
"value is null");
EwsUtilities.Assert(
(value.Count == 1 || type == UserConfigurationDictionaryObjectType.StringArray),
"UserConfigurationDictionary.ConstructObject",
"value is array but type is not StringArray");
object dictionaryObject = null;
switch (type)
{
case UserConfigurationDictionaryObjectType.Boolean:
dictionaryObject = bool.Parse(value[0]);
break;
case UserConfigurationDictionaryObjectType.Byte:
dictionaryObject = byte.Parse(value[0]);
break;
case UserConfigurationDictionaryObjectType.ByteArray:
dictionaryObject = Convert.FromBase64String(value[0]);
break;
case UserConfigurationDictionaryObjectType.DateTime:
DateTime? dateTime = service.ConvertUniversalDateTimeStringToLocalDateTime(value[0]);
if (dateTime.HasValue)
{
dictionaryObject = dateTime.Value;
}
else
{
EwsUtilities.Assert(
false,
"UserConfigurationDictionary.ConstructObject",
"DateTime is null");
}
break;
case UserConfigurationDictionaryObjectType.Integer32:
dictionaryObject = int.Parse(value[0]);
break;
case UserConfigurationDictionaryObjectType.Integer64:
dictionaryObject = long.Parse(value[0]);
break;
case UserConfigurationDictionaryObjectType.String:
dictionaryObject = value[0];
break;
case UserConfigurationDictionaryObjectType.StringArray:
dictionaryObject = value.ToArray();
break;
case UserConfigurationDictionaryObjectType.UnsignedInteger32:
dictionaryObject = uint.Parse(value[0]);
break;
case UserConfigurationDictionaryObjectType.UnsignedInteger64:
dictionaryObject = ulong.Parse(value[0]);
break;
default:
EwsUtilities.Assert(
false,
"UserConfigurationDictionary.ConstructObject",
"Type not recognized: " + type.ToString());
break;
}
return dictionaryObject;
}
/// <summary>
/// Validates the specified key and value.
/// </summary>
/// <param name="key">The dictionary entry key.</param>
/// <param name="value">The dictionary entry value.</param>
private void ValidateEntry(object key, object value)
{
this.ValidateObject(key);
this.ValidateObject(value);
}
/// <summary>
/// Validates the dictionary object (key or entry value).
/// </summary>
/// <param name="dictionaryObject">Object to validate.</param>
private void ValidateObject(object dictionaryObject)
{
// Keys may not be null but we rely on the internal dictionary to throw if the key is null.
if (dictionaryObject != null)
{
Array dictionaryObjectAsArray = dictionaryObject as Array;
if (dictionaryObjectAsArray != null)
{
this.ValidateArrayObject(dictionaryObjectAsArray);
}
else
{
this.ValidateObjectType(dictionaryObject.GetType());
}
}
}
/// <summary>
/// Validate the array object.
/// </summary>
/// <param name="dictionaryObjectAsArray">Object to validate</param>
private void ValidateArrayObject(Array dictionaryObjectAsArray)
{
// This logic is based on Microsoft.Exchange.Data.Storage.ConfigurationDictionary.CheckElementSupportedType().
if (dictionaryObjectAsArray is string[])
{
if (dictionaryObjectAsArray.Length > 0)
{
foreach (object arrayElement in dictionaryObjectAsArray)
{
if (arrayElement == null)
{
throw new ServiceLocalException(Strings.NullStringArrayElementInvalid);
}
}
}
else
{
throw new ServiceLocalException(Strings.ZeroLengthArrayInvalid);
}
}
else if (dictionaryObjectAsArray is byte[])
{
if (dictionaryObjectAsArray.Length <= 0)
{
throw new ServiceLocalException(Strings.ZeroLengthArrayInvalid);
}
}
else
{
throw new ServiceLocalException(string.Format(Strings.ObjectTypeNotSupported, dictionaryObjectAsArray.GetType()));
}
}
/// <summary>
/// Validates the dictionary object type.
/// </summary>
/// <param name="type">Type to validate.</param>
private void ValidateObjectType(Type type)
{
// This logic is based on Microsoft.Exchange.Data.Storage.ConfigurationDictionary.CheckElementSupportedType().
bool isValidType = false;
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.DateTime:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.String:
case TypeCode.UInt32:
case TypeCode.UInt64:
isValidType = true;
break;
}
if (! isValidType)
{
throw new ServiceLocalException(string.Format(Strings.ObjectTypeNotSupported, type));
}
}
}
}
| |
using System;
using Microsoft.SPOT.Hardware;
using System.Threading;
namespace uPLibrary.Hardware.Nfc
{
/// <summary>
/// I2C communication layer
/// </summary>
public class PN532CommunicationI2C : IPN532CommunicationLayer
{
#region I2C Constants ...
// NOTE : in pn532um.pdf on pag. 43 the following addresses are reported :
// Write = 0x48, Read = 0x49
// These addresses already consider the last bit of I2C (0 = W, 1 = R) but the address of
// a I2C device is 7 bit so we have to consider only the first 7 bit -> 0x24 is PN532 unique address
private const ushort PN532_I2C_ADDRESS = 0x24;
private const int PN532_I2C_CLOCK_RATE_KHZ = 200;
private const int PN532_I2C_TIMEOUT = 1000;
#endregion
// i2c interface
I2CDevice i2c;
// irq interrupt port and event related
InterruptPort irq;
AutoResetEvent whIrq;
/// <summary>
/// Constructor
/// </summary>
public PN532CommunicationI2C()
: this(Cpu.Pin.GPIO_NONE)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="irq">Pin related to IRQ from PN532</param>
public PN532CommunicationI2C(Cpu.Pin irq)
{
this.i2c = new I2CDevice(new I2CDevice.Configuration(PN532_I2C_ADDRESS, PN532_I2C_CLOCK_RATE_KHZ));
this.irq = null;
// use advanced handshake with IRQ pin (pn532um.pdf, pag. 44)
if (irq != Cpu.Pin.GPIO_NONE)
{
this.irq = new InterruptPort(irq, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow);
this.irq.OnInterrupt += irq_OnInterrupt;
this.whIrq = new AutoResetEvent(false);
}
}
#region IPN532CommunicationLayer interface ...
public bool SendNormalFrame(byte[] frame)
{
this.I2CWrite(frame);
// read acknowledge
byte[] acknowledge = this.ReadAcknowledge();
// if null, timeout waiting READY byte
if (acknowledge == null)
return false;
// return true or flase if ACK or NACK
if ((acknowledge[0] == PN532.ACK_PACKET_CODE[0] &&
acknowledge[1] == PN532.ACK_PACKET_CODE[1]))
return true;
else
return false;
}
public byte[] ReadNormalFrame()
{
byte[] read = new byte[PN532.PN532_EXTENDED_FRAME_MAX_LEN];
// using IRQ enabled
if (this.irq != null)
{
// wait for IRQ from PN532 if enabled
if (!this.whIrq.WaitOne(PN532.PN532_READY_TIMEOUT, false))
return null;
this.I2CRead(read);
}
else
{
long start = DateTime.Now.Ticks;
// waiting for status ready
while (read[0] != PN532.PN532_READY)
{
this.I2CRead(read);
// check timeout
if ((DateTime.Now.Ticks - start) / PN532.TICKS_PER_MILLISECONDS < PN532.PN532_READY_TIMEOUT)
Thread.Sleep(10);
else
return null;
}
}
// extract data len
byte len = read[PN532.PN532_LEN_OFFSET + 1]; // + 1, first byte is READY BYTE
// create buffer for all frame bytes
byte[] frame = new byte[5 + len + 2];
// save first part of received frame (first 5 bytes until LCS)
Array.Copy(read, 1, frame, 0, PN532.PN532_LCS_OFFSET + 1); // sourceIndex = 1, first byte is READY BYTE
// copy last part of the frame (data + DCS + POSTAMBLE)
Array.Copy(read, PN532.PN532_LCS_OFFSET + 1 + 1, frame, 5, len + 2); // sourceIndex = (PN532.PN532_LCS_OFFSET + 1) + 1, first byte is READY BYTE
return frame;
}
public void WakeUp()
{
// not needed (pn532um.pdf, pag. 100)
}
#endregion
void irq_OnInterrupt(uint data1, uint data2, DateTime time)
{
this.whIrq.Set();
}
/// <summary>
/// Read ACK/NACK frame fromPN532
/// </summary>
/// <returns>ACK/NACK frame</returns>
private byte[] ReadAcknowledge()
{
byte[] read = new byte[PN532.ACK_PACKET_SIZE + 1]; // + 1, first byte is READY BYTE
// using IRQ enabled
if (this.irq != null)
{
// wait for IRQ from PN532 if enabled
if (!this.whIrq.WaitOne(PN532.PN532_READY_TIMEOUT, false))
return null;
this.I2CRead(read);
}
else
{
long start = DateTime.Now.Ticks;
// waiting for status ready
while (read[0] != PN532.PN532_READY)
{
this.I2CRead(read);
// check timeout
if ((DateTime.Now.Ticks - start) / PN532.TICKS_PER_MILLISECONDS < PN532.PN532_READY_TIMEOUT)
Thread.Sleep(10);
else
return null;
}
}
return new byte[] { read[3 + 1], read[4 + 1] }; // + 1, first byte is READY BYTE
}
/// <summary>
/// Execute an I2C read transaction
/// </summary>
/// <param name="data">Output buffer with bytes read</param>
/// <returns>Number of bytes read</returns>
private int I2CRead(byte[] data)
{
// create a I2C read transaction
I2CDevice.I2CTransaction[] i2cTx = new I2CDevice.I2CTransaction[1];
i2cTx[0] = I2CDevice.CreateReadTransaction(data);
// receive data from PN532
int read = this.i2c.Execute(i2cTx, PN532_I2C_TIMEOUT);
// make sure the data was received.
if (read != data.Length)
throw new Exception("Error executing I2C reading from PN532");
return read;
}
/// <summary>
/// Execute an I2C write transaction
/// </summary>
/// <param name="data">Input buffer with bytes to write</param>
/// <returns>Number of bytes written</returns>
private int I2CWrite(byte[] data)
{
// create a I2C write transaction
I2CDevice.I2CTransaction[] i2cTx = new I2CDevice.I2CTransaction[1];
i2cTx[0] = I2CDevice.CreateWriteTransaction(data);
// write data to PN532
int write = this.i2c.Execute(i2cTx, PN532_I2C_TIMEOUT);
// make sure the data was sent.
if (write != data.Length)
throw new Exception("Error executing I2C writing from PN532");
return write;
}
}
}
| |
//
// 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.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation credentials. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
internal partial class CredentialOperations : IServiceOperations<AutomationManagementClient>, ICredentialOperations
{
/// <summary>
/// Initializes a new instance of the CredentialOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal CredentialOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a credential. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create or update
/// credential operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the create or update credential operation.
/// </returns>
public async Task<CredentialCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string automationAccount, CredentialCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.Password == null)
{
throw new ArgumentNullException("parameters.Properties.Password");
}
if (parameters.Properties.UserName == null)
{
throw new ArgumentNullException("parameters.Properties.UserName");
}
// 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("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/credentials/";
url = url + Uri.EscapeDataString(parameters.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
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
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject credentialCreateOrUpdateParametersValue = new JObject();
requestDoc = credentialCreateOrUpdateParametersValue;
credentialCreateOrUpdateParametersValue["name"] = parameters.Name;
JObject propertiesValue = new JObject();
credentialCreateOrUpdateParametersValue["properties"] = propertiesValue;
propertiesValue["userName"] = parameters.Properties.UserName;
propertiesValue["password"] = parameters.Properties.Password;
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
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
CredentialCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CredentialCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Credential credentialInstance = new Credential();
result.Credential = credentialInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
credentialInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
credentialInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
CredentialProperties propertiesInstance = new CredentialProperties();
credentialInstance.Properties = propertiesInstance;
JToken userNameValue = propertiesValue2["userName"];
if (userNameValue != null && userNameValue.Type != JTokenType.Null)
{
string userNameInstance = ((string)userNameValue);
propertiesInstance.UserName = userNameInstance;
}
JToken creationTimeValue = propertiesValue2["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue2["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
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>
/// Delete the credential. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='credentialName'>
/// Required. The name of credential.
/// </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> DeleteAsync(string resourceGroupName, string automationAccount, string credentialName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (credentialName == null)
{
throw new ArgumentNullException("credentialName");
}
// 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("automationAccount", automationAccount);
tracingParameters.Add("credentialName", credentialName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/credentials/";
url = url + Uri.EscapeDataString(credentialName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
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.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// 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
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>
/// Retrieve the credential identified by credential name. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='credentialName'>
/// Required. The name of credential.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get credential operation.
/// </returns>
public async Task<CredentialGetResponse> GetAsync(string resourceGroupName, string automationAccount, string credentialName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (credentialName == null)
{
throw new ArgumentNullException("credentialName");
}
// 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("automationAccount", automationAccount);
tracingParameters.Add("credentialName", credentialName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/credentials/";
url = url + Uri.EscapeDataString(credentialName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
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
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// 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
CredentialGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CredentialGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Credential credentialInstance = new Credential();
result.Credential = credentialInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
credentialInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
credentialInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
CredentialProperties propertiesInstance = new CredentialProperties();
credentialInstance.Properties = propertiesInstance;
JToken userNameValue = propertiesValue["userName"];
if (userNameValue != null && userNameValue.Type != JTokenType.Null)
{
string userNameInstance = ((string)userNameValue);
propertiesInstance.UserName = userNameInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
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>
/// Retrieve a list of credentials. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list credential operation.
/// </returns>
public async Task<CredentialListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// 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("automationAccount", automationAccount);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/credentials";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
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
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// 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
CredentialListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CredentialListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Credential credentialInstance = new Credential();
result.Credentials.Add(credentialInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
credentialInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
credentialInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
CredentialProperties propertiesInstance = new CredentialProperties();
credentialInstance.Properties = propertiesInstance;
JToken userNameValue = propertiesValue["userName"];
if (userNameValue != null && userNameValue.Type != JTokenType.Null)
{
string userNameInstance = ((string)userNameValue);
propertiesInstance.UserName = userNameInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
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>
/// Retrieve next list of credentials. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list credential operation.
/// </returns>
public async Task<CredentialListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
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
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// 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
CredentialListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CredentialListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Credential credentialInstance = new Credential();
result.Credentials.Add(credentialInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
credentialInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
credentialInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
CredentialProperties propertiesInstance = new CredentialProperties();
credentialInstance.Properties = propertiesInstance;
JToken userNameValue = propertiesValue["userName"];
if (userNameValue != null && userNameValue.Type != JTokenType.Null)
{
string userNameInstance = ((string)userNameValue);
propertiesInstance.UserName = userNameInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
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>
/// Update a credential. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the patch credential operation.
/// </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> PatchAsync(string resourceGroupName, string automationAccount, CredentialPatchParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
// 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("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/credentials/";
url = url + Uri.EscapeDataString(parameters.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
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 = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject credentialPatchParametersValue = new JObject();
requestDoc = credentialPatchParametersValue;
credentialPatchParametersValue["name"] = parameters.Name;
if (parameters.Properties != null)
{
JObject propertiesValue = new JObject();
credentialPatchParametersValue["properties"] = propertiesValue;
if (parameters.Properties.UserName != null)
{
propertiesValue["userName"] = parameters.Properties.UserName;
}
if (parameters.Properties.Password != null)
{
propertiesValue["password"] = parameters.Properties.Password;
}
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
}
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)
{
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();
}
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D07Level1111ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="D07Level1111ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D06Level111"/> collection.
/// </remarks>
[Serializable]
public partial class D07Level1111ReChild : BusinessBase<D07Level1111ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_Child_Name, "Level_1_1_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1_1_1 Child Name.</value>
public string Level_1_1_1_1_Child_Name
{
get { return GetProperty(Level_1_1_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_1_1_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D07Level1111ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D07Level1111ReChild"/> object.</returns>
internal static D07Level1111ReChild NewD07Level1111ReChild()
{
return DataPortal.CreateChild<D07Level1111ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="D07Level1111ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="cLarentID2">The CLarentID2 parameter of the D07Level1111ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="D07Level1111ReChild"/> object.</returns>
internal static D07Level1111ReChild GetD07Level1111ReChild(int cLarentID2)
{
return DataPortal.FetchChild<D07Level1111ReChild>(cLarentID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D07Level1111ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private D07Level1111ReChild()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D07Level1111ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D07Level1111ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="cLarentID2">The CLarent ID2.</param>
protected void Child_Fetch(int cLarentID2)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetD07Level1111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CLarentID2", cLarentID2).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, cLarentID2);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
BusinessRules.CheckRules();
}
}
/// <summary>
/// Loads a <see cref="D07Level1111ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D07Level1111ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D06Level111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddD07Level1111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D07Level1111ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(D06Level111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateD07Level1111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="D07Level1111ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(D06Level111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteD07Level1111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Gallio.Common.Collections;
using Gallio.Runtime.Extensibility;
namespace Gallio.Runtime.FileTypes
{
/// <summary>
/// A built-in file type manager that identified file types based on a
/// set of registered <see cref="IFileTypeRecognizer" /> components.
/// </summary>
public class FileTypeManager : IFileTypeManager
{
private readonly FileType unknownFileType;
private readonly List<FileType> fileTypes;
private readonly Dictionary<string, FileTypeInfo> fileTypeInfos;
private readonly List<FileTypeInfo> rootFileTypeInfos;
/// <summary>
/// Creates a file type manager.
/// </summary>
/// <param name="fileTypeRecognizerHandles">The file type recognizer component handles.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="fileTypeRecognizerHandles"/> is null.</exception>
public FileTypeManager(ComponentHandle<IFileTypeRecognizer, FileTypeRecognizerTraits>[] fileTypeRecognizerHandles)
{
if (fileTypeRecognizerHandles == null || Array.IndexOf(fileTypeRecognizerHandles, null) >= 0)
throw new ArgumentNullException("fileTypeRecognizerHandles");
unknownFileType = new FileType("Unknown", "File of unknown type.", null);
fileTypes = new List<FileType>();
fileTypeInfos = new Dictionary<string, FileTypeInfo>();
rootFileTypeInfos = new List<FileTypeInfo>();
Initialize(fileTypeRecognizerHandles);
// Note: The unknown type is not reachable from the roots so we pay no cost
// trying to apply a recognizer to it. We add it to the other tables for
// lookup and enumeration only.
fileTypes.Add(unknownFileType);
fileTypeInfos.Add(unknownFileType.Id, new FileTypeInfo()
{
FileType = unknownFileType
});
}
/// <inheritdoc />
public FileType UnknownFileType
{
get { return unknownFileType; }
}
/// <inheritdoc />
public FileType GetFileTypeById(string id)
{
if (id == null)
throw new ArgumentNullException("id");
FileTypeInfo fileTypeInfo;
if (fileTypeInfos.TryGetValue(id, out fileTypeInfo))
return fileTypeInfo.FileType;
return null;
}
/// <inheritdoc />
public IList<FileType> GetFileTypes()
{
return new ReadOnlyCollection<FileType>(fileTypes);
}
/// <inheritdoc />
public FileType IdentifyFileType(FileInfo fileInfo)
{
if (fileInfo == null)
throw new ArgumentNullException("fileInfo");
using (var fileInspector = new LazyFileInspector(fileInfo))
return IdentifyFileTypeImpl(fileInspector, null);
}
/// <inheritdoc />
public FileType IdentifyFileType(IFileInspector fileInspector)
{
if (fileInspector == null)
throw new ArgumentNullException("fileInspector");
return IdentifyFileTypeImpl(fileInspector, null);
}
/// <inheritdoc />
public FileType IdentifyFileType(FileInfo fileInfo, IEnumerable<FileType> candidates)
{
if (fileInfo == null)
throw new ArgumentNullException("fileInfo");
if (candidates == null)
throw new ArgumentNullException("candidates");
using (var fileInspector = new LazyFileInspector(fileInfo))
return IdentifyFileTypeImpl(fileInspector, candidates);
}
/// <inheritdoc />
public FileType IdentifyFileType(IFileInspector fileInspector, IEnumerable<FileType> candidates)
{
if (fileInspector == null)
throw new ArgumentNullException("fileInspector");
if (candidates == null)
throw new ArgumentNullException("candidates");
return IdentifyFileTypeImpl(fileInspector, candidates);
}
private FileType IdentifyFileTypeImpl(IFileInspector fileInspector, IEnumerable<FileType> candidates)
{
Dictionary<FileType, bool> fileTypeFilter = CreateFileTypeFilter(candidates);
FileType fileType = IdentifyFileTypeRecursive(fileInspector, fileTypeFilter, rootFileTypeInfos);
if (fileType == null)
fileType = unknownFileType;
return fileType;
}
private static Dictionary<FileType, bool> CreateFileTypeFilter(IEnumerable<FileType> candidates)
{
if (candidates == null)
return null;
Dictionary<FileType, bool> fileTypeFilter = new Dictionary<FileType, bool>();
foreach (FileType fileType in candidates)
AddFileTypeToFilter(fileTypeFilter, fileType, true);
return fileTypeFilter;
}
private static void AddFileTypeToFilter(Dictionary<FileType, bool> fileTypeFilter, FileType fileType, bool isExplicitCandidate)
{
if (!isExplicitCandidate && fileTypeFilter.ContainsKey(fileType))
return;
fileTypeFilter[fileType] = isExplicitCandidate;
if (fileType.SuperType != null)
AddFileTypeToFilter(fileTypeFilter, fileType.SuperType, false);
}
private static FileType IdentifyFileTypeRecursive(IFileInspector fileInspector, Dictionary<FileType, bool> fileTypeFilter,
IEnumerable<FileTypeInfo> fileTypeInfos)
{
foreach (var fileTypeInfo in fileTypeInfos)
{
bool isExplicitCandidate;
if (fileTypeFilter != null)
{
if (! fileTypeFilter.TryGetValue(fileTypeInfo.FileType, out isExplicitCandidate))
continue; // ignore if not in filter
}
else
{
isExplicitCandidate = true;
}
if (fileTypeInfo.IsRecognizedFile(fileInspector))
{
FileType subtype = IdentifyFileTypeRecursive(fileInspector, fileTypeFilter, fileTypeInfo.Subtypes);
if (subtype != null)
return subtype;
if (isExplicitCandidate)
return fileTypeInfo.FileType;
}
}
return null;
}
private void Initialize(IEnumerable<ComponentHandle<IFileTypeRecognizer, FileTypeRecognizerTraits>> fileTypeRecognizerHandles)
{
foreach (var handle in fileTypeRecognizerHandles)
{
string id = handle.GetTraits().Id;
if (fileTypeInfos.ContainsKey(id))
throw new InvalidOperationException(string.Format("There appear to be multiple file types registered with id '{0}'.", id));
fileTypeInfos.Add(id, new FileTypeInfo() { RecognizerHandle = handle });
}
foreach (var fileTypeInfo in fileTypeInfos.Values)
{
FileTypeRecognizerTraits recognizerTraits = fileTypeInfo.RecognizerHandle.GetTraits();
if (recognizerTraits.FileNameRegex != null)
fileTypeInfo.FileNameRegex = new Regex(recognizerTraits.FileNameRegex, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
if (recognizerTraits.ContentsRegex != null)
fileTypeInfo.ContentsRegex = new Regex(recognizerTraits.ContentsRegex, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
string superTypeId = recognizerTraits.SuperTypeId;
if (superTypeId != null)
{
FileTypeInfo superTypeInfo;
if (!fileTypeInfos.TryGetValue(superTypeId, out superTypeInfo))
throw new InvalidOperationException(string.Format("File type '{0}' refers to super type '{1}' but the super type is not registered.", recognizerTraits.Id, superTypeId));
if (fileTypeInfo.IsSameOrSubtype(superTypeInfo))
throw new InvalidOperationException(string.Format("File type '{0}' contains a circular reference to super type '{1}'.", recognizerTraits.Id, superTypeId));
superTypeInfo.AddSubtype(fileTypeInfo);
}
else
{
rootFileTypeInfos.Add(fileTypeInfo);
}
}
GenerateFileTypes(rootFileTypeInfos, null);
}
private void GenerateFileTypes(IEnumerable<FileTypeInfo> fileTypeInfos, FileType superType)
{
foreach (var fileTypeInfo in fileTypeInfos)
{
FileTypeRecognizerTraits recognizerTraits = fileTypeInfo.RecognizerHandle.GetTraits();
FileType fileType = new FileType(recognizerTraits.Id, recognizerTraits.Description, superType);
fileTypes.Add(fileType);
fileTypeInfo.FileType = fileType;
GenerateFileTypes(fileTypeInfo.Subtypes, fileType);
}
}
private sealed class FileTypeInfo
{
private List<FileTypeInfo> subtypes;
public ComponentHandle<IFileTypeRecognizer, FileTypeRecognizerTraits> RecognizerHandle { get; set; }
public FileType FileType { get; set; }
public IList<FileTypeInfo> Subtypes
{
get { return subtypes ?? (IList<FileTypeInfo>) EmptyArray<FileTypeInfo>.Instance; }
}
public Regex FileNameRegex { get; set; }
public Regex ContentsRegex { get; set; }
public void AddSubtype(FileTypeInfo subtype)
{
if (subtypes == null)
subtypes = new List<FileTypeInfo>();
subtypes.Add(subtype);
}
public bool IsRecognizedFile(IFileInspector fileInspector)
{
if (FileNameRegex != null)
{
FileInfo fileInfo;
if (!fileInspector.TryGetFileInfo(out fileInfo))
return false;
if (! FileNameRegex.IsMatch(fileInfo.Name))
return false;
}
if (ContentsRegex != null)
{
string contents;
if (!fileInspector.TryGetContents(out contents))
return false;
if (! ContentsRegex.IsMatch(contents))
return false;
}
IFileTypeRecognizer fileTypeRecognizer = RecognizerHandle.GetComponent();
return fileTypeRecognizer.IsRecognizedFile(fileInspector);
}
public bool IsSameOrSubtype(FileTypeInfo possibleSubtype)
{
if (this == possibleSubtype)
return true;
if (subtypes != null)
{
foreach (FileTypeInfo subtype in Subtypes)
{
if (subtype.IsSameOrSubtype(possibleSubtype))
return true;
}
}
return false;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
namespace RootMotion.FinalIK {
/// <summary>
/// Rotates a hierarchy of bones to face a target.
/// </summary>
[System.Serializable]
public class IKSolverLookAt : IKSolver {
#region Main Interface
/// <summary>
/// The target Transform.
/// </summary>
public Transform target;
/// <summary>
/// The spine hierarchy.
/// </summary>
public LookAtBone[] spine = new LookAtBone[0];
/// <summary>
/// The head bone.
/// </summary>
public LookAtBone head = new LookAtBone();
/// <summary>
/// The eye bones.
/// </summary>
public LookAtBone[] eyes = new LookAtBone[0];
/// <summary>
/// The body weight.
/// </summary>
[Range(0f, 1f)]
public float bodyWeight = 0.5f;
/// <summary>
/// The head weight.
/// </summary>
[Range(0f, 1f)]
public float headWeight = 0.5f;
/// <summary>
/// The eyes weight.
/// </summary>
[Range(0f, 1f)]
public float eyesWeight = 1f;
/// <summary>
/// Clamp weight for the body.
/// </summary>
[Range(0f, 1f)]
public float clampWeight = 0.5f;
/// <summary>
/// Clamp weight for the head.
/// </summary>
[Range(0f, 1f)]
public float clampWeightHead = 0.5f;
/// <summary>
/// Clamp weight for the eyes.
/// </summary>
[Range(0f, 1f)]
public float clampWeightEyes = 0.5f;
/// <summary>
/// Number of sine smoothing iterations applied on clamping to make the clamping point smoother.
/// </summary>
[Range(0, 2)]
public int clampSmoothing = 2;
/// <summary>
/// Weight distribution between the spine bones.
/// </summary>
public AnimationCurve spineWeightCurve = new AnimationCurve(new Keyframe[2] { new Keyframe(0f, 0.3f), new Keyframe(1f, 1f) });
/// <summary>
/// Sets the look at weight. NOTE: You are welcome edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight, float headWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
this.eyesWeight = Mathf.Clamp(eyesWeight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight, float clampWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
this.eyesWeight = Mathf.Clamp(eyesWeight, 0f, 1f);
this.clampWeight = Mathf.Clamp(clampWeight, 0f, 1f);
this.clampWeightHead = this.clampWeight;
this.clampWeightEyes = this.clampWeight;
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight = 0f, float headWeight = 1f, float eyesWeight = 0.5f, float clampWeight = 0.5f, float clampWeightHead = 0.5f, float clampWeightEyes = 0.3f) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
this.eyesWeight = Mathf.Clamp(eyesWeight, 0f, 1f);
this.clampWeight = Mathf.Clamp(clampWeight, 0f, 1f);
this.clampWeightHead = Mathf.Clamp(clampWeightHead, 0f, 1f);
this.clampWeightEyes = Mathf.Clamp(clampWeightEyes, 0f, 1f);
}
public override void StoreDefaultLocalState() {
for (int i = 0; i < spine.Length; i++) spine[i].StoreDefaultLocalState();
for (int i = 0; i < eyes.Length; i++) eyes[i].StoreDefaultLocalState();
if (head != null && head.transform != null) head.StoreDefaultLocalState();
}
public override void FixTransforms() {
if (IKPositionWeight <= 0f) return;
for (int i = 0; i < spine.Length; i++) spine[i].FixTransform();
for (int i = 0; i < eyes.Length; i++) eyes[i].FixTransform();
if (head != null && head.transform != null) head.FixTransform();
}
public override bool IsValid (ref string message) {
if (!spineIsValid) {
message = "IKSolverLookAt spine setup is invalid. Can't initiate solver.";
return false;
}
if (!headIsValid) {
message = "IKSolverLookAt head transform is null. Can't initiate solver.";
return false;
}
if (!eyesIsValid) {
message = "IKSolverLookAt eyes setup is invalid. Can't initiate solver.";
return false;
}
if (spineIsEmpty && headIsEmpty && eyesIsEmpty) {
message = "IKSolverLookAt eyes setup is invalid. Can't initiate solver.";
return false;
}
Transform spineDuplicate = ContainsDuplicateBone(spine);
if (spineDuplicate != null) {
message = spineDuplicate.name + " is represented multiple times in a single IK chain. Can't initiate solver.";
return false;
}
Transform eyeDuplicate = ContainsDuplicateBone(eyes);
if (eyeDuplicate != null) {
message = eyeDuplicate.name + " is represented multiple times in a single IK chain. Can't initiate solver.";
return false;
}
return true;
}
public override IKSolver.Point[] GetPoints() {
IKSolver.Point[] allPoints = new IKSolver.Point[spine.Length + eyes.Length + (head.transform != null? 1: 0)];
for (int i = 0; i < spine.Length; i++) allPoints[i] = spine[i] as IKSolver.Point;
int eye = 0;
for (int i = spine.Length; i < allPoints.Length; i++) {
allPoints[i] = eyes[eye] as IKSolver.Point;
eye ++;
}
if (head.transform != null) allPoints[allPoints.Length - 1] = head as IKSolver.Point;
return allPoints;
}
public override IKSolver.Point GetPoint(Transform transform) {
foreach (IKSolverLookAt.LookAtBone b in spine) if (b.transform == transform) return b as IKSolver.Point;
foreach (IKSolverLookAt.LookAtBone b in eyes) if (b.transform == transform) return b as IKSolver.Point;
if (head.transform == transform) return head as IKSolver.Point;
return null;
}
/// <summary>
/// Look At bone class.
/// </summary>
[System.Serializable]
public class LookAtBone: IKSolver.Bone {
#region Public methods
public LookAtBone() {}
/*
* Custom constructor
* */
public LookAtBone(Transform transform) {
this.transform = transform;
}
/*
* Initiates the bone, precalculates values.
* */
public void Initiate(Transform root) {
if (transform == null) return;
axis = Quaternion.Inverse(transform.rotation) * root.forward;
}
/*
* Rotates the bone to look at a world direction.
* */
public void LookAt(Vector3 direction, float weight) {
Quaternion fromTo = Quaternion.FromToRotation(forward, direction);
Quaternion r = transform.rotation;
transform.rotation = Quaternion.Lerp(r, fromTo * r, weight);
}
/*
* Gets the local axis to goal in world space.
* */
public Vector3 forward {
get {
return transform.rotation * axis;
}
}
#endregion Public methods
}
/// <summary>
/// Reinitiate the solver with new bone Transforms.
/// </summary>
/// <returns>
/// Returns true if the new chain is valid.
/// </returns>
public bool SetChain(Transform[] spine, Transform head, Transform[] eyes, Transform root) {
// Spine
SetBones(spine, ref this.spine);
// Head
this.head = new LookAtBone(head);
// Eyes
SetBones(eyes, ref this.eyes);
Initiate(root);
return initiated;
}
#endregion Main Interface
private Vector3[] spineForwards = new Vector3[0];
private Vector3[] headForwards = new Vector3[1];
private Vector3[] eyeForward = new Vector3[1];
protected override void OnInitiate() {
// Set IKPosition to default value
if (firstInitiation || !Application.isPlaying) {
if (spine.Length > 0) IKPosition = spine[spine.Length - 1].transform.position + root.forward * 3f;
else if (head.transform != null) IKPosition = head.transform.position + root.forward * 3f;
else if (eyes.Length > 0 && eyes[0].transform != null) IKPosition = eyes[0].transform.position + root.forward * 3f;
}
// Initiating the bones
foreach (LookAtBone s in spine) s.Initiate(root);
if (head != null) head.Initiate(root);
foreach (LookAtBone eye in eyes) eye.Initiate(root);
if (spineForwards == null || spineForwards.Length != spine.Length) spineForwards = new Vector3[spine.Length];
if (headForwards == null) headForwards = new Vector3[1];
if (eyeForward == null) eyeForward = new Vector3[1];
}
protected override void OnUpdate() {
if (IKPositionWeight <= 0) return;
IKPositionWeight = Mathf.Clamp(IKPositionWeight, 0f, 1f);
if (target != null) IKPosition = target.position;
// Solving the hierarchies
SolveSpine();
SolveHead();
SolveEyes();
}
private bool spineIsValid {
get {
if (spine == null) return false;
if (spine.Length == 0) return true;
for (int i = 0; i < spine.Length; i++) if (spine[i] == null || spine[i].transform == null) return false;
return true;
}
}
private bool spineIsEmpty { get { return spine.Length == 0; }}
// Solving the spine hierarchy
private void SolveSpine() {
if (bodyWeight <= 0) return;
if (spineIsEmpty) return;
// Get the look at vectors for each bone
//Vector3 targetForward = Vector3.Lerp(spine[0].forward, (IKPosition - spine[spine.Length - 1].transform.position).normalized, bodyWeight * IKPositionWeight).normalized;
Vector3 targetForward = (IKPosition - spine[spine.Length - 1].transform.position).normalized;
GetForwards(ref spineForwards, spine[0].forward, targetForward, spine.Length, clampWeight);
// Rotate each bone to face their look at vectors
for (int i = 0; i < spine.Length; i++) {
spine[i].LookAt(spineForwards[i], bodyWeight * IKPositionWeight);
}
}
private bool headIsValid {
get {
if (head == null) return false;
return true;
}
}
private bool headIsEmpty { get { return head.transform == null; }}
// Solving the head rotation
private void SolveHead() {
if (headWeight <= 0) return;
if (headIsEmpty) return;
// Get the look at vector for the head
Vector3 baseForward = spine.Length > 0 && spine[spine.Length - 1].transform != null? spine[spine.Length - 1].forward: head.forward;
Vector3 targetForward = Vector3.Lerp(baseForward, (IKPosition - head.transform.position).normalized, headWeight * IKPositionWeight).normalized;
GetForwards(ref headForwards, baseForward, targetForward, 1, clampWeightHead);
// Rotate the head to face its look at vector
head.LookAt(headForwards[0], headWeight * IKPositionWeight);
}
private bool eyesIsValid {
get {
if (eyes == null) return false;
if (eyes.Length == 0) return true;
for (int i = 0; i < eyes.Length; i++) if (eyes[i] == null || eyes[i].transform == null) return false;
return true;
}
}
private bool eyesIsEmpty { get { return eyes.Length == 0; }}
// Solving the eye rotations
private void SolveEyes() {
if (eyesWeight <= 0) return;
if (eyesIsEmpty) return;
for (int i = 0; i < eyes.Length; i++) {
// Get the look at vector for the eye
Vector3 baseForward = head.transform != null? head.forward: eyes[i].forward;
GetForwards(ref eyeForward, baseForward, (IKPosition - eyes[i].transform.position).normalized, 1, clampWeightEyes);
// Rotate the eye to face its look at vector
eyes[i].LookAt(eyeForward[0], eyesWeight * IKPositionWeight);
}
}
/*
* Returns forwards for a number of bones rotating from baseForward to targetForward.
* NB! Make sure baseForward and targetForward are normalized.
* */
private Vector3[] GetForwards(ref Vector3[] forwards, Vector3 baseForward, Vector3 targetForward, int bones, float clamp) {
// If clamp >= 1 make all the forwards match the base
if (clamp >= 1 || IKPositionWeight <= 0) {
for (int i = 0; i < forwards.Length; i++) forwards[i] = baseForward;
return forwards;
}
// Get normalized dot product.
float angle = Vector3.Angle(baseForward, targetForward);
float dot = 1f - (angle / 180f);
// Clamping the targetForward so it doesn't exceed clamp
float targetClampMlp = clamp > 0? Mathf.Clamp(1f - ((clamp - dot) / (1f - dot)), 0f, 1f): 1f;
// Calculating the clamp multiplier
float clampMlp = clamp > 0? Mathf.Clamp(dot / clamp, 0f, 1f): 1f;
for (int i = 0; i < clampSmoothing; i++) {
float sinF = clampMlp * Mathf.PI * 0.5f;
clampMlp = Mathf.Sin(sinF);
}
// Rotation amount for 1 bone
if (forwards.Length == 1) {
forwards[0] = Vector3.Slerp(baseForward, targetForward, clampMlp * targetClampMlp);
} else {
float step = 1f / (float)(forwards.Length - 1);
// Calculate the forward for each bone
for (int i = 0; i < forwards.Length; i++) {
forwards[i] = Vector3.Slerp(baseForward, targetForward, spineWeightCurve.Evaluate(step * i) * clampMlp * targetClampMlp);
}
}
return forwards;
}
/*
* Build LookAtBone[] array of a Transform array
* */
private void SetBones(Transform[] array, ref LookAtBone[] bones) {
if (array == null) {
bones = new LookAtBone[0];
return;
}
if (bones.Length != array.Length) bones = new LookAtBone[array.Length];
for (int i = 0; i < array.Length; i++) {
if (bones[i] == null) bones[i] = new LookAtBone(array[i]);
else bones[i].transform = array[i];
}
}
}
}
| |
// <copyright file="BitwiseExtensions.cs" company="LeetABit">
// Copyright (c) Hubert Bukowski. All rights reserved.
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace LeetABit.Binary
{
using System;
using System.Runtime.CompilerServices;
using LeetABit.Binary.Properties;
/// <summary>
/// Provides extension methods for bitwise types like <see cref="Span{T}"/>, <see cref="ReadOnlySpan{T}"/>,
/// <see cref="BitSpan"/>, <see cref="ReadOnlyBitSpan"/>, <see cref="IBitBlock"/> and <see cref="IReadOnlyBitBlock"/>.
/// </summary>
public static class BitwiseExtensions
{
/// <summary>
/// Forms a slice out of the current bit span that begins at a specified bit index.
/// </summary>
/// <param name="span">
/// An instance of the <see cref="BitSpan"/> to slice.
/// </param>
/// <param name="startBitIndex">
/// The bit index at which to begin the slice.
/// </param>
/// <returns>
/// A bit span that consists of all bits of the current bit span from <paramref name="startBitIndex"/> to the end of the bit span.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="startBitIndex"/> is less than zero.
/// <para>-or-</para>
/// <paramref name="startBitIndex"/> is greater than the available span size.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static BitSpan Slice(this BitSpan span, int startBitIndex)
{
_ = Requires.ArgumentGreaterThanOrEqualsZero(startBitIndex, nameof(startBitIndex));
_ = Requires.ArgumentLessThanOrEquals(startBitIndex, span.Length, nameof(startBitIndex), Resources.Exception_ArgumentOutOfRange_BitIndexOutsideOfBitsSpan);
return span.Slice(startBitIndex, span.Length - startBitIndex);
}
/// <summary>
/// Forms a slice out of the current bit span that begins at a specified bit index.
/// </summary>
/// <param name="span">
/// An instance of the <see cref="ReadOnlyBitSpan"/> to slice.
/// </param>
/// <param name="startBitIndex">
/// The bit index at which to begin the slice.
/// </param>
/// <returns>
/// A bit span that consists of all bits of the current bit span from <paramref name="startBitIndex"/> to the end of the bit span.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="startBitIndex"/> is less than zero.
/// <para>-or-</para>
/// <paramref name="startBitIndex"/> is greater than the available span size.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBitSpan Slice(this ReadOnlyBitSpan span, int startBitIndex)
{
_ = Requires.ArgumentGreaterThanOrEqualsZero(startBitIndex, nameof(startBitIndex));
_ = Requires.ArgumentLessThanOrEquals(startBitIndex, span.Length, nameof(startBitIndex), Resources.Exception_ArgumentOutOfRange_BitIndexOutsideOfBitsSpan);
return span.Slice(startBitIndex, span.Length - startBitIndex);
}
/// <summary>
/// Forms a slice out of the specified bit block that begins at a specified bit index.
/// </summary>
/// <param name="block">
/// An instance of the <see cref="IBitBlock"/> to slice.
/// </param>
/// <param name="startBitIndex">
/// The bit index at which to begin the slice.
/// </param>
/// <returns>
/// A bit span that consists of all bits of the current bit span from <paramref name="startBitIndex"/> to the end of the bit span.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="block"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="startBitIndex"/> is less than zero.
/// <para>-or-</para>
/// <paramref name="startBitIndex"/> is greater than the available span size.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IBitBlock Slice(this IBitBlock block, int startBitIndex)
{
_ = Requires.ArgumentNotNull(block, nameof(block));
_ = Requires.ArgumentGreaterThanOrEqualsZero(startBitIndex, nameof(startBitIndex));
_ = Requires.ArgumentLessThanOrEquals(startBitIndex, block.Length, nameof(startBitIndex), Resources.Exception_ArgumentOutOfRange_BitIndexOutsideOfBitsSpan);
return block.Slice(startBitIndex, block.Length - startBitIndex);
}
/// <summary>
/// Forms a slice out of the specified bit block that begins at a specified bit index.
/// </summary>
/// <param name="block">
/// An instance of the <see cref="IBitBlock"/> to slice.
/// </param>
/// <param name="startBitIndex">
/// The bit index at which to begin the slice.
/// </param>
/// <returns>
/// A bit span that consists of all bits of the current bit span from <paramref name="startBitIndex"/> to the end of the bit span.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="block"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="startBitIndex"/> is less than zero.
/// <para>-or-</para>
/// <paramref name="startBitIndex"/> is greater than the available span size.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IReadOnlyBitBlock Slice(this IReadOnlyBitBlock block, int startBitIndex)
{
_ = Requires.ArgumentNotNull(block, nameof(block));
_ = Requires.ArgumentGreaterThanOrEqualsZero(startBitIndex, nameof(startBitIndex));
_ = Requires.ArgumentLessThanOrEquals(startBitIndex, block.Length, nameof(startBitIndex), Resources.Exception_ArgumentOutOfRange_BitIndexOutsideOfBitsSpan);
return block.Slice(startBitIndex, block.Length - startBitIndex);
}
/// <summary>
/// Copies all the bits of the specified bit span into a new byte array.
/// </summary>
/// <param name="span">
/// Bit span which bits shall be stored in the array.
/// </param>
/// <returns>
/// A newly created byte array containing all the bits in the specified span.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] ToArray(this BitSpan span)
{
if (span.Length == 0)
{
return Array.Empty<byte>();
}
var array = new byte[BitCalculations.GetElementCountNeeded<byte>(span.Length)];
var destination = new BitSpan(array, 0, span.Length, span.BitOrder);
_ = span.CopyBitsTo(destination);
return array;
}
/// <summary>
/// Copies all the bits of the specified bit span into a new byte array.
/// </summary>
/// <param name="span">
/// Bit span which bits shall be stored in the array.
/// </param>
/// <returns>
/// A newly created byte array containing all the bits in the specified span.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] ToArray(this ReadOnlyBitSpan span)
{
if (span.Length == 0)
{
return Array.Empty<byte>();
}
var array = new byte[BitCalculations.GetElementCountNeeded<byte>(span.Length)];
var destination = new BitSpan(array, 0, span.Length, span.BitOrder);
_ = span.CopyBitsTo(destination);
return array;
}
/// <summary>
/// Copies all the bits of the specified bit block into a new byte array.
/// </summary>
/// <param name="block">
/// Bit block which bits shall be stored in the array.
/// </param>
/// <returns>
/// A newly created byte array containing all the bits in the specified block.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="block"/> is <see langword="null"/>.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] ToArray(this IBitBlock block)
{
_ = Requires.ArgumentNotNull(block, nameof(block));
if (block.Length == 0)
{
return Array.Empty<byte>();
}
var array = new byte[BitCalculations.GetElementCountNeeded<byte>(block.Length)];
var destination = new BitSpan(array, 0, block.Length, block.BitOrder);
_ = block.CopyBitsTo(destination);
return array;
}
/// <summary>
/// Copies all the bits of the specified bit block into a new byte array.
/// </summary>
/// <param name="block">
/// Bit block which bits shall be stored in the array.
/// </param>
/// <returns>
/// A newly created byte array containing all the bits in the specified block.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="block"/> is <see langword="null"/>.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] ToArray(this IReadOnlyBitBlock block)
{
_ = Requires.ArgumentNotNull(block, nameof(block));
if (block.Length == 0)
{
return Array.Empty<byte>();
}
var array = new byte[BitCalculations.GetElementCountNeeded<byte>(block.Length)];
var destination = new BitSpan(array, 0, block.Length, block.BitOrder);
_ = block.CopyBitsTo(destination);
return array;
}
/// <summary>
/// Copies all bits from the specified source bit span to the destination if the destination is large enough to contain all the bits.
/// </summary>
/// <param name="source">
/// Bit span from which the bits shall be copied.
/// </param>
/// <param name="destination">
/// Destination span for copied bits.
/// </param>
/// <returns>
/// <see langword="true"/> if all the bits contained in the specified source bit span has been copied to the destination;
/// otherwise, <see langword="false"/> as an indication that there was no space avaialble in destination span and no bits were copied.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryCopyAllTo(this BitSpan source, BitSpan destination)
{
var result = false;
if (source.Length <= destination.Length)
{
_ = source.CopyBitsTo(destination);
result = true;
}
return result;
}
/// <summary>
/// Copies all bits from the specified source bit span to the destination if the destination is large enough to contain all the bits.
/// </summary>
/// <param name="source">
/// Bit span from which the bits shall be copied.
/// </param>
/// <param name="destination">
/// Destination span for copied bits.
/// </param>
/// <returns>
/// <see langword="true"/> if all the bits contained in the specified source bit span has been copied to the destination;
/// otherwise, <see langword="false"/> as an indication that there was no space avaialble in destination span and no bits were copied.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryCopyAllTo(this ReadOnlyBitSpan source, BitSpan destination)
{
var result = false;
if (source.Length <= destination.Length)
{
_ = source.CopyBitsTo(destination);
result = true;
}
return result;
}
/// <summary>
/// Copies all bits from the specified source bit block to the destination if the destination is large enough to contain all the bits.
/// </summary>
/// <param name="source">
/// Bit block from which the bits shall be copied.
/// </param>
/// <param name="destination">
/// Destination span for copied bits.
/// </param>
/// <returns>
/// <see langword="true"/> if all the bits contained in the specified source bit block has been copied to the destination;
/// otherwise, <see langword="false"/> as an indication that there was no space avaialble in destination span and no bits were copied.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> is <see langword="null"/>.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryCopyAllTo(this IBitBlock source, BitSpan destination)
{
_ = Requires.ArgumentNotNull(source, nameof(source));
var result = false;
if (source.Length <= destination.Length)
{
_ = source.CopyBitsTo(destination);
result = true;
}
return result;
}
/// <summary>
/// Copies all bits from the specified source bit block to the destination if the destination is large enough to contain all the bits.
/// </summary>
/// <param name="source">
/// Bit block from which the bits shall be copied.
/// </param>
/// <param name="destination">
/// Destination span for copied bits.
/// </param>
/// <returns>
/// <see langword="true"/> if all the bits contained in the specified source bit block has been copied to the destination;
/// otherwise, <see langword="false"/> as an indication that there was no space avaialble in destination span and no bits were copied.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> is <see langword="null"/>.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryCopyAllTo(this IReadOnlyBitBlock source, BitSpan destination)
{
_ = Requires.ArgumentNotNull(source, nameof(source));
var result = false;
if (source.Length <= destination.Length)
{
_ = source.CopyBitsTo(destination);
result = true;
}
return result;
}
/// <summary>
/// Copies all bits from the specified source bit span to the destination.
/// </summary>
/// <param name="source">
/// Bit span from which the bits shall be copied.
/// </param>
/// <param name="destination">
/// Destination span for copied bits.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="destination"/> is too short to contain all the bits stored in the specified source bit span.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CopyAllTo(this BitSpan source, BitSpan destination)
{
if (!source.TryCopyAllTo(destination))
{
throw new ArgumentException(Resources.Exception_Argument_DestinationBitSpanTooShort, nameof(destination));
}
}
/// <summary>
/// Copies all bits from the specified source bit span to the destination.
/// </summary>
/// <param name="source">
/// Bit span from which the bits shall be copied.
/// </param>
/// <param name="destination">
/// Destination span for copied bits.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="destination"/> is too short to contain all the bits stored in the specified source bit span.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CopyAllTo(this ReadOnlyBitSpan source, BitSpan destination)
{
if (!source.TryCopyAllTo(destination))
{
throw new ArgumentException(Resources.Exception_Argument_DestinationBitSpanTooShort, nameof(destination));
}
}
/// <summary>
/// Copies all bits from the specified source bit span to the destination.
/// </summary>
/// <param name="source">
/// Bit block from which the bits shall be copied.
/// </param>
/// <param name="destination">
/// Destination span for copied bits.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="destination"/> is too short to contain all the bits stored in the specified source bit block.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CopyAllTo(this IBitBlock source, BitSpan destination)
{
if (!source.TryCopyAllTo(destination))
{
throw new ArgumentException(Resources.Exception_Argument_DestinationBitSpanTooShort, nameof(destination));
}
}
/// <summary>
/// Copies all bits from the specified source bit span to the destination.
/// </summary>
/// <param name="source">
/// Bit block from which the bits shall be copied.
/// </param>
/// <param name="destination">
/// Destination span for copied bits.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="destination"/> is too short to contain all the bits stored in the specified source bit block.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CopyAllTo(this IReadOnlyBitBlock source, BitSpan destination)
{
if (!source.TryCopyAllTo(destination))
{
throw new ArgumentException(Resources.Exception_Argument_DestinationBitSpanTooShort, nameof(destination));
}
}
/// <summary>
/// Gets number of bits in the specified span.
/// </summary>
/// <typeparam name="T">
/// The type of items in the <paramref name="span"/>.
/// </typeparam>
/// <param name="span">
/// Span which length shall be measured.
/// </param>
/// <returns>
/// Number of bits in the specified span.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int GetBitLength<T>(this Span<T> span)
where T : struct
{
return span.Length << (BitCalculations.BitIndexBitSizeOf<T>() + 1);
}
/// <summary>
/// Gets number of bits in the specified read-only span.
/// </summary>
/// <typeparam name="T">
/// The type of items in the <paramref name="span"/>.
/// </typeparam>
/// <param name="span">
/// Span which length shall be measured.
/// </param>
/// <returns>
/// Number of bits in the specified read-only span.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int GetBitLength<T>(this ReadOnlySpan<T> span)
where T : struct
{
return span.Length << (BitCalculations.BitIndexBitSizeOf<T>() + 1);
}
/// <summary>
/// Gets number of bits in the specified memory.
/// </summary>
/// <typeparam name="T">
/// The type of items in the <paramref name="memory"/>.
/// </typeparam>
/// <param name="memory">
/// Memory which bit length shall be measured.
/// </param>
/// <returns>
/// Number of bits in the specified memory.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int GetBitLength<T>(this Memory<T> memory)
where T : struct
{
return memory.Length << (BitCalculations.BitIndexBitSizeOf<T>() + 1);
}
/// <summary>
/// Gets number of bits in the specified read-only memory.
/// </summary>
/// <typeparam name="T">
/// The type of items in the <paramref name="memory"/>.
/// </typeparam>
/// <param name="memory">
/// Memory which length shall be measured.
/// </param>
/// <returns>
/// Number of bits in the specified read-only memory.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int GetBitLength<T>(this ReadOnlyMemory<T> memory)
where T : struct
{
return memory.Length << (BitCalculations.BitIndexBitSizeOf<T>() + 1);
}
/// <summary>
/// Gets number of bits in the specified span starting from the specified bit index.
/// </summary>
/// <typeparam name="T">
/// The type of items in the <paramref name="span"/>.
/// </typeparam>
/// <param name="span">
/// Span which length shall be measured.
/// </param>
/// <param name="bitIndex">
/// Index of the first bit at which the calculation shall start.
/// </param>
/// <returns>
/// Length of the specified span starting from the specified bit index.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int GetBitLength<T>(this Span<T> span, int bitIndex)
where T : struct
{
return span.GetBitLength() - bitIndex;
}
/// <summary>
/// Gets number of bits in the specified read-only span starting from the specified bit index.
/// </summary>
/// <typeparam name="T">
/// The type of items in the <paramref name="span"/>.
/// </typeparam>
/// <param name="span">
/// Span which length shall be measured.
/// </param>
/// <param name="bitIndex">
/// Index of the first bit at which the calculation shall start.
/// </param>
/// <returns>
/// Length of the specified read-only span starting from the specified bit index.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int GetBitLength<T>(this ReadOnlySpan<T> span, int bitIndex)
where T : struct
{
return span.GetBitLength() - bitIndex;
}
/// <summary>
/// Gets number of bits in the specified memory starting from the specified bit index.
/// </summary>
/// <typeparam name="T">
/// The type of items in the <paramref name="memory"/>.
/// </typeparam>
/// <param name="memory">
/// Memory which bit length shall be measured.
/// </param>
/// <param name="bitIndex">
/// Index of the first bit at which the calculation shall start.
/// </param>
/// <returns>
/// Bit length of the specified memory starting from the specified bit index.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int GetBitLength<T>(this Memory<T> memory, int bitIndex)
where T : struct
{
return memory.GetBitLength() - bitIndex;
}
/// <summary>
/// Gets number of bits in the specified read-only memory starting from the specified bit index.
/// </summary>
/// <typeparam name="T">
/// The type of items in the <paramref name="memory"/>.
/// </typeparam>
/// <param name="memory">
/// Memory which length shall be measured.
/// </param>
/// <param name="bitIndex">
/// Index of the first bit at which the calculation shall start.
/// </param>
/// <returns>
/// Bit length of the specified read-only memory starting from the specified bit index.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int GetBitLength<T>(this ReadOnlyMemory<T> memory, int bitIndex)
where T : struct
{
return memory.GetBitLength() - bitIndex;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Crypto.Interfaces.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Javax.Crypto.Interfaces
{
/// <summary>
/// <para>The interface for a Diffie-Hellman key. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHKey", AccessFlags = 1537)]
public partial interface IDHKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the parameters for this key.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters for this key. </para>
/// </returns>
/// <java-name>
/// getParams
/// </java-name>
[Dot42.DexImport("getParams", "()Ljavax/crypto/spec/DHParameterSpec;", AccessFlags = 1025)]
global::Javax.Crypto.Spec.DHParameterSpec GetParams() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a public key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPublicKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IDHPublicKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = -6628103563352519193;
}
/// <summary>
/// <para>The interface for a public key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPublicKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPublicKey", AccessFlags = 1537)]
public partial interface IDHPublicKey : global::Javax.Crypto.Interfaces.IDHKey, global::Java.Security.IPublicKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns this key's public value Y. </para>
/// </summary>
/// <returns>
/// <para>this key's public value Y. </para>
/// </returns>
/// <java-name>
/// getY
/// </java-name>
[Dot42.DexImport("getY", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetY() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface to a <b>password-based-encryption</b> key. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/PBEKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/PBEKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IPBEKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = -1430015993304333921;
}
/// <summary>
/// <para>The interface to a <b>password-based-encryption</b> key. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/PBEKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/PBEKey", AccessFlags = 1537)]
public partial interface IPBEKey : global::Javax.Crypto.ISecretKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the iteration count, 0 if not specified.</para><para></para>
/// </summary>
/// <returns>
/// <para>the iteration count, 0 if not specified. </para>
/// </returns>
/// <java-name>
/// getIterationCount
/// </java-name>
[Dot42.DexImport("getIterationCount", "()I", AccessFlags = 1025)]
int GetIterationCount() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a copy of the salt data or null if not specified.</para><para></para>
/// </summary>
/// <returns>
/// <para>a copy of the salt data or null if not specified. </para>
/// </returns>
/// <java-name>
/// getSalt
/// </java-name>
[Dot42.DexImport("getSalt", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
byte[] GetSalt() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a copy to the password.</para><para></para>
/// </summary>
/// <returns>
/// <para>a copy to the password. </para>
/// </returns>
/// <java-name>
/// getPassword
/// </java-name>
[Dot42.DexImport("getPassword", "()[C", AccessFlags = 1025)]
char[] GetPassword() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a private key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPrivateKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IDHPrivateKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serialization version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = 2211791113380396553;
}
/// <summary>
/// <para>The interface for a private key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPrivateKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPrivateKey", AccessFlags = 1537)]
public partial interface IDHPrivateKey : global::Javax.Crypto.Interfaces.IDHKey, global::Java.Security.IPrivateKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns this key's private value x. </para>
/// </summary>
/// <returns>
/// <para>this key's private value x. </para>
/// </returns>
/// <java-name>
/// getX
/// </java-name>
[Dot42.DexImport("getX", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetX() /* MethodBuilder.Create */ ;
}
}
| |
#region Copyright (c) 2004 Ian Davis and James Carlyle
/*------------------------------------------------------------------------------
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 2004 Ian Davis and James Carlyle
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
namespace SemPlan.Spiral.Tests.Core {
using NUnit.Framework;
using SemPlan.Spiral.Core;
using SemPlan.Spiral.Expressions;
using SemPlan.Spiral.Utility;
using System;
using System.Collections;
/// <summary>
/// Programmer tests for Query class
/// </summary>
/// <remarks>
/// $Id: QueryTest.cs,v 1.6 2006/02/16 15:25:24 ian Exp $
///</remarks>
[TestFixture]
public class QueryTest {
[Test]
public void EqualsComparesSelectAll() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.SelectAll = false;
query2.SelectAll = false;
query3.SelectAll = true;
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesSelectAll() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.SelectAll = false;
query2.SelectAll = false;
query3.SelectAll = true;
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query3" );
}
[Test]
public void EqualsComparesPatterns() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query2.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query3.AddPattern( new Pattern( new UriRef("http://example.com/other"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesPatterns() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query2.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query3.AddPattern( new Pattern( new UriRef("http://example.com/other"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query2" );
}
[Test]
public void EqualsComparesQueryGroup() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.QueryGroup = new QueryGroupOr();
query2.QueryGroup = new QueryGroupOr();
query3.QueryGroup = new QueryGroupAnd();
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesQueryGroup() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.QueryGroup = new QueryGroupOr();
query2.QueryGroup = new QueryGroupOr();
query3.QueryGroup = new QueryGroupAnd();
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query2" );
}
[Test]
public void EqualsComparesPatternCount() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query2.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query3.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query3.AddPattern( new Pattern( new UriRef("http://example.com/other"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void EqualsComparesOptionalGroup() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.PatternGroup.OptionalGroup.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query2.PatternGroup.OptionalGroup.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query3.PatternGroup.OptionalGroup.AddPattern( new Pattern( new UriRef("http://example.com/other"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesOptionalGroup() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.PatternGroup.OptionalGroup.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query2.PatternGroup.OptionalGroup.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query3.PatternGroup.OptionalGroup.AddPattern( new Pattern( new UriRef("http://example.com/other"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query2" );
}
[Test]
public void EqualsComparesOptionalPatternCount() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.PatternGroup.OptionalGroup.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query2.PatternGroup.OptionalGroup.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query3.PatternGroup.OptionalGroup.AddPattern( new Pattern( new UriRef("http://example.com/subject"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
query3.PatternGroup.OptionalGroup.AddPattern( new Pattern( new UriRef("http://example.com/other"), new UriRef("http://example.com/predicate"), new Variable("var") ) );
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void EqualsComparesVariables() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.AddVariable( new Variable("var") );
query2.AddVariable( new Variable("var") );
query3.AddVariable( new Variable("other") );
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesVariables() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.AddVariable( new Variable("var") );
query2.AddVariable( new Variable("var") );
query3.AddVariable( new Variable("other") );
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query2" );
}
[Test]
public void EqualsComparesVariableCounts() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.AddVariable( new Variable("var") );
query2.AddVariable( new Variable("var") );
query3.AddVariable( new Variable("var") );
query3.AddVariable( new Variable("other") );
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void EqualsComparesConstraints() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.AddConstraint( new Constraint(new VariableExpression( new Variable("var") ) ) );
query2.AddConstraint( new Constraint( new VariableExpression( new Variable("var") ) ) );
query3.AddConstraint( new Constraint( new VariableExpression( new Variable("other") ) ) );
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesConstraints() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.AddConstraint( new Constraint(new VariableExpression( new Variable("var") ) ) );
query2.AddConstraint( new Constraint( new VariableExpression( new Variable("var") ) ) );
query3.AddConstraint( new Constraint( new VariableExpression( new Variable("other") ) ) );
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query3" );
}
[Test]
public void EqualsComparesBase() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.Base="http://example.org/a";
query2.Base="http://example.org/a";
query3.Base="http://example.org/b";
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesBase() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.Base="http://example.org/a";
query2.Base="http://example.org/a";
query3.Base="http://example.org/b";
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query3" );
}
[Test]
public void EqualsComparesOrderDirection() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.OrderDirection=Query.SortOrder.Ascending;
query2.OrderDirection=Query.SortOrder.Ascending;
query3.OrderDirection=Query.SortOrder.Descending;
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesOrderDirection() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.OrderDirection=Query.SortOrder.Ascending;
query2.OrderDirection=Query.SortOrder.Ascending;
query3.OrderDirection=Query.SortOrder.Descending;
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query3" );
}
[Test]
public void EqualsComparesOrderBy() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.OrderBy = new VariableExpression( new Variable("x") );
query2.OrderBy = new VariableExpression( new Variable("x") );
query3.OrderBy = new VariableExpression( new Variable("y") );
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesOrderBy() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.OrderBy = new VariableExpression( new Variable("x") );
query2.OrderBy = new VariableExpression( new Variable("x") );
query3.OrderBy = new VariableExpression( new Variable("y") );
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query3" );
}
[Test]
public void ResultLimitDefaultsToMaximumIntegerValue() {
Query query1 = new Query();
Assert.AreEqual( Int32.MaxValue, query1.ResultLimit, "Query should have default value for ResultLimit" );
}
[Test]
public void EqualsComparesResultLimit() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.ResultLimit = 5;
query2.ResultLimit = 5;
query3.ResultLimit = 4;
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesResultLimit() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.ResultLimit = 5;
query2.ResultLimit = 5;
query3.ResultLimit = 4;
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query3" );
}
[Test]
public void EqualsComparesResultOffset() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.ResultOffset = 5;
query2.ResultOffset = 5;
query3.ResultOffset = 4;
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesResultOffset() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.ResultOffset = 5;
query2.ResultOffset = 5;
query3.ResultOffset = 4;
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query3" );
}
[Test]
public void VariablesIncludesOnlyExplicitlyAddedVariablesIfNotSelectAll() {
Query query = new Query();
query.PatternGroup.AddPattern( new Pattern( new Variable("var"), new UriRef("http://example.com/predicate"), new Variable("foo")) );
query.AddVariable( new Variable("foo") );
query.SelectAll = false;
IList variables = query.Variables;
Assert.AreEqual( 1, variables.Count, "Should only be one variable");
}
[Test]
public void VariablesIncludesAllVariablesIfSelectAll() {
Query query = new Query();
query.PatternGroup.AddPattern( new Pattern( new Variable("var"), new UriRef("http://example.com/predicate"), new Variable("foo")) );
query.AddVariable( new Variable("foo") );
query.SelectAll = true;
IList variables = query.Variables;
Assert.AreEqual( 2, variables.Count, "Should only be one variable");
}
[Test]
public void EqualsComparesResultForm() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.ResultForm = Query.ResultFormType.Select;
query2.ResultForm = Query.ResultFormType.Select;
query3.ResultForm = Query.ResultFormType.Ask;
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeComparesResultForm() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.ResultForm = Query.ResultFormType.Select;
query2.ResultForm = Query.ResultFormType.Select;
query3.ResultForm = Query.ResultFormType.Ask;
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query3" );
}
[Test]
public void EqualsComparesDescribeTerms() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.AddDescribeTerm( new Variable("var") );
query2.AddDescribeTerm( new Variable("var") );
query3.AddDescribeTerm( new Variable("other") );
Assert.IsTrue( query1.Equals( query2 ), "Query1 should equal query2" );
Assert.IsTrue( ! query1.Equals( query3), "Query1 should not equal query3" );
}
[Test]
public void GetHashCodeUsesDescribeTerms() {
Query query1 = new Query();
Query query2 = new Query();
Query query3 = new Query();
query1.AddDescribeTerm( new Variable("var") );
query2.AddDescribeTerm( new Variable("var") );
query3.AddDescribeTerm( new Variable("other") );
Assert.IsTrue( query1.GetHashCode() == query2.GetHashCode() , "Query1 should have same hash code as query2" );
Assert.IsTrue( query1.GetHashCode() != query3.GetHashCode() , "Query1 should not have same hash code as query2" );
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.MarkMembersAsStaticAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.QualityGuidelines.CSharpMarkMembersAsStaticFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.MarkMembersAsStaticAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.QualityGuidelines.BasicMarkMembersAsStaticFixer>;
namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests
{
public class MarkMembersAsStaticFixerTests
{
[Fact]
public async Task TestCSharp_SimpleMembers_NoReferencesAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class MembersTests
{
internal static int s_field;
public const int Zero = 0;
public int [|Method1|](string name)
{
return name.Length;
}
public void [|Method2|]() { }
public void [|Method3|]()
{
s_field = 4;
}
public int [|Method4|]()
{
return Zero;
}
public int [|Property|]
{
get { return 5; }
}
public int [|Property2|]
{
set { s_field = value; }
}
public int [|MyProperty|]
{
get { return 10; }
set { System.Console.WriteLine(value); }
}
public event System.EventHandler<System.EventArgs> [|CustomEvent|] { add {} remove {} }
}",
@"
public class MembersTests
{
internal static int s_field;
public const int Zero = 0;
public static int Method1(string name)
{
return name.Length;
}
public static void Method2() { }
public static void Method3()
{
s_field = 4;
}
public static int Method4()
{
return Zero;
}
public static int Property
{
get { return 5; }
}
public static int Property2
{
set { s_field = value; }
}
public static int MyProperty
{
get { return 10; }
set { System.Console.WriteLine(value); }
}
public static event System.EventHandler<System.EventArgs> CustomEvent { add {} remove {} }
}");
}
[Fact]
public async Task TestBasic_SimpleMembers_NoReferencesAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Imports System
Public Class MembersTests
Shared s_field As Integer
Public Const Zero As Integer = 0
Public Function [|Method1|](name As String) As Integer
Return name.Length
End Function
Public Sub [|Method2|]()
End Sub
Public Sub [|Method3|]()
s_field = 4
End Sub
Public Function [|Method4|]() As Integer
Return Zero
End Function
Public Property [|MyProperty|] As Integer
Get
Return 10
End Get
Set
System.Console.WriteLine(Value)
End Set
End Property
Public Custom Event [|CustomEvent|] As EventHandler(Of EventArgs)
AddHandler(value As EventHandler(Of EventArgs))
End AddHandler
RemoveHandler(value As EventHandler(Of EventArgs))
End RemoveHandler
RaiseEvent(sender As Object, e As EventArgs)
End RaiseEvent
End Event
End Class",
@"
Imports System
Public Class MembersTests
Shared s_field As Integer
Public Const Zero As Integer = 0
Public Shared Function Method1(name As String) As Integer
Return name.Length
End Function
Public Shared Sub Method2()
End Sub
Public Shared Sub Method3()
s_field = 4
End Sub
Public Shared Function Method4() As Integer
Return Zero
End Function
Public Shared Property MyProperty As Integer
Get
Return 10
End Get
Set
System.Console.WriteLine(Value)
End Set
End Property
Public Shared Custom Event CustomEvent As EventHandler(Of EventArgs)
AddHandler(value As EventHandler(Of EventArgs))
End AddHandler
RemoveHandler(value As EventHandler(Of EventArgs))
End RemoveHandler
RaiseEvent(sender As Object, e As EventArgs)
End RaiseEvent
End Event
End Class");
}
[Fact]
public async Task TestCSharp_ReferencesInSameType_MemberReferencesAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
using System;
public class C
{
private C fieldC;
private C PropertyC { get; set; }
public int [|M1|]()
{
return 0;
}
public void M2(C paramC)
{
var localC = fieldC;
Func<int> m1 = M1,
m2 = paramC.M1,
m3 = localC.M1,
m4 = fieldC.M1,
m5 = PropertyC.M1,
m6 = fieldC.PropertyC.M1,
m7 = this.M1;
}
}",
@"
using System;
public class C
{
private C fieldC;
private C PropertyC { get; set; }
public static int M1()
{
return 0;
}
public void M2(C paramC)
{
var localC = fieldC;
Func<int> m1 = M1,
m2 = M1,
m3 = M1,
m4 = M1,
m5 = M1,
m6 = M1,
m7 = M1;
}
}");
}
[Fact]
public async Task TestBasic_ReferencesInSameType_MemberReferencesAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Imports System
Public Class C
Private fieldC As C
Private Property PropertyC As C
Public Function [|M1|]() As Integer
Return 0
End Function
Public Sub M2(paramC As C)
Dim localC = fieldC
Dim m As Func(Of Integer) = AddressOf M1,
m2 As Func(Of Integer) = AddressOf paramC.M1,
m3 As Func(Of Integer) = AddressOf localC.M1,
m4 As Func(Of Integer) = AddressOf fieldC.M1,
m5 As Func(Of Integer) = AddressOf PropertyC.M1,
m6 As Func(Of Integer) = AddressOf fieldC.PropertyC.M1,
m7 As Func(Of Integer) = AddressOf Me.M1
End Sub
End Class",
@"
Imports System
Public Class C
Private fieldC As C
Private Property PropertyC As C
Public Shared Function M1() As Integer
Return 0
End Function
Public Sub M2(paramC As C)
Dim localC = fieldC
Dim m As Func(Of Integer) = AddressOf M1,
m2 As Func(Of Integer) = AddressOf M1,
m3 As Func(Of Integer) = AddressOf M1,
m4 As Func(Of Integer) = AddressOf M1,
m5 As Func(Of Integer) = AddressOf M1,
m6 As Func(Of Integer) = AddressOf M1,
m7 As Func(Of Integer) = AddressOf M1
End Sub
End Class");
}
[Fact]
public async Task TestCSharp_ReferencesInSameType_InvocationsAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class C
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
private static C staticFieldC;
private static C StaticPropertyC { get; set; }
public int [|M1|]()
{
return 0;
}
public void M2(C paramC)
{
var localC = fieldC;
x = M1() + paramC.M1() + localC.M1() + fieldC.M1() + PropertyC.M1() + fieldC.PropertyC.M1() + this.M1() + C.staticFieldC.M1() + StaticPropertyC.M1();
}
}",
@"
public class C
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
private static C staticFieldC;
private static C StaticPropertyC { get; set; }
public static int M1()
{
return 0;
}
public void M2(C paramC)
{
var localC = fieldC;
x = M1() + M1() + M1() + M1() + M1() + M1() + M1() + M1() + M1();
}
}");
}
[Fact]
public async Task TestBasic_ReferencesInSameType_InvocationsAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class C
Private x As Integer
Private fieldC As C
Private Property PropertyC As C
Public Function [|M1|]() As Integer
Return 0
End Function
Public Sub M2(paramC As C)
Dim localC = fieldC
x = M1() + paramC.M1() + localC.M1() + fieldC.M1() + PropertyC.M1() + fieldC.PropertyC.M1() + Me.M1()
End Sub
End Class",
@"
Public Class C
Private x As Integer
Private fieldC As C
Private Property PropertyC As C
Public Shared Function M1() As Integer
Return 0
End Function
Public Sub M2(paramC As C)
Dim localC = fieldC
x = M1() + M1() + M1() + M1() + M1() + M1() + M1()
End Sub
End Class");
}
[Fact]
public async Task TestCSharp_ReferencesInSameFile_MemberReferencesAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
using System;
public class C
{
public C PropertyC { get; set; }
public int [|M1|]()
{
return 0;
}
}
class C2
{
private C fieldC;
private C PropertyC { get; set; }
public void M2(C paramC)
{
var localC = fieldC;
Func<int> m1 = paramC.M1,
m2 = localC.M1,
m3 = fieldC.M1,
m4 = PropertyC.M1,
m5 = fieldC.PropertyC.M1;
}
}",
@"
using System;
public class C
{
public C PropertyC { get; set; }
public static int M1()
{
return 0;
}
}
class C2
{
private C fieldC;
private C PropertyC { get; set; }
public void M2(C paramC)
{
var localC = fieldC;
Func<int> m1 = C.M1,
m2 = C.M1,
m3 = C.M1,
m4 = C.M1,
m5 = C.M1;
}
}");
}
[Fact]
public async Task TestCSharp_ReferencesInSameFile_InvocationsAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
using System;
public class C
{
public C PropertyC { get; set; }
public int [|M1|]()
{
return 0;
}
}
class C2
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
public void M2(C paramC)
{
var localC = fieldC;
x = paramC.M1() + localC.M1() + fieldC.M1() + PropertyC.M1() + fieldC.PropertyC.M1();
}
}",
@"
using System;
public class C
{
public C PropertyC { get; set; }
public static int M1()
{
return 0;
}
}
class C2
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
public void M2(C paramC)
{
var localC = fieldC;
x = C.M1() + C.M1() + C.M1() + C.M1() + C.M1();
}
}");
}
[Fact]
public async Task TestCSharp_ReferencesInMultipleFiles_MemberReferencesAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
using System;
public class C
{
public C PropertyC { get; set; }
public int [|M1|]()
{
return 0;
}
}
class C2
{
private C fieldC;
private C PropertyC { get; set; }
public void M2(C paramC)
{
var localC = fieldC;
Func<int> m1 = paramC.M1,
m2 = localC.M1,
m3 = fieldC.M1,
m4 = PropertyC.M1,
m5 = fieldC.PropertyC.M1;
}
}",
@"
using System;
class C3
{
private C fieldC;
private C PropertyC { get; set; }
public void M3(C paramC)
{
var localC = fieldC;
Func<int> m1 = paramC.M1,
m2 = localC.M1,
m3 = fieldC.M1,
m4 = PropertyC.M1,
m5 = fieldC.PropertyC.M1;
}
}",
},
},
FixedState =
{
Sources =
{
@"
using System;
public class C
{
public C PropertyC { get; set; }
public static int M1()
{
return 0;
}
}
class C2
{
private C fieldC;
private C PropertyC { get; set; }
public void M2(C paramC)
{
var localC = fieldC;
Func<int> m1 = C.M1,
m2 = C.M1,
m3 = C.M1,
m4 = C.M1,
m5 = C.M1;
}
}",
@"
using System;
class C3
{
private C fieldC;
private C PropertyC { get; set; }
public void M3(C paramC)
{
var localC = fieldC;
Func<int> m1 = C.M1,
m2 = C.M1,
m3 = C.M1,
m4 = C.M1,
m5 = C.M1;
}
}",
},
},
}.RunAsync();
}
[Fact]
public async Task TestCSharp_ReferencesInMultipleFiles_InvocationsAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
using System;
public class C
{
public C PropertyC { get; set; }
public int [|M1|]()
{
return 0;
}
}
class C2
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
public void M2(C paramC)
{
var localC = fieldC;
x = paramC.M1() + localC.M1() + fieldC.M1() + PropertyC.M1() + fieldC.PropertyC.M1();
}
}",
@"
using System;
class C3
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
public void M3(C paramC)
{
var localC = fieldC;
x = paramC.M1() + localC.M1() + fieldC.M1() + PropertyC.M1() + fieldC.PropertyC.M1();
}
}",
},
},
FixedState =
{
Sources =
{
@"
using System;
public class C
{
public C PropertyC { get; set; }
public static int M1()
{
return 0;
}
}
class C2
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
public void M2(C paramC)
{
var localC = fieldC;
x = C.M1() + C.M1() + C.M1() + C.M1() + C.M1();
}
}",
@"
using System;
class C3
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
public void M3(C paramC)
{
var localC = fieldC;
x = C.M1() + C.M1() + C.M1() + C.M1() + C.M1();
}
}",
},
},
}.RunAsync();
}
[Fact]
public async Task TestCSharp_ReferenceInArgumentAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class C
{
private C fieldC;
public C [|M1|](C c)
{
return c;
}
public C M2(C paramC)
{
var localC = fieldC;
return this.M1(paramC.M1(localC));
}
}",
@"
public class C
{
private C fieldC;
public static C M1(C c)
{
return c;
}
public C M2(C paramC)
{
var localC = fieldC;
return M1(M1(localC));
}
}");
}
[Fact]
public async Task TestBasic_ReferenceInArgumentAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class C
Private fieldC As C
Public Function [|M1|](c As C) As C
Return c
End Function
Public Function M2(paramC As C) As C
Dim localC = fieldC
Return Me.M1(paramC.M1(localC))
End Function
End Class",
@"
Public Class C
Private fieldC As C
Public Shared Function M1(c As C) As C
Return c
End Function
Public Function M2(paramC As C) As C
Dim localC = fieldC
Return M1(M1(localC))
End Function
End Class");
}
[Fact]
public async Task TestCSharp_GenericMethodAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class C
{
private C fieldC;
public C [|M1|]<T>(C c, T t)
{
return c;
}
public C M1<T>(T t, int i)
{
return fieldC;
}
}
public class C2<T2>
{
private C fieldC;
public void M2(C paramC)
{
// Explicit type argument
paramC.M1<int>(fieldC, 0);
// Implicit type argument
paramC.M1(fieldC, this);
}
}",
@"
public class C
{
private C fieldC;
public static C M1<T>(C c, T t)
{
return c;
}
public C M1<T>(T t, int i)
{
return fieldC;
}
}
public class C2<T2>
{
private C fieldC;
public void M2(C paramC)
{
// Explicit type argument
C.M1(fieldC, 0);
// Implicit type argument
C.M1(fieldC, this);
}
}");
}
[Fact]
public async Task TestCSharp_GenericMethod_02Async()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class C
{
private C fieldC;
public C [|M1|]<T>(C c)
{
return c;
}
public C M1<T>(T t)
{
return fieldC;
}
}
public class C2<T2>
{
private C fieldC;
public void M2(C paramC)
{
// Explicit type argument
paramC.M1<int>(fieldC);
}
}",
@"
public class C
{
private C fieldC;
public static C M1<T>(C c)
{
return c;
}
public C M1<T>(T t)
{
return fieldC;
}
}
public class C2<T2>
{
private C fieldC;
public void M2(C paramC)
{
// Explicit type argument
C.M1<int>(fieldC);
}
}");
}
[Fact]
public async Task TestBasic_GenericMethodAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class C
Private fieldC As C
Public Function [|M1|](Of T)(c As C, t1 As T) As C
Return c
End Function
Public Function M1(Of T)(t1 As T, i As Integer) As C
Return fieldC
End Function
End Class
Public Class C2(Of T2)
Private fieldC As C
Public Sub M2(paramC As C)
' Explicit type argument
paramC.M1(Of Integer)(fieldC, 0)
' Implicit type argument
paramC.M1(fieldC, Me)
End Sub
End Class",
@"
Public Class C
Private fieldC As C
Public Shared Function M1(Of T)(c As C, t1 As T) As C
Return c
End Function
Public Function M1(Of T)(t1 As T, i As Integer) As C
Return fieldC
End Function
End Class
Public Class C2(Of T2)
Private fieldC As C
Public Sub M2(paramC As C)
' Explicit type argument
C.M1(Of Integer)(fieldC, 0)
' Implicit type argument
C.M1(fieldC, Me)
End Sub
End Class");
}
[Fact]
public async Task TestCSharp_InvocationInInstanceAsync()
{
// We don't make the replacement if instance has an invocation.
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class C
{
private C fieldC;
public C [|M1|](C c)
{
return c;
}
public C M2(C paramC)
{
var localC = fieldC;
return localC.M1(paramC).M1(paramC.M1(localC));
}
}",
},
},
FixedState =
{
Sources =
{
@"
public class C
{
private C fieldC;
public static C M1(C c)
{
return c;
}
public C M2(C paramC)
{
var localC = fieldC;
return {|CS0176:M1(paramC).M1|}(M1(localC));
}
}",
},
},
}.RunAsync();
}
[Fact]
public async Task TestBasic_InvocationInInstanceAsync()
{
// We don't make the replacement if instance has an invocation.
await VerifyVB.VerifyCodeFixAsync(@"
Public Class C
Private fieldC As C
Public Function [|M1|](c As C) As C
Return c
End Function
Public Function M2(paramC As C) As C
Dim localC = fieldC
Return localC.M1(paramC).M1(paramC.M1(localC))
End Function
End Class",
@"
Public Class C
Private fieldC As C
Public Shared Function M1(c As C) As C
Return c
End Function
Public Function M2(paramC As C) As C
Dim localC = fieldC
Return M1(paramC).M1(M1(localC))
End Function
End Class");
}
[Fact]
public async Task TestCSharp_ConversionInInstanceAsync()
{
// We don't make the replacement if instance has a conversion.
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class C
{
private C fieldC;
public object [|M1|](C c)
{
return c;
}
public C M2(C paramC)
{
var localC = fieldC;
return {|CS0266:((C)paramC).M1(localC)|};
}
}"
},
},
FixedState =
{
Sources =
{
@"
public class C
{
private C fieldC;
public static object M1(C c)
{
return c;
}
public C M2(C paramC)
{
var localC = fieldC;
return {|CS0176:((C)paramC).M1|}(localC);
}
}",
},
},
}.RunAsync();
}
[Fact]
public async Task TestBasic_ConversionInInstanceAsync()
{
// We don't make the replacement if instance has a conversion.
await VerifyVB.VerifyCodeFixAsync(@"
Public Class C
Private fieldC As C
Public Function [|M1|](c As C) As Object
Return c
End Function
Public Function M2(paramC As C) As C
Dim localC = fieldC
Return (CType(paramC, C)).M1(localC)
End Function
End Class",
@"
Public Class C
Private fieldC As C
Public Shared Function M1(c As C) As Object
Return c
End Function
Public Function M2(paramC As C) As C
Dim localC = fieldC
Return (CType(paramC, C)).M1(localC)
End Function
End Class");
}
[Fact]
public async Task TestCSharp_FixAllAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
using System;
public class C
{
public C PropertyC { get; set; }
public int [|M1|]()
{
return 0;
}
public int [|M2|]()
{
return 0;
}
}
class C2
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
public void M2(C paramC)
{
var localC = fieldC;
x = paramC.M1() + localC.M2() + fieldC.M1() + PropertyC.M2() + fieldC.PropertyC.M1();
}
}",
@"
using System;
class C3
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
public void M3(C paramC)
{
var localC = fieldC;
x = paramC.M2() + localC.M1() + fieldC.M2() + PropertyC.M1() + fieldC.PropertyC.M2();
}
}",
},
},
FixedState =
{
Sources =
{
@"
using System;
public class C
{
public C PropertyC { get; set; }
public static int M1()
{
return 0;
}
public static int M2()
{
return 0;
}
}
class C2
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
public void M2(C paramC)
{
var localC = fieldC;
x = C.M1() + C.M2() + C.M1() + C.M2() + C.M1();
}
}",
@"
using System;
class C3
{
private int x;
private C fieldC;
private C PropertyC { get; set; }
public void M3(C paramC)
{
var localC = fieldC;
x = C.M2() + C.M1() + C.M2() + C.M1() + C.M2();
}
}",
},
},
}.RunAsync();
}
[Fact]
public async Task TestBasic_FixAllAsync()
{
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Imports System
Public Class C
Public Property PropertyC As C
Public Function [|M1|]() As Integer
Return 0
End Function
Public Function [|M2|]() As Integer
Return 0
End Function
End Class
Class C2
Private x As Integer
Private fieldC As C
Private Property PropertyC As C
Public Sub M2(paramC As C)
Dim localC = fieldC
x = paramC.M1() + localC.M2() + fieldC.M1() + PropertyC.M2() + fieldC.PropertyC.M1()
End Sub
End Class",
@"
Imports System
Class C3
Private x As Integer
Private fieldC As C
Private Property PropertyC As C
Public Sub M3(paramC As C)
Dim localC = fieldC
x = paramC.M2() + localC.M1() + fieldC.M2() + PropertyC.M1() + fieldC.PropertyC.M2()
End Sub
End Class",
},
},
FixedState =
{
Sources =
{
@"
Imports System
Public Class C
Public Property PropertyC As C
Public Shared Function M1() As Integer
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class
Class C2
Private x As Integer
Private fieldC As C
Private Property PropertyC As C
Public Sub M2(paramC As C)
Dim localC = fieldC
x = C.M1() + C.M2() + C.M1() + C.M2() + C.M1()
End Sub
End Class",
@"
Imports System
Class C3
Private x As Integer
Private fieldC As C
Private Property PropertyC As C
Public Sub M3(paramC As C)
Dim localC = fieldC
x = C.M2() + C.M1() + C.M2() + C.M1() + C.M2()
End Sub
End Class",
},
},
}.RunAsync();
}
[Fact]
public async Task TestCSharp_PropertyWithReferencesAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class C
{
private C fieldC;
public C [|M1|] { get { return null; } set { } }
public C M2(C paramC)
{
var x = this.M1;
paramC.M1 = x;
return fieldC;
}
}",
@"
public class C
{
private C fieldC;
public static C M1 { get { return null; } set { } }
public C M2(C paramC)
{
var x = M1;
M1 = x;
return fieldC;
}
}");
}
[Fact]
public async Task TestBasic_PropertyWithReferencesAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class C
Private fieldC As C
Public Property [|M1|] As C
Get
Return Nothing
End Get
Set(ByVal value As C)
End Set
End Property
Public Function M2(paramC As C) As C
Dim x = Me.M1
paramC.M1 = x
Return fieldC
End Function
End Class",
@"
Public Class C
Private fieldC As C
Public Shared Property M1 As C
Get
Return Nothing
End Get
Set(ByVal value As C)
End Set
End Property
Public Function M2(paramC As C) As C
Dim x = M1
M1 = x
Return fieldC
End Function
End Class");
}
[Fact, WorkItem(2888, "https://github.com/dotnet/roslyn-analyzers/issues/2888")]
public async Task CA1822_CSharp_AsyncModifierAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
using System.Threading.Tasks;
public class C
{
public async Task<int> [|M1|]()
{
await Task.Delay(20).ConfigureAwait(false);
return 20;
}
}",
@"
using System.Threading.Tasks;
public class C
{
public static async Task<int> M1()
{
await Task.Delay(20).ConfigureAwait(false);
return 20;
}
}");
await VerifyVB.VerifyCodeFixAsync(@"
Imports System.Threading.Tasks
Public Class C
Public Async Function [|M1|]() As Task(Of Integer)
Await Task.Delay(20).ConfigureAwait(False)
Return 20
End Function
End Class",
@"
Imports System.Threading.Tasks
Public Class C
Public Shared Async Function M1() As Task(Of Integer)
Await Task.Delay(20).ConfigureAwait(False)
Return 20
End Function
End Class");
}
[Fact]
[WorkItem(4733, "https://github.com/dotnet/roslyn-analyzers/issues/4733")]
[WorkItem(5168, "https://github.com/dotnet/roslyn-analyzers/issues/5168")]
public async Task CA1822_PartialMethod_CannotBeStaticAsync()
{
string source = @"
using System.Threading;
using System.Threading.Tasks;
public partial class Class1
{
public partial Task Example(CancellationToken token = default);
}
partial class Class1
{
private readonly int timeout;
public Class1(int timeout)
{
this.timeout = timeout;
}
public async partial Task Example(CancellationToken token)
{
await Task.Delay(timeout, token);
}
}
";
await new VerifyCS.Test
{
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9,
TestCode = source,
FixedCode = source,
}.RunAsync();
}
[Fact]
[WorkItem(4733, "https://github.com/dotnet/roslyn-analyzers/issues/4733")]
[WorkItem(5168, "https://github.com/dotnet/roslyn-analyzers/issues/5168")]
public async Task CA1822_PartialMethod_CanBeStaticAsync()
{
string source = @"
using System.Threading;
using System.Threading.Tasks;
public partial class Class1
{
public partial Task Example(CancellationToken token = default);
}
partial class Class1
{
private readonly int timeout;
public Class1(int timeout)
{
this.timeout = timeout;
}
public async partial Task [|Example|](CancellationToken token)
{
await Task.Delay(0);
}
}
";
// The fixed source shouldn't have diagnostics. Tracked by https://github.com/dotnet/roslyn-analyzers/issues/5171.
string fixedSource = @"
using System.Threading;
using System.Threading.Tasks;
public partial class Class1
{
public partial Task Example(CancellationToken token = default);
}
partial class Class1
{
private readonly int timeout;
public Class1(int timeout)
{
this.timeout = timeout;
}
public static async partial Task {|CS0763:Example|}(CancellationToken token)
{
await Task.Delay(0);
}
}
";
await new VerifyCS.Test
{
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
}
}
| |
using System;
using CryptoTokenKit;
using Foundation;
using ObjCRuntime;
using Security;
namespace CryptoTokenKit
{
[Static]
partial interface Constants
{
[Field ("TKErrorDomain", "/System/Library/Frameworks/CryptoTokenKit.framework/CryptoTokenKit")]
NSString TKErrorDomain { get; }
}
// @interface TKTLVRecord : NSObject
[BaseType (typeof (NSObject))]
[DisableDefaultCtor]
interface TKTLVRecord
{
// @property (readonly, nonatomic) TKTLVTag tag;
[Export ("tag")]
ulong Tag { get; }
// @property (readonly, nonatomic) NSData * _Nonnull value;
[Export ("value")]
NSData Value { get; }
// @property (readonly, nonatomic) NSData * _Nonnull data;
[Export ("data")]
NSData Data { get; }
// +(instancetype _Nullable)recordFromData:(NSData * _Nonnull)data;
[Static]
[Export ("recordFromData:")]
[return: NullAllowed]
TKTLVRecord RecordFromData (NSData data);
// +(NSArray<TKTLVRecord *> * _Nullable)sequenceOfRecordsFromData:(NSData * _Nonnull)data;
[Static]
[Export ("sequenceOfRecordsFromData:")]
[return: NullAllowed]
TKTLVRecord [] SequenceOfRecordsFromData (NSData data);
}
// @interface TKBERTLVRecord : TKTLVRecord
[BaseType (typeof (TKTLVRecord))]
interface TKBERTLVRecord
{
// +(NSData * _Nonnull)dataForTag:(TKTLVTag)tag;
[Static]
[Export ("dataForTag:")]
NSData DataForTag (ulong tag);
// -(instancetype _Nonnull)initWithTag:(TKTLVTag)tag value:(NSData * _Nonnull)value;
[Export ("initWithTag:value:")]
IntPtr Constructor (ulong tag, NSData value);
// -(instancetype _Nonnull)initWithTag:(TKTLVTag)tag records:(NSArray<TKTLVRecord *> * _Nonnull)records;
[Export ("initWithTag:records:")]
IntPtr Constructor (ulong tag, TKTLVRecord [] records);
}
// @interface TKSimpleTLVRecord : TKTLVRecord
[BaseType (typeof (TKTLVRecord))]
interface TKSimpleTLVRecord
{
// -(instancetype _Nonnull)initWithTag:(UInt8)tag value:(NSData * _Nonnull)value;
[Export ("initWithTag:value:")]
IntPtr Constructor (byte tag, NSData value);
}
// @interface TKCompactTLVRecord : TKTLVRecord
[BaseType (typeof (TKTLVRecord))]
interface TKCompactTLVRecord
{
// -(instancetype _Nonnull)initWithTag:(UInt8)tag value:(NSData * _Nonnull)value;
[Export ("initWithTag:value:")]
IntPtr Constructor (byte tag, NSData value);
}
// @interface TKSmartCardATRInterfaceGroup : NSObject
[BaseType (typeof (NSObject))]
interface TKSmartCardATRInterfaceGroup
{
// @property (readonly, nonatomic) NSNumber * _Nullable TA;
[NullAllowed, Export ("TA")]
NSNumber TA { get; }
// @property (readonly, nonatomic) NSNumber * _Nullable TB;
[NullAllowed, Export ("TB")]
NSNumber TB { get; }
// @property (readonly, nonatomic) NSNumber * _Nullable TC;
[NullAllowed, Export ("TC")]
NSNumber TC { get; }
// @property (readonly, nonatomic) NSNumber * _Nullable protocol;
[NullAllowed, Export ("protocol")]
NSNumber Protocol { get; }
}
// @interface TKSmartCardATR : NSObject
[BaseType (typeof (NSObject))]
interface TKSmartCardATR
{
// -(instancetype _Nullable)initWithBytes:(NSData * _Nonnull)bytes;
[Export ("initWithBytes:")]
IntPtr Constructor (NSData bytes);
// -(instancetype _Nullable)initWithSource:(int (^ _Nonnull)())source;
[Export ("initWithSource:")]
IntPtr Constructor (Func<int> source);
// @property (readonly, nonatomic) NSData * _Nonnull bytes;
[Export ("bytes")]
NSData Bytes { get; }
// @property (readonly, nonatomic) NSArray<NSNumber *> * _Nonnull protocols;
[Export ("protocols")]
NSNumber [] Protocols { get; }
// -(TKSmartCardATRInterfaceGroup * _Nullable)interfaceGroupAtIndex:(NSInteger)index;
[Export ("interfaceGroupAtIndex:")]
[return: NullAllowed]
TKSmartCardATRInterfaceGroup InterfaceGroupAtIndex (nint index);
// -(TKSmartCardATRInterfaceGroup * _Nullable)interfaceGroupForProtocol:(TKSmartCardProtocol)protocol;
[Export ("interfaceGroupForProtocol:")]
[return: NullAllowed]
TKSmartCardATRInterfaceGroup InterfaceGroupForProtocol (TKSmartCardProtocol protocol);
// @property (readonly, nonatomic) NSData * _Nonnull historicalBytes;
[Export ("historicalBytes")]
NSData HistoricalBytes { get; }
// @property (readonly, nonatomic) NSArray<TKCompactTLVRecord *> * _Nullable historicalRecords __attribute__((availability(watchos, introduced=4.0))) __attribute__((availability(tvos, introduced=11.0))) __attribute__((availability(ios, introduced=10.0))) __attribute__((availability(macos, introduced=10.12)));
[NullAllowed, Export ("historicalRecords")]
TKCompactTLVRecord [] HistoricalRecords { get; }
}
// @interface TKSmartCardSlotManager : NSObject
[BaseType (typeof (NSObject))]
interface TKSmartCardSlotManager
{
// @property (readonly, class) TKSmartCardSlotManager * _Nullable defaultManager;
[Static]
[NullAllowed, Export ("defaultManager")]
TKSmartCardSlotManager DefaultManager { get; }
// @property (readonly) NSArray<NSString *> * _Nonnull slotNames;
[Export ("slotNames")]
string [] SlotNames { get; }
// -(void)getSlotWithName:(NSString * _Nonnull)name reply:(void (^ _Nonnull)(TKSmartCardSlot * _Nullable))reply;
[Export ("getSlotWithName:reply:")]
void GetSlotWithName (string name, Action<TKSmartCardSlot> reply);
// -(TKSmartCardSlot * _Nullable)slotNamed:(NSString * _Nonnull)name __attribute__((availability(macos, introduced=10.13)));
[Export ("slotNamed:")]
[return: NullAllowed]
TKSmartCardSlot SlotNamed (string name);
}
// @interface TKSmartCardPINFormat : NSObject
[BaseType (typeof (NSObject))]
interface TKSmartCardPINFormat
{
// @property TKSmartCardPINCharset charset;
[Export ("charset", ArgumentSemantic.Assign)]
TKSmartCardPINCharset Charset { get; set; }
// @property TKSmartCardPINEncoding encoding;
[Export ("encoding", ArgumentSemantic.Assign)]
TKSmartCardPINEncoding Encoding { get; set; }
// @property NSInteger minPINLength;
[Export ("minPINLength")]
nint MinPINLength { get; set; }
// @property NSInteger maxPINLength;
[Export ("maxPINLength")]
nint MaxPINLength { get; set; }
// @property NSInteger PINBlockByteLength;
[Export ("PINBlockByteLength")]
nint PINBlockByteLength { get; set; }
// @property TKSmartCardPINJustification PINJustification;
[Export ("PINJustification", ArgumentSemantic.Assign)]
TKSmartCardPINJustification PINJustification { get; set; }
// @property NSInteger PINBitOffset;
[Export ("PINBitOffset")]
nint PINBitOffset { get; set; }
// @property NSInteger PINLengthBitOffset;
[Export ("PINLengthBitOffset")]
nint PINLengthBitOffset { get; set; }
// @property NSInteger PINLengthBitSize;
[Export ("PINLengthBitSize")]
nint PINLengthBitSize { get; set; }
}
class ITKSmartCardUserInteractionDelegate {}
// @protocol TKSmartCardUserInteractionDelegate
[Protocol, Model]
interface TKSmartCardUserInteractionDelegate
{
// @optional -(void)characterEnteredInUserInteraction:(TKSmartCardUserInteraction * _Nonnull)interaction;
[Export ("characterEnteredInUserInteraction:")]
void CharacterEnteredInUserInteraction (TKSmartCardUserInteraction interaction);
// @optional -(void)correctionKeyPressedInUserInteraction:(TKSmartCardUserInteraction * _Nonnull)interaction;
[Export ("correctionKeyPressedInUserInteraction:")]
void CorrectionKeyPressedInUserInteraction (TKSmartCardUserInteraction interaction);
// @optional -(void)validationKeyPressedInUserInteraction:(TKSmartCardUserInteraction * _Nonnull)interaction;
[Export ("validationKeyPressedInUserInteraction:")]
void ValidationKeyPressedInUserInteraction (TKSmartCardUserInteraction interaction);
// @optional -(void)invalidCharacterEnteredInUserInteraction:(TKSmartCardUserInteraction * _Nonnull)interaction;
[Export ("invalidCharacterEnteredInUserInteraction:")]
void InvalidCharacterEnteredInUserInteraction (TKSmartCardUserInteraction interaction);
// @optional -(void)oldPINRequestedInUserInteraction:(TKSmartCardUserInteraction * _Nonnull)interaction;
[Export ("oldPINRequestedInUserInteraction:")]
void OldPINRequestedInUserInteraction (TKSmartCardUserInteraction interaction);
// @optional -(void)newPINRequestedInUserInteraction:(TKSmartCardUserInteraction * _Nonnull)interaction;
[Export ("newPINRequestedInUserInteraction:")]
void NewPINRequestedInUserInteraction (TKSmartCardUserInteraction interaction);
// @optional -(void)newPINConfirmationRequestedInUserInteraction:(TKSmartCardUserInteraction * _Nonnull)interaction;
[Export ("newPINConfirmationRequestedInUserInteraction:")]
void NewPINConfirmationRequestedInUserInteraction (TKSmartCardUserInteraction interaction);
}
// @interface TKSmartCardUserInteraction : NSObject
[BaseType (typeof (NSObject))]
interface TKSmartCardUserInteraction
{
[Protocolize]
[Wrap ("WeakDelegate")]
[NullAllowed]
TKSmartCardUserInteractionDelegate Delegate { get; set; }
// @property (weak) id<TKSmartCardUserInteractionDelegate> _Nullable delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @property NSTimeInterval initialTimeout;
[Export ("initialTimeout")]
double InitialTimeout { get; set; }
// @property NSTimeInterval interactionTimeout;
[Export ("interactionTimeout")]
double InteractionTimeout { get; set; }
// -(void)runWithReply:(void (^ _Nonnull)(BOOL, NSError * _Nullable))reply;
[Export ("runWithReply:")]
void RunWithReply (Action<bool, NSError> reply);
// -(BOOL)cancel;
[Export ("cancel")]
bool Cancel ();
}
// @interface TKSmartCardUserInteractionForPINOperation : TKSmartCardUserInteraction
[BaseType (typeof (TKSmartCardUserInteraction))]
interface TKSmartCardUserInteractionForPINOperation
{
// @property TKSmartCardPINCompletion PINCompletion;
[Export ("PINCompletion", ArgumentSemantic.Assign)]
TKSmartCardPINCompletion PINCompletion { get; set; }
// @property NSArray<NSNumber *> * _Nullable PINMessageIndices;
[NullAllowed, Export ("PINMessageIndices", ArgumentSemantic.Assign)]
NSNumber [] PINMessageIndices { get; set; }
// @property NSLocale * _Null_unspecified locale;
[Export ("locale", ArgumentSemantic.Assign)]
NSLocale Locale { get; set; }
// @property UInt16 resultSW;
[Export ("resultSW")]
ushort ResultSW { get; set; }
// @property NSData * _Nullable resultData;
[NullAllowed, Export ("resultData", ArgumentSemantic.Assign)]
NSData ResultData { get; set; }
}
// @interface TKSmartCardUserInteractionForSecurePINVerification : TKSmartCardUserInteractionForPINOperation
[BaseType (typeof (TKSmartCardUserInteractionForPINOperation))]
interface TKSmartCardUserInteractionForSecurePINVerification
{
}
// @interface TKSmartCardUserInteractionForSecurePINChange : TKSmartCardUserInteractionForPINOperation
[BaseType (typeof (TKSmartCardUserInteractionForPINOperation))]
interface TKSmartCardUserInteractionForSecurePINChange
{
// @property TKSmartCardPINConfirmation PINConfirmation;
[Export ("PINConfirmation", ArgumentSemantic.Assign)]
TKSmartCardPINConfirmation PINConfirmation { get; set; }
}
// @interface TKSmartCardSlot : NSObject
[BaseType (typeof (NSObject))]
interface TKSmartCardSlot
{
// @property (readonly) TKSmartCardSlotState state;
[Export ("state")]
TKSmartCardSlotState State { get; }
// @property (readonly) TKSmartCardATR * _Nullable ATR;
[NullAllowed, Export ("ATR")]
TKSmartCardATR ATR { get; }
// @property (readonly, nonatomic) NSString * _Nonnull name;
[Export ("name")]
string Name { get; }
// @property (readonly, nonatomic) NSInteger maxInputLength;
[Export ("maxInputLength")]
nint MaxInputLength { get; }
// @property (readonly, nonatomic) NSInteger maxOutputLength;
[Export ("maxOutputLength")]
nint MaxOutputLength { get; }
// -(TKSmartCard * _Nullable)makeSmartCard;
[NullAllowed, Export ("makeSmartCard")]
TKSmartCard MakeSmartCard { get; }
}
// @interface TKSmartCard : NSObject
[BaseType (typeof (NSObject))]
interface TKSmartCard
{
// @property (readonly, nonatomic) TKSmartCardSlot * _Nonnull slot;
[Export ("slot")]
TKSmartCardSlot Slot { get; }
// @property (readonly) BOOL valid;
[Export ("valid")]
bool Valid { get; }
// @property TKSmartCardProtocol allowedProtocols;
[Export ("allowedProtocols", ArgumentSemantic.Assign)]
TKSmartCardProtocol AllowedProtocols { get; set; }
// @property (readonly) TKSmartCardProtocol currentProtocol;
[Export ("currentProtocol")]
TKSmartCardProtocol CurrentProtocol { get; }
// @property BOOL sensitive;
[Export ("sensitive")]
bool Sensitive { get; set; }
// @property id _Nullable context;
[NullAllowed, Export ("context", ArgumentSemantic.Assign)]
NSObject Context { get; set; }
// -(void)beginSessionWithReply:(void (^ _Nonnull)(BOOL, NSError * _Nullable))reply;
[Export ("beginSessionWithReply:")]
void BeginSessionWithReply (Action<bool, NSError> reply);
// -(void)transmitRequest:(NSData * _Nonnull)request reply:(void (^ _Nonnull)(NSData * _Nullable, NSError * _Nullable))reply;
[Export ("transmitRequest:reply:")]
void TransmitRequest (NSData request, Action<NSData, NSError> reply);
// -(void)endSession;
[Export ("endSession")]
void EndSession ();
// -(TKSmartCardUserInteractionForSecurePINVerification * _Nullable)userInteractionForSecurePINVerificationWithPINFormat:(TKSmartCardPINFormat * _Nonnull)PINFormat APDU:(NSData * _Nonnull)APDU PINByteOffset:(NSInteger)PINByteOffset __attribute__((availability(macos, introduced=10.11)));
[Export ("userInteractionForSecurePINVerificationWithPINFormat:APDU:PINByteOffset:")]
[return: NullAllowed]
TKSmartCardUserInteractionForSecurePINVerification UserInteractionForSecurePINVerificationWithPINFormat (TKSmartCardPINFormat PINFormat, NSData APDU, nint PINByteOffset);
// -(TKSmartCardUserInteractionForSecurePINChange * _Nullable)userInteractionForSecurePINChangeWithPINFormat:(TKSmartCardPINFormat * _Nonnull)PINFormat APDU:(NSData * _Nonnull)APDU currentPINByteOffset:(NSInteger)currentPINByteOffset newPINByteOffset:(NSInteger)newPINByteOffset __attribute__((availability(macos, introduced=10.11)));
[Export ("userInteractionForSecurePINChangeWithPINFormat:APDU:currentPINByteOffset:newPINByteOffset:")]
[return: NullAllowed]
TKSmartCardUserInteractionForSecurePINChange UserInteractionForSecurePINChangeWithPINFormat (TKSmartCardPINFormat PINFormat, NSData APDU, nint currentPINByteOffset, nint newPINByteOffset);
}
// @interface APDULevelTransmit (TKSmartCard)
//[Category]
//[BaseType (typeof (TKSmartCard))]
//interface TKSmartCard_APDULevelTransmit
//{
// // @property UInt8 cla __attribute__((availability(watchos, introduced=4.0))) __attribute__((availability(tvos, introduced=11.0))) __attribute__((availability(ios, introduced=9.0))) __attribute__((availability(macos, introduced=10.10)));
// [Export ("cla")]
// byte Cla { get; set; }
// // @property BOOL useExtendedLength __attribute__((availability(watchos, introduced=4.0))) __attribute__((availability(tvos, introduced=11.0))) __attribute__((availability(ios, introduced=9.0))) __attribute__((availability(macos, introduced=10.10)));
// [Export ("useExtendedLength")]
// bool UseExtendedLength { get; set; }
// // @property BOOL useCommandChaining __attribute__((availability(watchos, introduced=4.0))) __attribute__((availability(tvos, introduced=11.0))) __attribute__((availability(ios, introduced=10.0))) __attribute__((availability(macos, introduced=10.12)));
// [Export ("useCommandChaining")]
// bool UseCommandChaining { get; set; }
// // -(void)sendIns:(UInt8)ins p1:(UInt8)p1 p2:(UInt8)p2 data:(NSData * _Nullable)requestData le:(NSNumber * _Nullable)le reply:(void (^ _Nonnull)(NSData * _Nullable, UInt16, NSError * _Nullable))reply __attribute__((availability(watchos, introduced=4.0))) __attribute__((availability(tvos, introduced=11.0))) __attribute__((availability(ios, introduced=9.0))) __attribute__((availability(macos, introduced=10.10)));
// [Export ("sendIns:p1:p2:data:le:reply:")]
// void SendIns (byte ins, byte p1, byte p2, [NullAllowed] NSData requestData, [NullAllowed] NSNumber le, Action<NSData, ushort, NSError> reply);
// // -(BOOL)inSessionWithError:(NSError * _Nullable * _Nullable)error executeBlock:(BOOL (^ _Nonnull)(NSError * _Nullable * _Nullable))block __attribute__((availability(watchos, introduced=4.0))) __attribute__((availability(tvos, introduced=11.0))) __attribute__((availability(ios, introduced=10.0))) __attribute__((availability(macos, introduced=10.12)));
// [Watch (4, 0), TV (11, 0), Mac (10, 12), iOS (10, 0)]
// [Export ("inSessionWithError:executeBlock:")]
// unsafe bool InSessionWithError ([NullAllowed] out NSError error, Func<Foundation.NSError*, bool> block);
// -(NSData * _Nullable)sendIns:(UInt8)ins p1:(UInt8)p1 p2:(UInt8)p2 data:(NSData * _Nullable)requestData le:(NSNumber * _Nullable)le sw:(UInt16 * _Nonnull)sw error:(NSError * _Nullable * _Nullable)error __attribute__((availability(watchos, introduced=4.0))) __attribute__((availability(tvos, introduced=11.0))) __attribute__((availability(ios, introduced=10.0))) __attribute__((availability(macos, introduced=10.12)));
// [Export ("sendIns:p1:p2:data:le:sw:error:")]
// [return: NullAllowed]
// unsafe NSData SendIns (byte ins, byte p1, byte p2, [NullAllowed] NSData requestData, [NullAllowed] NSNumber le, ushort* sw, [NullAllowed] out NSError error);
//}
// @interface TKTokenKeyAlgorithm : NSObject
[BaseType (typeof (NSObject))]
[DisableDefaultCtor]
interface TKTokenKeyAlgorithm
{
// -(BOOL)isAlgorithm:(SecKeyAlgorithm _Nonnull)algorithm;
[Export ("isAlgorithm:")]
unsafe bool IsAlgorithm (IntPtr algorithm);
// -(BOOL)supportsAlgorithm:(SecKeyAlgorithm _Nonnull)algorithm;
[Export ("supportsAlgorithm:")]
unsafe bool SupportsAlgorithm (IntPtr algorithm);
}
// @interface TKTokenKeyExchangeParameters : NSObject
[BaseType (typeof (NSObject))]
interface TKTokenKeyExchangeParameters
{
// @property (readonly) NSInteger requestedSize;
[Export ("requestedSize")]
nint RequestedSize { get; }
// @property (readonly, copy) NSData * _Nullable sharedInfo;
[NullAllowed, Export ("sharedInfo", ArgumentSemantic.Copy)]
NSData SharedInfo { get; }
}
// @interface TKTokenSession : NSObject
[BaseType (typeof (NSObject))]
[DisableDefaultCtor]
interface TKTokenSession
{
// -(instancetype _Nonnull)initWithToken:(TKToken * _Nonnull)token __attribute__((objc_designated_initializer));
[Export ("initWithToken:")]
[DesignatedInitializer]
IntPtr Constructor (TKToken token);
// @property (readonly) TKToken * _Nonnull token;
[Export ("token")]
TKToken Token { get; }
[Wrap ("WeakDelegate")]
[NullAllowed]
TKTokenSessionDelegate Delegate { get; set; }
// @property (weak) id<TKTokenSessionDelegate> _Nullable delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
}
// @protocol TKTokenSessionDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof (NSObject))]
interface TKTokenSessionDelegate
{
// @optional -(TKTokenAuthOperation * _Nullable)tokenSession:(TKTokenSession * _Nonnull)session beginAuthForOperation:(TKTokenOperation)operation constraint:(TKTokenOperationConstraint _Nonnull)constraint error:(NSError * _Nullable * _Nullable)error;
[Export ("tokenSession:beginAuthForOperation:constraint:error:")]
[return: NullAllowed]
TKTokenAuthOperation BeginAuth (TKTokenSession session, TKTokenOperation operation, NSObject constraint, [NullAllowed] out NSError error);
// @optional -(BOOL)tokenSession:(TKTokenSession * _Nonnull)session supportsOperation:(TKTokenOperation)operation usingKey:(TKTokenObjectID _Nonnull)keyObjectID algorithm:(TKTokenKeyAlgorithm * _Nonnull)algorithm;
[Export ("tokenSession:supportsOperation:usingKey:algorithm:")]
bool SupportsOperation (TKTokenSession session, TKTokenOperation operation, NSObject keyObjectID, TKTokenKeyAlgorithm algorithm);
// @optional -(NSData * _Nullable)tokenSession:(TKTokenSession * _Nonnull)session signData:(NSData * _Nonnull)dataToSign usingKey:(TKTokenObjectID _Nonnull)keyObjectID algorithm:(TKTokenKeyAlgorithm * _Nonnull)algorithm error:(NSError * _Nullable * _Nullable)error;
[Export ("tokenSession:signData:usingKey:algorithm:error:")]
[return: NullAllowed]
NSData SignData (TKTokenSession session, NSData dataToSign, NSObject keyObjectID, TKTokenKeyAlgorithm algorithm, [NullAllowed] out NSError error);
// @optional -(NSData * _Nullable)tokenSession:(TKTokenSession * _Nonnull)session decryptData:(NSData * _Nonnull)ciphertext usingKey:(TKTokenObjectID _Nonnull)keyObjectID algorithm:(TKTokenKeyAlgorithm * _Nonnull)algorithm error:(NSError * _Nullable * _Nullable)error;
[Export ("tokenSession:decryptData:usingKey:algorithm:error:")]
[return: NullAllowed]
NSData DecryptData (TKTokenSession session, NSData ciphertext, NSObject keyObjectID, TKTokenKeyAlgorithm algorithm, [NullAllowed] out NSError error);
// @optional -(NSData * _Nullable)tokenSession:(TKTokenSession * _Nonnull)session performKeyExchangeWithPublicKey:(NSData * _Nonnull)otherPartyPublicKeyData usingKey:(TKTokenObjectID _Nonnull)objectID algorithm:(TKTokenKeyAlgorithm * _Nonnull)algorithm parameters:(TKTokenKeyExchangeParameters * _Nonnull)parameters error:(NSError * _Nullable * _Nullable)error;
[Export ("tokenSession:performKeyExchangeWithPublicKey:usingKey:algorithm:parameters:error:")]
[return: NullAllowed]
NSData PerformKeyExchangeWithPublicKey (TKTokenSession session, NSData otherPartyPublicKeyData, NSObject objectID, TKTokenKeyAlgorithm algorithm, TKTokenKeyExchangeParameters parameters, [NullAllowed] out NSError error);
}
// @interface TKToken : NSObject
[BaseType (typeof (NSObject))]
[DisableDefaultCtor]
interface TKToken
{
// -(instancetype _Nonnull)initWithTokenDriver:(TKTokenDriver * _Nonnull)tokenDriver instanceID:(NSString * _Nonnull)instanceID __attribute__((objc_designated_initializer));
[Export ("initWithTokenDriver:instanceID:")]
[DesignatedInitializer]
IntPtr Constructor (TKTokenDriver tokenDriver, string instanceID);
// @property (readonly) TKTokenDriver * _Nonnull tokenDriver;
[Export ("tokenDriver")]
TKTokenDriver TokenDriver { get; }
[Wrap ("WeakDelegate")]
[NullAllowed]
TKTokenDelegate Delegate { get; set; }
// @property (weak) id<TKTokenDelegate> _Nullable delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @property (readonly) TKTokenKeychainContents * _Nullable keychainContents;
[NullAllowed, Export ("keychainContents")]
TKTokenKeychainContents KeychainContents { get; }
}
// @protocol TKTokenDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof (NSObject))]
interface TKTokenDelegate
{
// @required -(TKTokenSession * _Nullable)token:(TKToken * _Nonnull)token createSessionWithError:(NSError * _Nullable * _Nullable)error;
[Abstract]
[Export ("token:createSessionWithError:")]
[return: NullAllowed]
TKTokenSession Token (TKToken token, [NullAllowed] out NSError error);
// @optional -(void)token:(TKToken * _Nonnull)token terminateSession:(TKTokenSession * _Nonnull)session;
[Export ("token:terminateSession:")]
void Token (TKToken token, TKTokenSession session);
}
// @interface TKTokenDriver : NSObject
[BaseType (typeof (NSObject))]
interface TKTokenDriver
{
[Wrap ("WeakDelegate")]
[NullAllowed]
TKTokenDriverDelegate Delegate { get; set; }
// @property (weak) id<TKTokenDriverDelegate> _Nullable delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
}
// @protocol TKTokenDriverDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof (NSObject))]
interface TKTokenDriverDelegate
{
// @optional -(void)tokenDriver:(TKTokenDriver * _Nonnull)driver terminateToken:(TKToken * _Nonnull)token;
[Export ("tokenDriver:terminateToken:")]
void TerminateToken (TKTokenDriver driver, TKToken token);
}
// @interface TKTokenAuthOperation : NSObject <NSSecureCoding>
[BaseType (typeof (NSObject))]
interface TKTokenAuthOperation : INSSecureCoding
{
// -(BOOL)finishWithError:(NSError * _Nullable * _Nullable)error;
[Export ("finishWithError:")]
bool FinishWithError ([NullAllowed] out NSError error);
}
// @interface TKTokenPasswordAuthOperation : TKTokenAuthOperation
[BaseType (typeof (TKTokenAuthOperation))]
interface TKTokenPasswordAuthOperation
{
// @property (copy) NSString * _Nullable password;
[NullAllowed, Export ("password")]
string Password { get; set; }
}
// @interface TKTokenKeychainItem : NSObject
[BaseType (typeof (NSObject))]
[DisableDefaultCtor]
interface TKTokenKeychainItem
{
// -(instancetype _Nonnull)initWithObjectID:(TKTokenObjectID _Nonnull)objectID __attribute__((objc_designated_initializer));
[Export ("initWithObjectID:")]
[DesignatedInitializer]
IntPtr Constructor (NSObject objectID);
// @property (readonly, copy) TKTokenObjectID _Nonnull objectID;
[Export ("objectID", ArgumentSemantic.Copy)]
NSObject ObjectID { get; }
// @property (copy) NSString * _Nullable label;
[NullAllowed, Export ("label")]
string Label { get; set; }
// @property (copy) NSDictionary<NSNumber *,TKTokenOperationConstraint> * _Nullable constraints;
[NullAllowed, Export ("constraints", ArgumentSemantic.Copy)]
NSDictionary<NSNumber, NSObject> Constraints { get; set; }
}
// @interface TKTokenKeychainCertificate : TKTokenKeychainItem
[BaseType (typeof (TKTokenKeychainItem))]
interface TKTokenKeychainCertificate
{
// -(instancetype _Nullable)initWithCertificate:(SecCertificateRef _Nonnull)certificateRef objectID:(TKTokenObjectID _Nonnull)objectID __attribute__((objc_designated_initializer));
[Export ("initWithCertificate:objectID:")]
[DesignatedInitializer]
unsafe IntPtr Constructor (IntPtr certificateRef, NSObject objectID);
// @property (readonly, copy) NSData * _Nonnull data;
[Export ("data", ArgumentSemantic.Copy)]
NSData Data { get; }
}
// @interface TKTokenKeychainKey : TKTokenKeychainItem
[BaseType (typeof (TKTokenKeychainItem))]
interface TKTokenKeychainKey
{
// -(instancetype _Nullable)initWithCertificate:(SecCertificateRef _Nullable)certificateRef objectID:(TKTokenObjectID _Nonnull)objectID __attribute__((objc_designated_initializer));
[Export ("initWithCertificate:objectID:")]
[DesignatedInitializer]
unsafe IntPtr Constructor ([NullAllowed] IntPtr certificateRef, NSObject objectID);
// @property (copy) NSString * _Nonnull keyType;
[Export ("keyType")]
string KeyType { get; set; }
// @property (copy) NSData * _Nullable applicationTag;
[NullAllowed, Export ("applicationTag", ArgumentSemantic.Copy)]
NSData ApplicationTag { get; set; }
// @property NSInteger keySizeInBits;
[Export ("keySizeInBits")]
nint KeySizeInBits { get; set; }
// @property (copy) NSData * _Nullable publicKeyData;
[NullAllowed, Export ("publicKeyData", ArgumentSemantic.Copy)]
NSData PublicKeyData { get; set; }
// @property (copy) NSData * _Nullable publicKeyHash;
[NullAllowed, Export ("publicKeyHash", ArgumentSemantic.Copy)]
NSData PublicKeyHash { get; set; }
// @property BOOL canDecrypt;
[Export ("canDecrypt")]
bool CanDecrypt { get; set; }
// @property BOOL canSign;
[Export ("canSign")]
bool CanSign { get; set; }
// @property BOOL canPerformKeyExchange;
[Export ("canPerformKeyExchange")]
bool CanPerformKeyExchange { get; set; }
// @property (getter = isSuitableForLogin) BOOL suitableForLogin;
[Export ("suitableForLogin")]
bool SuitableForLogin { [Bind ("isSuitableForLogin")] get; set; }
}
// @interface TKTokenKeychainContents : NSObject
[BaseType (typeof (NSObject))]
[DisableDefaultCtor]
interface TKTokenKeychainContents
{
// -(void)fillWithItems:(NSArray<TKTokenKeychainItem *> * _Nonnull)items;
[Export ("fillWithItems:")]
void FillWithItems (TKTokenKeychainItem [] items);
// @property (readonly, copy) NSArray<TKTokenKeychainItem *> * _Nonnull items;
[Export ("items", ArgumentSemantic.Copy)]
TKTokenKeychainItem [] Items { get; }
// -(TKTokenKeychainKey * _Nullable)keyForObjectID:(TKTokenObjectID _Nonnull)objectID error:(NSError * _Nullable * _Nullable)error;
[Export ("keyForObjectID:error:")]
[return: NullAllowed]
TKTokenKeychainKey KeyForObjectID (NSObject objectID, [NullAllowed] out NSError error);
// -(TKTokenKeychainCertificate * _Nullable)certificateForObjectID:(TKTokenObjectID _Nonnull)objectID error:(NSError * _Nullable * _Nullable)error;
[Export ("certificateForObjectID:error:")]
[return: NullAllowed]
TKTokenKeychainCertificate CertificateForObjectID (NSObject objectID, [NullAllowed] out NSError error);
}
// @interface TKTokenSmartCardPINAuthOperation : TKTokenAuthOperation
[BaseType (typeof (TKTokenAuthOperation))]
interface TKTokenSmartCardPINAuthOperation
{
// @property TKSmartCardPINFormat * _Nonnull PINFormat;
[Export ("PINFormat", ArgumentSemantic.Assign)]
TKSmartCardPINFormat PINFormat { get; set; }
// @property (copy) NSData * _Nullable APDUTemplate;
[NullAllowed, Export ("APDUTemplate", ArgumentSemantic.Copy)]
NSData APDUTemplate { get; set; }
// @property NSInteger PINByteOffset;
[Export ("PINByteOffset")]
nint PINByteOffset { get; set; }
// @property TKSmartCard * _Nullable smartCard;
[NullAllowed, Export ("smartCard", ArgumentSemantic.Assign)]
TKSmartCard SmartCard { get; set; }
// @property (copy) NSString * _Nullable PIN;
[NullAllowed, Export ("PIN")]
string PIN { get; set; }
}
// @interface TKSmartCardTokenSession : TKTokenSession
[BaseType (typeof (TKTokenSession))]
interface TKSmartCardTokenSession
{
// @property (readonly) TKSmartCard * _Nonnull smartCard;
[Export ("smartCard")]
TKSmartCard SmartCard { get; }
}
// @interface TKSmartCardToken : TKToken
[BaseType (typeof (TKToken))]
interface TKSmartCardToken
{
// -(instancetype _Nonnull)initWithSmartCard:(TKSmartCard * _Nonnull)smartCard AID:(NSData * _Nullable)AID instanceID:(NSString * _Nonnull)instanceID tokenDriver:(TKSmartCardTokenDriver * _Nonnull)tokenDriver __attribute__((objc_designated_initializer));
[Export ("initWithSmartCard:AID:instanceID:tokenDriver:")]
[DesignatedInitializer]
IntPtr Constructor (TKSmartCard smartCard, [NullAllowed] NSData AID, string instanceID, TKSmartCardTokenDriver tokenDriver);
// @property (readonly) NSData * _Nullable AID;
[NullAllowed, Export ("AID")]
NSData AID { get; }
}
// @interface TKSmartCardTokenDriver : TKTokenDriver
[BaseType (typeof (TKTokenDriver))]
interface TKSmartCardTokenDriver
{
}
// @protocol TKSmartCardTokenDriverDelegate <TKTokenDriverDelegate>
//[Protocol, Model]
//interface TKSmartCardTokenDriverDelegate : ITKTokenDriverDelegate
//{
// // @required -(TKSmartCardToken * _Nullable)tokenDriver:(TKSmartCardTokenDriver * _Nonnull)driver createTokenForSmartCard:(TKSmartCard * _Nonnull)smartCard AID:(NSData * _Nullable)AID error:(NSError * _Nullable * _Nullable)error;
// [Abstract]
// [Export ("tokenDriver:createTokenForSmartCard:AID:error:")]
// [return: NullAllowed]
// TKSmartCardToken CreateTokenForSmartCard (TKSmartCardTokenDriver driver, TKSmartCard smartCard, [NullAllowed] NSData AID, [NullAllowed] out NSError error);
//}
// @interface TKTokenWatcher : NSObject
[BaseType (typeof (NSObject))]
interface TKTokenWatcher
{
// @property (readonly) NSArray<NSString *> * _Nonnull tokenIDs;
[Export ("tokenIDs")]
string [] TokenIDs { get; }
// -(instancetype _Nonnull)initWithInsertionHandler:(void (^ _Nonnull)(NSString * _Nonnull))insertionHandler __attribute__((availability(ios, deprecated=10.13))) __attribute__((availability(ios, introduced=10.12))) __attribute__((availability(macos, deprecated=10.13))) __attribute__((availability(macos, introduced=10.12)));
[Deprecated (PlatformName.iOS, 10, 13, message: "Use 'setInsertionHandler' instead")]
[Deprecated (PlatformName.MacOSX, 10, 13, message: "Use 'setInsertionHandler' instead")]
[Export ("initWithInsertionHandler:")]
IntPtr Constructor (Action<NSString> insertionHandler);
// -(void)setInsertionHandler:(void (^ _Nonnull)(NSString * _Nonnull))insertionHandler __attribute__((availability(ios, introduced=10.13))) __attribute__((availability(macos, introduced=10.13)));
[Export ("setInsertionHandler:")]
void SetInsertionHandler (Action<NSString> insertionHandler);
// -(void)addRemovalHandler:(void (^ _Nonnull)(NSString * _Nonnull))removalHandler forTokenID:(NSString * _Nonnull)tokenID;
[Export ("addRemovalHandler:forTokenID:")]
void AddRemovalHandler (Action<NSString> removalHandler, string tokenID);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
namespace FploBandWeights
{
class BandWeightsProgram
{
public static void Main(string[] args)
{
new BandWeightsProgram().Run(args);
}
string[] splitString = new string[] { " " };
string[] doubleSpaceSplit = new string[] { " " };
List<StateInfo> states = new List<StateInfo>();
List<int> plots = new List<int>();
string bandFile = "+band";
string weightsFile = "+bweights";
void Run(string[] args)
{
if (args.Length == 1)
weightsFile = args[0];
LoadStateInfo();
RunMenu();
Console.Write("Enter output filename (weights.agr) : ");
string file = Console.ReadLine();
if (string.IsNullOrEmpty(file))
file = "weights.agr";
Console.WriteLine();
SaveBandWeights(file);
}
private void LoadStateInfo()
{
using (var weights = new StreamReader(weightsFile))
{
string firstLine = weights.ReadLine();
string secondLine = weights.ReadLine();
string[] data = secondLine.Split(doubleSpaceSplit, StringSplitOptions.RemoveEmptyEntries);
if (data[0].Trim() != "#" ||
data[1].Trim() != "ik" ||
data[2].Trim() != "e(k,n)")
{
Console.Error.WriteLine("Could not understand input file.");
Environment.Exit(1);
}
for (int i = 3; i < data.Length; i++)
{
int index = i - 2;
StateInfo info = new StateInfo { Index = index, Name = data[i] };
states.Add(info);
}
Console.WriteLine("Found {0} states.", states.Count);
}
}
private void RunMenu()
{
bool done = false;
Console.Clear();
while (!done)
{
Console.WriteLine("Menu:");
Console.WriteLine();
Console.WriteLine(" a. Add weight to plot");
Console.WriteLine(" d. Delete weight to plot");
Console.WriteLine(" f. Select different band file.");
Console.WriteLine(" r. Rescan file");
Console.WriteLine(" x. Exit and save to agr file.");
Console.WriteLine();
WritePlots();
ConsoleKeyInfo key = Console.ReadKey(true);
Console.WriteLine();
switch (key.Key)
{
case ConsoleKey.A:
AddWeight();
break;
case ConsoleKey.D:
DeleteWeight();
break;
case ConsoleKey.F:
SelectFile();
break;
case ConsoleKey.R:
RescanFile();
break;
case ConsoleKey.X:
done = true;
break;
}
Console.WriteLine();
}
}
private void RescanFile()
{
LoadStateInfo();
}
private void SelectFile()
{
Console.Write("Enter band file: ");
bandFile = Console.ReadLine();
Console.Write("Enter bweights file: ");
weightsFile = Console.ReadLine();
RescanFile();
}
private void DeleteWeight()
{
Console.Write("Enter index to delete (blank to cancel): ");
string entry = Console.ReadLine().Trim();
if (string.IsNullOrEmpty(entry))
return;
int result;
if (int.TryParse(entry, out result) == false)
{
Console.WriteLine("That is not a valid entry. Your entry must be numeric.");
return;
}
if (plots.Contains(result))
{
plots.Remove(result);
}
else
{
Console.WriteLine("Could not find the specified index.");
}
}
private void AddWeight()
{
Console.Write("Enter filter (blank for none): ");
string filter = Console.ReadLine();
Console.WriteLine();
foreach (var state in states)
{
if (string.IsNullOrEmpty(filter) == false)
{
if (state.Name.Contains(filter) == false)
continue;
}
Console.WriteLine("{0} : {1}", state.Index, state.Name);
}
Console.WriteLine();
Console.Write("Enter index (blank to cancel): ");
string entry = Console.ReadLine().Trim();
if (string.IsNullOrEmpty(entry))
return;
int[] result = null;
try
{
result = GetIntVals(entry);
}
catch
{
Console.WriteLine("That is not a valid entry. Your entry must be numeric.");
return;
}
for (int i = 0; i < result.Length; i++)
{
if (plots.Contains(result[i]))
continue;
plots.Add(result[i]);
}
}
private int[] GetIntVals(string entry)
{
string[] vals = entry.Split(splitString, StringSplitOptions.RemoveEmptyEntries);
return (from x in vals select int.Parse(x)).ToArray();
}
private void WritePlots()
{
if (plots.Count != 0)
{
Console.WriteLine("Current selected weights: ");
plots.ForEach(x => { Console.WriteLine(" {0} : {1}", x, State(x).Name); });
Console.WriteLine();
}
}
private StateInfo State(int index)
{
return states.First(x => x.Index == index);
}
List<SymmetryPoint> pts = new List<SymmetryPoint>();
List<AgrDataset> data = new List<AgrDataset>();
private void SaveBandWeights(string file)
{
ReadPoints();
ReadBands();
ReadWeights();
Console.Write("Writing to {0}...", file);
AgrWriter.Write(file, data, pts);
Console.WriteLine(" done.");
}
private void ReadWeights()
{
Console.WriteLine("Reading weights from {0} file.", weightsFile);
int numBands = 0;
int numPoints = 0;
int ptCount = 0;
using (var r = new StreamReader(weightsFile))
{
string first = r.ReadLine();
if (first.StartsWith("#") == false)
throw new Exception("Could not read bands file.");
first = first.Substring(1);
double[] vals = GetVals(first);
numPoints = (int)(vals[2] + 0.5);
numBands = (int)(vals[4] + 0.5);
r.ReadLine();
AgrDataset[] data = new AgrDataset[plots.Count];
for (int i = 0; i < plots.Count; i++)
{
data[i] = new AgrDataset();
data[i].DatasetType = DatasetType.xysize;
data[i].Legend = State(plots[i]).Name;
data[i].LineStyle = LineStyle.None;
data[i].Symbol = Symbol.Circle;
data[i].SymbolColor = (GraceColor)i + 1;
data[i].SymbolFillColor = (GraceColor)i + 1;
data[i].SymbolFill = SymbolFill.Solid;
}
const double scaleFactor = 1.5;
for (int i = 0; i < numPoints; i++)
{
for (int j = 0; j < numBands; j++)
{
string line = r.ReadLine();
vals = GetVals(line);
double x = vals[0];
double y = vals[1];
for (int k = 0; k < plots.Count; k++)
{
int index = plots[k] + 1;
AgrDataPoint dp = new AgrDataPoint { X = x, Y = y };
dp.Weight = vals[index] * scaleFactor;
if (dp.Weight < 0.03)
continue;
data[k].Data.Add(dp);
ptCount += 1;
}
}
}
this.data.AddRange(data);
}
Console.WriteLine("Found {0} bands, with {1} points with weight.", numBands, ptCount);
Console.WriteLine();
}
private void ReadBands()
{
Console.WriteLine("Reading bands from {0} file.", bandFile);
int numBands = 0;
int numPoints = 0;
using (var r = new StreamReader(bandFile))
{
string first = r.ReadLine();
if (first.StartsWith("#") == false)
throw new Exception("Could not read bands file.");
first = first.Substring(1);
double[] vals = GetVals(first);
numPoints = (int)(vals[2] + 0.5);
numBands = (int)(vals[4] + 0.5);
AgrDataset[] data = new AgrDataset[numBands];
for (int j = 0; j < numBands; j++)
{
data[j] = new AgrDataset();
}
for (int i = 0; i < numPoints; i++)
{
// skip comment
r.ReadLine();
string line = r.ReadLine();
vals = GetVals(line);
for (int j = 0; j < numBands; j++)
{
AgrDataPoint dp = new AgrDataPoint();
dp.X = vals[0];
dp.Y = vals[j+1];
data[j].Data.Add(dp);
}
}
this.data.AddRange(data);
}
Console.WriteLine("Found {0} bands, with {1} k-points.", numBands, numPoints);
Console.WriteLine();
}
private double[] GetVals(string line)
{
string[] items = line.Split(splitString, StringSplitOptions.RemoveEmptyEntries);
return (from x in items select double.Parse(x)).ToArray();
}
private void ReadPoints()
{
Console.WriteLine("Reading points from +points file.");
using (var r = new StreamReader("+points"))
{
string first = r.ReadLine();
if (first.StartsWith("#") == false)
throw new Exception("Could not understand +points file.");
first = first.Substring(1);
int count = int.Parse(first);
for (int i = 0; i < count; i++)
{
string nameLine = r.ReadLine().Trim();
string numLine = r.ReadLine().Trim();
r.ReadLine();
r.ReadLine();
string trimedName = nameLine.Substring(3, nameLine.Length - 4);
string name = trimedName.Trim();
name = name.Replace("$~", @"\x");
name = name.Replace("$_", @"\s");
name = name.Replace("$^", @"\S");
name = name.Replace("$.", @"\N");
int index = numLine.IndexOf(' ');
double val = double.Parse(numLine.Substring(0, index));
SymmetryPoint pt = new SymmetryPoint { Location = val, Name = name };
pts.Add(pt);
}
}
Console.WriteLine("Found {0} symmetry points.", pts.Count);
Console.WriteLine();
}
}
}
| |
/*
* Copyright (C) 2005-2016 Christoph Rupp (chris@crupp.de).
* All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See the file COPYING for License information.
*/
namespace Upscaledb
{
/// <summary>
/// Upscaledb constants - error codes and flags
/// </summary>
public sealed class UpsConst
{
private UpsConst() {
}
/// <summary>Operation completed successfully</summary>
public const int UPS_SUCCESS = 0;
/// <summary>Invalid record size</summary>
public const int UPS_INV_RECORD_SIZE = -2;
/// <summary>Invalid key size</summary>
public const int UPS_INV_KEY_SIZE = -3;
/// <summary>Invalid key size</summary>
public const int UPS_INV_KEYSIZE = -3;
/// <summary>Invalid page size (must be 1024 or a multiple of 2048)</summary>
public const int UPS_INV_PAGESIZE = -4;
/// <summary>Memory allocation failed - out of memory</summary>
public const int UPS_OUT_OF_MEMORY = -6;
/// <summary>Invalid function parameter</summary>
public const int UPS_INV_PARAMETER = -8;
/// <summary>Invalid file header</summary>
public const int UPS_INV_FILE_HEADER = -9;
/// <summary>Invalid file version</summary>
public const int UPS_INV_FILE_VERSION = -10;
/// <summary>Key was not found</summary>
public const int UPS_KEY_NOT_FOUND = -11;
/// <summary>Tried to insert a key which already exists</summary>
public const int UPS_DUPLICATE_KEY = -12;
/// <summary>Internal Database integrity violated</summary>
public const int UPS_INTEGRITY_VIOLATED = -13;
/// <summary>Internal upscaledb error</summary>
public const int UPS_INTERNAL_ERROR = -14;
/// <summary>Tried to modify the Database, but the file was opened as read-only</summary>
public const int UPS_WRITE_PROTECTED = -15;
/// <summary>Database record not found</summary>
public const int UPS_BLOB_NOT_FOUND = -16;
/// <summary>Prefix comparison function needs more data</summary>
public const int UPS_PREFIX_REQUEST_FULLKEY = -17;
/// <summary>Generic file I/O error</summary>
public const int UPS_IO_ERROR = -18;
/// <summary>Function is not yet implemented</summary>
public const int UPS_NOT_IMPLEMENTED = -20;
/// <summary>File not found</summary>
public const int UPS_FILE_NOT_FOUND = -21;
/// <summary>Operation would block</summary>
public const int UPS_WOULD_BLOCK = -22;
/// <summary>Object was not initialized correctly</summary>
public const int UPS_NOT_READY = -23;
/// <summary>Database limits reached</summary>
public const int UPS_LIMITS_REACHED = -24;
/// <summary>Object was already initialized</summary>
public const int UPS_ALREADY_INITIALIZED = -27;
/// <summary>Database needs recovery</summary>
public const int UPS_NEED_RECOVERY = -28;
/// <summary>Cursor must be closed prior to Transaction abort/commit</summary>
public const int UPS_CURSOR_STILL_OPEN = -29;
/// <summary>Operation conflicts with another Transaction</summary>
public const int UPS_TXN_CONFLICT = -31;
/// <summary>Database cannot be closed because it is modified in a Transaction</summary>
public const int UPS_TXN_STIL_OPEN = -33;
/// <summary>Cursor does not point to a valid item</summary>
public const int UPS_CURSOR_IS_NIL = -100;
/// <summary>Database not found</summary>
public const int UPS_DATABASE_NOT_FOUND = -200;
/// <summary>Database name already exists</summary>
public const int UPS_DATABASE_ALREADY_EXISTS = -201;
/// <summary>Database already open, or: Database handle is already initialized</summary>
public const int UPS_DATABASE_ALREADY_OPEN = -202;
/// <summary>Environment already open, or: Environment handle is already initialized</summary>
public const int UPS_ENVIRONMENT_ALREADY_OPEN = -203;
/// <summary>Invalid log file header</summary>
public const int UPS_LOG_INV_FILE_HEADER = -300;
// Error handling levels
/// <summary>A debug message</summary>
public const int UPS_DEBUG_LEVEL_DEBUG = 0;
/// <summary>A normal error message</summary>
public const int UPS_DEBUG_LEVEL_NORMAL = 1;
/// <summary>A fatal error message</summary>
public const int UPS_DEBUG_LEVEL_FATAL = 3;
// Transaction constants
/// <summary>Flag for Transaction.Begin</summary>
public const int UPS_TXN_READ_ONLY = 1;
/// <summary>Flag for Transaction.Commit</summary>
public const int UPS_TXN_FORCE_WRITE = 1;
// Create/Open flags
/// <summary>Flag for Database.Open, Database.Create</summary>
public const int UPS_ENABLE_FSYNC = 0x001;
/// <summary>Flag for Database.Open</summary>
public const int UPS_READ_ONLY = 0x004;
/// <summary>Flag for Database.Create</summary>
public const int UPS_IN_MEMORY = 0x00080;
/// <summary>Flag for Database.Open, Database.Create</summary>
public const int UPS_DISABLE_MMAP = 0x00200;
/// <summary>Flag for Database.Open, Database.Create</summary>
public const int UPS_DISABLE_FREELIST_FLUSH = 0x00800;
/// <summary>Flag for Database.Create</summary>
public const int UPS_RECORD_NUMBER32 = 0x01000;
/// <summary>Flag for Database.Create</summary>
public const int UPS_RECORD_NUMBER64 = 0x02000;
/// <summary>Flag for Database.Create (deprecated)</summary>
public const int UPS_RECORD_NUMBER = UPS_RECORD_NUMBER64;
/// <summary>Flag for Database.Create</summary>
public const int UPS_ENABLE_DUPLICATE_KEYS = 0x04000;
/// <summary>Flag for Database.Create</summary>
public const int UPS_ENABLE_RECOVERY = UPS_ENABLE_TRANSACTIONS;
/// <summary>Flag for Database.Open</summary>
public const int UPS_AUTO_RECOVERY = 0x10000;
/// <summary>Flag for Database.Create, Database.Open</summary>
public const int UPS_ENABLE_TRANSACTIONS = 0x20000;
/// <summary>Flag for Database.Create, Database.Open</summary>
public const int UPS_CACHE_UNLIMITED = 0x40000;
/// <summary>Flag for Environment.Create, Environment.Open</summary>
public const int UPS_FLUSH_WHEN_COMMITTED = 0x01000000;
/// <summary>Flag for Environment.Create, Environment.Open</summary>
public const int UPS_ENABLE_CRC32 = 0x02000000;
// Extended parameters
/// <summary>Parameter name for Environment.Open,
/// Environment.Create</summary>
public const int UPS_PARAM_CACHE_SIZE = 0x00100;
/// <summary>Parameter name for Environment.Open,
/// Environment.Create (deprecated)</summary>
public const int UPS_PARAM_CACHESIZE = 0x00100;
/// <summary>Parameter name for Environment.Create</summary>
public const int UPS_PARAM_PAGE_SIZE = 0x00101;
/// <summary>Parameter name for Environment.Create (deprecated)</summary>
public const int UPS_PARAM_PAGESIZE = 0x00101;
/// <summary>Parameter name for Database.Create</summary>
public const int UPS_PARAM_KEY_SIZE = 0x00102;
/// <summary>Parameter name for Database.Create (deprecated)</summary>
public const int UPS_PARAM_KEYSIZE = 0x00102;
/// <summary>Parameter name for GetParameters</summary>
public const int UPS_PARAM_MAX_DATABASES = 0x00103;
/// <summary>Parameter name for Database.Create</summary>
public const int UPS_PARAM_KEY_TYPE = 0x00104;
/// <summary>Parameter name for Environment.Open, Environment.Create</summary>
public const int UPS_PARAM_NETWORK_TIMEOUT_SEC = 0x00000107;
/// <summary>Parameter name for Database.Create</summary>
public const int UPS_PARAM_RECORD_SIZE = 0x00108;
/// <summary>Parameter name for Environment.Create,
/// Environment.Open</summary>
public const int UPS_PARAM_FILE_SIZE_LIMIT = 0x00109;
/// <summary>Parameter name for Database.Create</summary>
public const int UPS_PARAM_CUSTOM_COMPARE_NAME = 0x00111;
// Database operations
/// <summary>Parameter for GetParameters</summary>
public const int UPS_PARAM_FLAGS = 0x00000200;
/// <summary>Parameter for GetParameters</summary>
public const int UPS_PARAM_FILEMODE = 0x00000201;
/// <summary>Parameter for GetParameters</summary>
public const int UPS_PARAM_FILENAME = 0x00000202;
/// <summary>Parameter for GetParameters</summary>
public const int UPS_PARAM_DATABASE_NAME = 0x00000203;
/// <summary>Parameter for GetParameters</summary>
public const int UPS_PARAM_MAX_KEYS_PER_PAGE = 0x00000204;
/// <summary>Value for UPS_PARAM_KEY_SIZE</summary>
public const int UPS_KEY_SIZE_UNLIMITED = 0xffff;
/// <summary>Value for UPS_PARAM_RECORD_SIZE</summary>
public const long UPS_RECORD_SIZE_UNLIMITED = 0xffffffff;
/// <summary>Value for Environment.Create, /// Environment.Open</summary>
public const int UPS_PARAM_JOURNAL_COMPRESSION = 0x1000;
/// <summary>Value for Database.Create, /// Database.Open</summary>
public const int UPS_PARAM_RECORD_COMPRESSION = 0x1001;
/// <summary>Value for Database.Create, /// Database.Open</summary>
public const int UPS_PARAM_KEY_COMPRESSION = 0x1002;
/// <summary>"null" compression</summary>
public const int UPS_COMPRESSION_NONE = 0;
/// <summary>zlib compression</summary>
public const int UPS_COMPRESSION_ZLIB = 1;
/// <summary>snappy compression</summary>
public const int UPS_COMPRESSION_SNAPPY = 2;
/// <summary>lzf compression</summary>
public const int UPS_COMPRESSION_LZF = 3;
/// <summary>lzop compression</summary>
public const int UPS_COMPRESSION_LZOP = 4;
// Database operations
/// <summary>Flag for Database.Insert, Cursor.Insert</summary>
public const int UPS_OVERWRITE = 0x0001;
/// <summary>Flag for Database.Insert, Cursor.Insert</summary>
public const int UPS_DUPLICATE = 0x0002;
/// <summary>Flag for Cursor.Insert</summary>
public const int UPS_DUPLICATE_INSERT_BEFORE = 0x0004;
/// <summary>Flag for Cursor.Insert</summary>
public const int UPS_DUPLICATE_INSERT_AFTER = 0x0008;
/// <summary>Flag for Cursor.Insert</summary>
public const int UPS_DUPLICATE_INSERT_FIRST = 0x0010;
/// <summary>Flag for Cursor.Insert</summary>
public const int UPS_DUPLICATE_INSERT_LAST = 0x0020;
/// <summary>Flag for Database.Find</summary>
public const int UPS_DIRECT_ACCESS = 0x0040;
/// <summary>Flag for Database.Insert</summary>
public const int UPS_HINT_APPEND = 0x0080000;
/// <summary>Flag for Database.Insert</summary>
public const int UPS_HINT_PREPEND = 0x0100000;
/// <summary>Flag for Database.Close</summary>
public const int UPS_AUTO_CLEANUP = 1;
/// <summary>Private flag for testing</summary>
public const int UPS_DONT_CLEAR_LOG = 2;
/// <summary>Flag for Database.Close</summary>
public const int UPS_TXN_AUTO_ABORT = 4;
/// <summary>Flag for Database.Close</summary>
public const int UPS_TXN_AUTO_COMMIT = 8;
// Cursor operations
/// <summary>Flag for Cursor.Move</summary>
public const int UPS_CURSOR_FIRST = 1;
/// <summary>Flag for Cursor.Move</summary>
public const int UPS_CURSOR_LAST = 2;
/// <summary>Flag for Cursor.Move</summary>
public const int UPS_CURSOR_NEXT = 4;
/// <summary>Flag for Cursor.Move</summary>
public const int UPS_CURSOR_PREVIOUS = 8;
/// <summary>Flag for Cursor.Move</summary>
public const int UPS_SKIP_DUPLICATES = 16;
/// <summary>Flag for Cursor.Move</summary>
public const int UPS_ONLY_DUPLICATES = 32;
// Cursor find flags
/// <summary>Flag for Cursor.Find</summary>
public const int UPS_FIND_EQ_MATCH = 0x4000;
/// <summary>Flag for Cursor.Find</summary>
public const int UPS_FIND_LT_MATCH = 0x1000;
/// <summary>Flag for Cursor.Find</summary>
public const int UPS_FIND_GT_MATCH = 0x2000;
/// <summary>Flag for Cursor.Find</summary>
public const int UPS_FIND_LEQ_MATCH = (UPS_FIND_LT_MATCH
| UPS_FIND_EQ_MATCH);
/// <summary>Flag for Cursor.Find</summary>
public const int UPS_FIND_GEQ_MATCH = (UPS_FIND_GT_MATCH
| UPS_FIND_EQ_MATCH);
/// <summary>A binary blob without type; sorted by memcmp</summary>
public const int UPS_TYPE_BINARY = 0;
/// <summary>A binary blob without type; sorted by callback function</summary>
public const int UPS_TYPE_CUSTOM = 1;
/// <summary>An unsigned 8-bit integer</summary>
public const int UPS_TYPE_UINT8 = 3;
/// <summary>An unsigned 16-bit integer</summary>
public const int UPS_TYPE_UINT16 = 5;
/// <summary>An unsigned 32-bit integer</summary>
public const int UPS_TYPE_UINT32 = 7;
/// <summary>An unsigned 64-bit integer</summary>
public const int UPS_TYPE_UINT64 = 9;
/// <summary>An 32-bit float</summary>
public const int UPS_TYPE_REAL32 = 11;
/// <summary>An 64-bit double</summary>
public const int UPS_TYPE_REAL64 = 12;
}
}
| |
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Diagnostics;
using System.Windows.Resources;
using System.Windows;
namespace WPCordovaClassLib.Cordova.Commands
{
/// <summary>
/// Provides access to isolated storage
/// </summary>
public class File : BaseCommand
{
// Error codes
public const int NOT_FOUND_ERR = 1;
public const int SECURITY_ERR = 2;
public const int ABORT_ERR = 3;
public const int NOT_READABLE_ERR = 4;
public const int ENCODING_ERR = 5;
public const int NO_MODIFICATION_ALLOWED_ERR = 6;
public const int INVALID_STATE_ERR = 7;
public const int SYNTAX_ERR = 8;
public const int INVALID_MODIFICATION_ERR = 9;
public const int QUOTA_EXCEEDED_ERR = 10;
public const int TYPE_MISMATCH_ERR = 11;
public const int PATH_EXISTS_ERR = 12;
// File system options
public const int TEMPORARY = 0;
public const int PERSISTENT = 1;
public const int RESOURCE = 2;
public const int APPLICATION = 3;
/// <summary>
/// Temporary directory name
/// </summary>
private readonly string TMP_DIRECTORY_NAME = "tmp";
/// <summary>
/// Represents error code for callback
/// </summary>
[DataContract]
public class ErrorCode
{
/// <summary>
/// Error code
/// </summary>
[DataMember(IsRequired = true, Name = "code")]
public int Code { get; set; }
/// <summary>
/// Creates ErrorCode object
/// </summary>
public ErrorCode(int code)
{
this.Code = code;
}
}
/// <summary>
/// Represents File action options.
/// </summary>
[DataContract]
public class FileOptions
{
/// <summary>
/// File path
/// </summary>
///
private string _fileName;
[DataMember(Name = "fileName")]
public string FilePath
{
get
{
return this._fileName;
}
set
{
int index = value.IndexOfAny(new char[] { '#', '?' });
this._fileName = index > -1 ? value.Substring(0, index) : value;
}
}
/// <summary>
/// Full entryPath
/// </summary>
[DataMember(Name = "fullPath")]
public string FullPath { get; set; }
/// <summary>
/// Directory name
/// </summary>
[DataMember(Name = "dirName")]
public string DirectoryName { get; set; }
/// <summary>
/// Path to create file/directory
/// </summary>
[DataMember(Name = "path")]
public string Path { get; set; }
/// <summary>
/// The encoding to use to encode the file's content. Default is UTF8.
/// </summary>
[DataMember(Name = "encoding")]
public string Encoding { get; set; }
/// <summary>
/// Uri to get file
/// </summary>
///
private string _uri;
[DataMember(Name = "uri")]
public string Uri
{
get
{
return this._uri;
}
set
{
int index = value.IndexOfAny(new char[] { '#', '?' });
this._uri = index > -1 ? value.Substring(0, index) : value;
}
}
/// <summary>
/// Size to truncate file
/// </summary>
[DataMember(Name = "size")]
public long Size { get; set; }
/// <summary>
/// Data to write in file
/// </summary>
[DataMember(Name = "data")]
public string Data { get; set; }
/// <summary>
/// Position the writing starts with
/// </summary>
[DataMember(Name = "position")]
public int Position { get; set; }
/// <summary>
/// Type of file system requested
/// </summary>
[DataMember(Name = "type")]
public int FileSystemType { get; set; }
/// <summary>
/// New file/directory name
/// </summary>
[DataMember(Name = "newName")]
public string NewName { get; set; }
/// <summary>
/// Destination directory to copy/move file/directory
/// </summary>
[DataMember(Name = "parent")]
public string Parent { get; set; }
/// <summary>
/// Options for getFile/getDirectory methods
/// </summary>
[DataMember(Name = "options")]
public CreatingOptions CreatingOpt { get; set; }
/// <summary>
/// Creates options object with default parameters
/// </summary>
public FileOptions()
{
this.SetDefaultValues(new StreamingContext());
}
/// <summary>
/// Initializes default values for class fields.
/// Implemented in separate method because default constructor is not invoked during deserialization.
/// </summary>
/// <param name="context"></param>
[OnDeserializing()]
public void SetDefaultValues(StreamingContext context)
{
this.Encoding = "UTF-8";
this.FilePath = "";
this.FileSystemType = -1;
}
}
/// <summary>
/// Stores image info
/// </summary>
[DataContract]
public class FileMetadata
{
[DataMember(Name = "fileName")]
public string FileName { get; set; }
[DataMember(Name = "fullPath")]
public string FullPath { get; set; }
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "lastModifiedDate")]
public string LastModifiedDate { get; set; }
[DataMember(Name = "size")]
public long Size { get; set; }
public FileMetadata(string filePath)
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (string.IsNullOrEmpty(filePath))
{
throw new FileNotFoundException("File doesn't exist");
}
else if (!isoFile.FileExists(filePath))
{
// attempt to get it from the resources
if (filePath.IndexOf("www") == 0)
{
Uri fileUri = new Uri(filePath, UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri);
if (streamInfo != null)
{
this.Size = streamInfo.Stream.Length;
this.FileName = filePath.Substring(filePath.LastIndexOf("/") + 1);
this.FullPath = filePath;
}
}
else
{
throw new FileNotFoundException("File doesn't exist");
}
}
else
{
//TODO get file size the other way if possible
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.Read, isoFile))
{
this.Size = stream.Length;
}
this.FullPath = filePath;
this.FileName = System.IO.Path.GetFileName(filePath);
this.LastModifiedDate = isoFile.GetLastWriteTime(filePath).DateTime.ToString();
}
this.Type = MimeTypeMapper.GetMimeType(this.FileName);
}
}
}
/// <summary>
/// Represents file or directory modification metadata
/// </summary>
[DataContract]
public class ModificationMetadata
{
/// <summary>
/// Modification time
/// </summary>
[DataMember]
public string modificationTime { get; set; }
}
/// <summary>
/// Represents file or directory entry
/// </summary>
[DataContract]
public class FileEntry
{
/// <summary>
/// File type
/// </summary>
[DataMember(Name = "isFile")]
public bool IsFile { get; set; }
/// <summary>
/// Directory type
/// </summary>
[DataMember(Name = "isDirectory")]
public bool IsDirectory { get; set; }
/// <summary>
/// File/directory name
/// </summary>
[DataMember(Name = "name")]
public string Name { get; set; }
/// <summary>
/// Full path to file/directory
/// </summary>
[DataMember(Name = "fullPath")]
public string FullPath { get; set; }
public bool IsResource { get; set; }
public static FileEntry GetEntry(string filePath, bool bIsRes=false)
{
FileEntry entry = null;
try
{
entry = new FileEntry(filePath, bIsRes);
}
catch (Exception ex)
{
Debug.WriteLine("Exception in GetEntry for filePath :: " + filePath + " " + ex.Message);
}
return entry;
}
//public static FileEntry GetEntry(Uri uri)
//{
// FileEntry entry = null;
// //try
// //{
// // this.Name = Path.GetFileName(uri.OriginalString);
// // entry = new FileEntry(uri.OriginalString);
// // entry
// //}
// return entry;
//}
/// <summary>
/// Creates object and sets necessary properties
/// </summary>
/// <param name="filePath"></param>
public FileEntry(string filePath, bool bIsRes = false)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentException();
}
if(filePath.Contains(" "))
{
Debug.WriteLine("FilePath with spaces :: " + filePath);
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
IsResource = bIsRes;
IsFile = isoFile.FileExists(filePath);
IsDirectory = isoFile.DirectoryExists(filePath);
if (IsFile)
{
this.Name = Path.GetFileName(filePath);
}
else if (IsDirectory)
{
this.Name = this.GetDirectoryName(filePath);
if (string.IsNullOrEmpty(Name))
{
this.Name = "/";
}
}
else
{
if (IsResource)
{
this.Name = Path.GetFileName(filePath);
}
else
{
throw new FileNotFoundException();
}
}
try
{
this.FullPath = filePath.Replace('\\', '/'); // new Uri(filePath).LocalPath;
}
catch (Exception)
{
this.FullPath = filePath;
}
}
}
/// <summary>
/// Extracts directory name from path string
/// Path should refer to a directory, for example \foo\ or /foo.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private string GetDirectoryName(string path)
{
if (String.IsNullOrEmpty(path))
{
return path;
}
string[] split = path.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
if (split.Length < 1)
{
return null;
}
else
{
return split[split.Length - 1];
}
}
}
/// <summary>
/// Represents info about requested file system
/// </summary>
[DataContract]
public class FileSystemInfo
{
/// <summary>
/// file system type
/// </summary>
[DataMember(Name = "name", IsRequired = true)]
public string Name { get; set; }
/// <summary>
/// Root directory entry
/// </summary>
[DataMember(Name = "root", EmitDefaultValue = false)]
public FileEntry Root { get; set; }
/// <summary>
/// Creates class instance
/// </summary>
/// <param name="name"></param>
/// <param name="rootEntry"> Root directory</param>
public FileSystemInfo(string name, FileEntry rootEntry = null)
{
Name = name;
Root = rootEntry;
}
}
[DataContract]
public class CreatingOptions
{
/// <summary>
/// Create file/directory if is doesn't exist
/// </summary>
[DataMember(Name = "create")]
public bool Create { get; set; }
/// <summary>
/// Generate an exception if create=true and file/directory already exists
/// </summary>
[DataMember(Name = "exclusive")]
public bool Exclusive { get; set; }
}
/// <summary>
/// File options
/// </summary>
private FileOptions fileOptions;
private bool LoadFileOptions(string options)
{
try
{
fileOptions = JSON.JsonHelper.Deserialize<FileOptions>(options);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return false;
}
return true;
}
// returns null value if it fails.
private string getSingleStringOption(string options)
{
string result = null;
try
{
result = JSON.JsonHelper.Deserialize<string[]>(options)[0];
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
}
return result;
}
/// <summary>
/// Gets amount of free space available for Isolated Storage
/// </summary>
/// <param name="options">No options is needed for this method</param>
public void getFreeDiskSpace(string options)
{
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isoFile.AvailableFreeSpace));
}
}
catch (IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
/// <summary>
/// Check if file exists
/// </summary>
/// <param name="options">File path</param>
public void testFileExists(string options)
{
IsDirectoryOrFileExist(options, false);
}
/// <summary>
/// Check if directory exists
/// </summary>
/// <param name="options">directory name</param>
public void testDirectoryExists(string options)
{
IsDirectoryOrFileExist(options, true);
}
/// <summary>
/// Check if file or directory exist
/// </summary>
/// <param name="options">File path/Directory name</param>
/// <param name="isDirectory">Flag to recognize what we should check</param>
public void IsDirectoryOrFileExist(string options, bool isDirectory)
{
if (!LoadFileOptions(options))
{
return;
}
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool isExist;
if (isDirectory)
{
isExist = isoFile.DirectoryExists(fileOptions.DirectoryName);
}
else
{
isExist = isoFile.FileExists(fileOptions.FilePath);
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isExist));
}
}
catch (IsolatedStorageException) // default handler throws INVALID_MODIFICATION_ERR
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
public void readAsDataURL(string options)
{
// exception+PluginResult are handled by getSingleStringOptions
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
string base64URL = null;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
string mimeType = MimeTypeMapper.GetMimeType(filePath);
using (IsolatedStorageFileStream stream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
string base64String = GetFileContent(stream);
base64URL = "data:" + mimeType + ";base64," + base64String;
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, base64URL));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
}
public void readAsText(string options)
{
// TODO: try/catch
string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options);
string filePath = optStrings[0];
string encStr = optStrings[1];
try
{
string text;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
//DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
readResourceAsText(options);
return;
}
Encoding encoding = Encoding.GetEncoding(encStr);
using (TextReader reader = new StreamReader(isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read), encoding))
{
text = reader.ReadToEnd();
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
/// <summary>
/// Reads application resource as a text
/// </summary>
/// <param name="options">Path to a resource</param>
public void readResourceAsText(string options)
{
string pathToResource;
try
{
string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options);
pathToResource = optStrings[0];
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
try
{
if (pathToResource.StartsWith("/"))
{
pathToResource = pathToResource.Remove(0, 1);
}
var resource = Application.GetResourceStream(new Uri(pathToResource, UriKind.Relative));
if (resource == null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
string text;
StreamReader streamReader = new StreamReader(resource.Stream);
text = streamReader.ReadToEnd();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
public void truncate(string options)
{
// TODO: try/catch
string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options);
string filePath = optStrings[0];
int size = int.Parse(optStrings[1]);
try
{
long streamLength = 0;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile))
{
if (0 <= size && size <= stream.Length)
{
stream.SetLength(size);
}
streamLength = stream.Length;
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
//write:["filePath","data","position"],
public void write(string options)
{
// TODO: try/catch
string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options);
string filePath = optStrings[0];
string data = optStrings[1];
int position = int.Parse(optStrings[2]);
try
{
if (string.IsNullOrEmpty(data))
{
Debug.WriteLine("Expected some data to be send in the write command to {0}", filePath);
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
// create the file if not exists
if (!isoFile.FileExists(filePath))
{
var file = isoFile.CreateFile(filePath);
file.Close();
}
using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile))
{
if (0 <= position && position <= stream.Length)
{
stream.SetLength(position);
}
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Seek(0, SeekOrigin.End);
writer.Write(data.ToCharArray());
}
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, data.Length));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
/// <summary>
/// Look up metadata about this entry.
/// </summary>
/// <param name="options">filePath to entry</param>
public void getMetadata(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.FileExists(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK,
new ModificationMetadata() { modificationTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString() }));
}
else if (isoFile.DirectoryExists(filePath))
{
string modTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = modTime }));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
}
/// <summary>
/// Returns a File that represents the current state of the file that this FileEntry represents.
/// </summary>
/// <param name="filePath">filePath to entry</param>
/// <returns></returns>
public void getFileMetadata(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
FileMetadata metaData = new FileMetadata(filePath);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, metaData));
}
catch (IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
}
/// <summary>
/// Look up the parent DirectoryEntry containing this Entry.
/// If this Entry is the root of IsolatedStorage, its parent is itself.
/// </summary>
/// <param name="options"></param>
public void getParent(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
if (string.IsNullOrEmpty(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
FileEntry entry;
if (isoFile.FileExists(filePath) || isoFile.DirectoryExists(filePath))
{
string path = this.GetParentDirectory(filePath);
entry = FileEntry.GetEntry(path);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
}
public void remove(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
if (filePath == "/" || filePath == "" || filePath == @"\")
{
throw new Exception("Cannot delete root file system") ;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.FileExists(filePath))
{
isoFile.DeleteFile(filePath);
}
else
{
if (isoFile.DirectoryExists(filePath))
{
isoFile.DeleteDirectory(filePath);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
}
public void removeRecursively(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
if (string.IsNullOrEmpty(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
}
else
{
removeDirRecursively(filePath);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
}
}
public void readEntries(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
if (string.IsNullOrEmpty(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.DirectoryExists(filePath))
{
string path = File.AddSlashToDirectory(filePath);
List<FileEntry> entries = new List<FileEntry>();
string[] files = isoFile.GetFileNames(path + "*");
string[] dirs = isoFile.GetDirectoryNames(path + "*");
foreach (string file in files)
{
entries.Add(FileEntry.GetEntry(path + file));
}
foreach (string dir in dirs)
{
entries.Add(FileEntry.GetEntry(path + dir + "/"));
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entries));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
}
public void requestFileSystem(string options)
{
// TODO: try/catch
double[] optVals = JSON.JsonHelper.Deserialize<double[]>(options);
double fileSystemType = optVals[0];
double size = optVals[1];
IsolatedStorageFile.GetUserStoreForApplication();
if (size > (10 * 1024 * 1024)) // 10 MB, compier will clean this up!
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR));
return;
}
try
{
if (size != 0)
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
long availableSize = isoFile.AvailableFreeSpace;
if (size > availableSize)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR));
return;
}
}
}
if (fileSystemType == PERSISTENT)
{
// TODO: this should be in it's own folder to prevent overwriting of the app assets, which are also in ISO
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("persistent", FileEntry.GetEntry("/"))));
}
else if (fileSystemType == TEMPORARY)
{
using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStorage.FileExists(TMP_DIRECTORY_NAME))
{
isoStorage.CreateDirectory(TMP_DIRECTORY_NAME);
}
}
string tmpFolder = "/" + TMP_DIRECTORY_NAME + "/";
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("temporary", FileEntry.GetEntry(tmpFolder))));
}
else if (fileOptions.FileSystemType == RESOURCE)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("resource")));
}
else if (fileOptions.FileSystemType == APPLICATION)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("application")));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
public void resolveLocalFileSystemURI(string options)
{
string uri = getSingleStringOption(options).Split('?')[0];
if (uri != null)
{
// a single '/' is valid, however, '/someDir' is not, but '/tmp//somedir' is valid
if (uri.StartsWith("/") && uri.IndexOf("//") < 0 && uri != "/")
{
Debug.WriteLine("Starts with / ::: " + uri);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR));
return;
}
try
{
// fix encoded spaces
string path = Uri.UnescapeDataString(uri);
FileEntry uriEntry = FileEntry.GetEntry(path);
if (uriEntry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, uriEntry));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
}
public void copyTo(string options)
{
TransferTo(options, false);
}
public void moveTo(string options)
{
TransferTo(options, true);
}
public void getFile(string options)
{
GetFileOrDirectory(options, false);
}
public void getDirectory(string options)
{
GetFileOrDirectory(options, true);
}
#region internal functionality
/// <summary>
/// Retrieves the parent directory name of the specified path,
/// </summary>
/// <param name="path">Path</param>
/// <returns>Parent directory name</returns>
private string GetParentDirectory(string path)
{
if (String.IsNullOrEmpty(path) || path == "/")
{
return "/";
}
if (path.EndsWith(@"/") || path.EndsWith(@"\"))
{
return this.GetParentDirectory(Path.GetDirectoryName(path));
}
string result = Path.GetDirectoryName(path);
if (result == null)
{
result = "/";
}
return result;
}
private void removeDirRecursively(string fullPath)
{
try
{
if (fullPath == "/")
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.DirectoryExists(fullPath))
{
string tempPath = File.AddSlashToDirectory(fullPath);
string[] files = isoFile.GetFileNames(tempPath + "*");
if (files.Length > 0)
{
foreach (string file in files)
{
isoFile.DeleteFile(tempPath + file);
}
}
string[] dirs = isoFile.GetDirectoryNames(tempPath + "*");
if (dirs.Length > 0)
{
foreach (string dir in dirs)
{
removeDirRecursively(tempPath + dir);
}
}
isoFile.DeleteDirectory(fullPath);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
private bool CanonicalCompare(string pathA, string pathB)
{
string a = pathA.Replace("//", "/");
string b = pathB.Replace("//", "/");
return a.Equals(b, StringComparison.OrdinalIgnoreCase);
}
/*
* copyTo:["fullPath","parent", "newName"],
* moveTo:["fullPath","parent", "newName"],
*/
private void TransferTo(string options, bool move)
{
// TODO: try/catch
string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options);
string fullPath = optStrings[0];
string parent = optStrings[1];
string newFileName = optStrings[2];
char[] invalids = Path.GetInvalidPathChars();
if (newFileName.IndexOfAny(invalids) > -1 || newFileName.IndexOf(":") > -1 )
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR));
return;
}
try
{
if ((parent == null) || (string.IsNullOrEmpty(parent)) || (string.IsNullOrEmpty(fullPath)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
string parentPath = File.AddSlashToDirectory(parent);
string currentPath = fullPath;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool isFileExist = isoFile.FileExists(currentPath);
bool isDirectoryExist = isoFile.DirectoryExists(currentPath);
bool isParentExist = isoFile.DirectoryExists(parentPath);
if ( ( !isFileExist && !isDirectoryExist ) || !isParentExist )
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
string newName;
string newPath;
if (isFileExist)
{
newName = (string.IsNullOrEmpty(newFileName))
? Path.GetFileName(currentPath)
: newFileName;
newPath = Path.Combine(parentPath, newName);
// sanity check ..
// cannot copy file onto itself
if (CanonicalCompare(newPath,currentPath)) //(parent + newFileName))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR));
return;
}
else if (isoFile.DirectoryExists(newPath))
{
// there is already a folder with the same name, operation is not allowed
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR));
return;
}
else if (isoFile.FileExists(newPath))
{ // remove destination file if exists, in other case there will be exception
isoFile.DeleteFile(newPath);
}
if (move)
{
isoFile.MoveFile(currentPath, newPath);
}
else
{
isoFile.CopyFile(currentPath, newPath, true);
}
}
else
{
newName = (string.IsNullOrEmpty(newFileName))
? currentPath
: newFileName;
newPath = Path.Combine(parentPath, newName);
if (move)
{
// remove destination directory if exists, in other case there will be exception
// target directory should be empty
if (!newPath.Equals(currentPath) && isoFile.DirectoryExists(newPath))
{
isoFile.DeleteDirectory(newPath);
}
isoFile.MoveDirectory(currentPath, newPath);
}
else
{
CopyDirectory(currentPath, newPath, isoFile);
}
}
FileEntry entry = FileEntry.GetEntry(newPath);
if (entry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
private bool HandleException(Exception ex)
{
bool handled = false;
if (ex is SecurityException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR));
handled = true;
}
else if (ex is FileNotFoundException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
handled = true;
}
else if (ex is ArgumentException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR));
handled = true;
}
else if (ex is IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR));
handled = true;
}
else if (ex is DirectoryNotFoundException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
handled = true;
}
return handled;
}
private void CopyDirectory(string sourceDir, string destDir, IsolatedStorageFile isoFile)
{
string path = File.AddSlashToDirectory(sourceDir);
bool bExists = isoFile.DirectoryExists(destDir);
if (!bExists)
{
isoFile.CreateDirectory(destDir);
}
destDir = File.AddSlashToDirectory(destDir);
string[] files = isoFile.GetFileNames(path + "*");
if (files.Length > 0)
{
foreach (string file in files)
{
isoFile.CopyFile(path + file, destDir + file,true);
}
}
string[] dirs = isoFile.GetDirectoryNames(path + "*");
if (dirs.Length > 0)
{
foreach (string dir in dirs)
{
CopyDirectory(path + dir, destDir + dir, isoFile);
}
}
}
private void GetFileOrDirectory(string options, bool getDirectory)
{
FileOptions fOptions = new FileOptions();
try
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
fOptions.FullPath = args[0];
fOptions.Path = args[1];
fOptions.CreatingOpt = JSON.JsonHelper.Deserialize<CreatingOptions>(args[2]);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
try
{
if ((string.IsNullOrEmpty(fOptions.Path)) || (string.IsNullOrEmpty(fOptions.FullPath)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
string path;
if (fOptions.Path.Split(':').Length > 2)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR));
return;
}
try
{
path = Path.Combine(fOptions.FullPath + "/", fOptions.Path);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR));
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool isFile = isoFile.FileExists(path);
bool isDirectory = isoFile.DirectoryExists(path);
bool create = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Create;
bool exclusive = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Exclusive;
if (create)
{
if (exclusive && (isoFile.FileExists(path) || isoFile.DirectoryExists(path)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, PATH_EXISTS_ERR));
return;
}
// need to make sure the parent exists
// it is an error to create a directory whose immediate parent does not yet exist
// see issue: https://issues.apache.org/jira/browse/CB-339
string[] pathParts = path.Split('/');
string builtPath = pathParts[0];
for (int n = 1; n < pathParts.Length - 1; n++)
{
builtPath += "/" + pathParts[n];
if (!isoFile.DirectoryExists(builtPath))
{
Debug.WriteLine(String.Format("Error :: Parent folder \"{0}\" does not exist, when attempting to create \"{1}\"",builtPath,path));
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
}
if ((getDirectory) && (!isDirectory))
{
isoFile.CreateDirectory(path);
}
else
{
if ((!getDirectory) && (!isFile))
{
IsolatedStorageFileStream fileStream = isoFile.CreateFile(path);
fileStream.Close();
}
}
}
else // (not create)
{
if ((!isFile) && (!isDirectory))
{
if (path.IndexOf("//www") == 0)
{
Uri fileUri = new Uri(path.Remove(0,2), UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri);
if (streamInfo != null)
{
FileEntry _entry = FileEntry.GetEntry(fileUri.OriginalString,true);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, _entry));
//using (BinaryReader br = new BinaryReader(streamInfo.Stream))
//{
// byte[] data = br.ReadBytes((int)streamInfo.Stream.Length);
//}
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
return;
}
if (((getDirectory) && (!isDirectory)) || ((!getDirectory) && (!isFile)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, TYPE_MISMATCH_ERR));
return;
}
}
FileEntry entry = FileEntry.GetEntry(path);
if (entry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
private static string AddSlashToDirectory(string dirPath)
{
if (dirPath.EndsWith("/"))
{
return dirPath;
}
else
{
return dirPath + "/";
}
}
/// <summary>
/// Returns file content in a form of base64 string
/// </summary>
/// <param name="stream">File stream</param>
/// <returns>Base64 representation of the file</returns>
private string GetFileContent(Stream stream)
{
int streamLength = (int)stream.Length;
byte[] fileData = new byte[streamLength + 1];
stream.Read(fileData, 0, streamLength);
stream.Close();
return Convert.ToBase64String(fileData);
}
#endregion
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Collections;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* An implementation of <a href="http://tools.ietf.org/html/rfc7253">RFC 7253 on The OCB
* Authenticated-Encryption Algorithm</a>, licensed per:
*
* <blockquote><p><a href="http://www.cs.ucdavis.edu/~rogaway/ocb/license1.pdf">License for
* Open-Source Software Implementations of OCB</a> (Jan 9, 2013) - 'License 1'<br/>
* Under this license, you are authorized to make, use, and distribute open-source software
* implementations of OCB. This license terminates for you if you sue someone over their open-source
* software implementation of OCB claiming that you have a patent covering their implementation.
* </p><p>
* This is a non-binding summary of a legal document (the link above). The parameters of the license
* are specified in the license document and that document is controlling.</p></blockquote>
*/
public class OcbBlockCipher
: IAeadBlockCipher
{
private const int BLOCK_SIZE = 16;
private readonly IBlockCipher hashCipher;
private readonly IBlockCipher mainCipher;
/*
* CONFIGURATION
*/
private bool forEncryption;
private int macSize;
private byte[] initialAssociatedText;
/*
* KEY-DEPENDENT
*/
// NOTE: elements are lazily calculated
private IList L;
private byte[] L_Asterisk, L_Dollar;
/*
* NONCE-DEPENDENT
*/
private byte[] KtopInput = null;
private byte[] Stretch = new byte[24];
private byte[] OffsetMAIN_0 = new byte[16];
/*
* PER-ENCRYPTION/DECRYPTION
*/
private byte[] hashBlock, mainBlock;
private int hashBlockPos, mainBlockPos;
private long hashBlockCount, mainBlockCount;
private byte[] OffsetHASH;
private byte[] Sum;
private byte[] OffsetMAIN = new byte[16];
private byte[] Checksum;
// NOTE: The MAC value is preserved after doFinal
private byte[] macBlock;
public OcbBlockCipher(IBlockCipher hashCipher, IBlockCipher mainCipher)
{
if (hashCipher == null)
throw new ArgumentNullException("hashCipher");
if (hashCipher.GetBlockSize() != BLOCK_SIZE)
throw new ArgumentException("must have a block size of " + BLOCK_SIZE, "hashCipher");
if (mainCipher == null)
throw new ArgumentNullException("mainCipher");
if (mainCipher.GetBlockSize() != BLOCK_SIZE)
throw new ArgumentException("must have a block size of " + BLOCK_SIZE, "mainCipher");
if (!hashCipher.AlgorithmName.Equals(mainCipher.AlgorithmName))
throw new ArgumentException("'hashCipher' and 'mainCipher' must be the same algorithm");
this.hashCipher = hashCipher;
this.mainCipher = mainCipher;
}
public virtual IBlockCipher GetUnderlyingCipher()
{
return mainCipher;
}
public virtual string AlgorithmName
{
get { return mainCipher.AlgorithmName + "/OCB"; }
}
public virtual void Init(bool forEncryption, ICipherParameters parameters)
{
bool oldForEncryption = this.forEncryption;
this.forEncryption = forEncryption;
this.macBlock = null;
KeyParameter keyParameter;
byte[] N;
if (parameters is AeadParameters)
{
AeadParameters aeadParameters = (AeadParameters) parameters;
N = aeadParameters.GetNonce();
initialAssociatedText = aeadParameters.GetAssociatedText();
int macSizeBits = aeadParameters.MacSize;
if (macSizeBits < 64 || macSizeBits > 128 || macSizeBits % 8 != 0)
throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
macSize = macSizeBits / 8;
keyParameter = aeadParameters.Key;
}
else if (parameters is ParametersWithIV)
{
ParametersWithIV parametersWithIV = (ParametersWithIV) parameters;
N = parametersWithIV.GetIV();
initialAssociatedText = null;
macSize = 16;
keyParameter = (KeyParameter) parametersWithIV.Parameters;
}
else
{
throw new ArgumentException("invalid parameters passed to OCB");
}
this.hashBlock = new byte[16];
this.mainBlock = new byte[forEncryption ? BLOCK_SIZE : (BLOCK_SIZE + macSize)];
if (N == null)
{
N = new byte[0];
}
if (N.Length > 15)
{
throw new ArgumentException("IV must be no more than 15 bytes");
}
/*
* KEY-DEPENDENT INITIALISATION
*/
if (keyParameter != null)
{
// hashCipher always used in forward mode
hashCipher.Init(true, keyParameter);
mainCipher.Init(forEncryption, keyParameter);
KtopInput = null;
}
else if (oldForEncryption != forEncryption)
{
throw new ArgumentException("cannot change encrypting state without providing key.");
}
this.L_Asterisk = new byte[16];
hashCipher.ProcessBlock(L_Asterisk, 0, L_Asterisk, 0);
this.L_Dollar = OCB_double(L_Asterisk);
this.L = Platform.CreateArrayList();
this.L.Add(OCB_double(L_Dollar));
/*
* NONCE-DEPENDENT AND PER-ENCRYPTION/DECRYPTION INITIALISATION
*/
int bottom = ProcessNonce(N);
int bits = bottom % 8, bytes = bottom / 8;
if (bits == 0)
{
Array.Copy(Stretch, bytes, OffsetMAIN_0, 0, 16);
}
else
{
for (int i = 0; i < 16; ++i)
{
uint b1 = Stretch[bytes];
uint b2 = Stretch[++bytes];
this.OffsetMAIN_0[i] = (byte) ((b1 << bits) | (b2 >> (8 - bits)));
}
}
this.hashBlockPos = 0;
this.mainBlockPos = 0;
this.hashBlockCount = 0;
this.mainBlockCount = 0;
this.OffsetHASH = new byte[16];
this.Sum = new byte[16];
Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
this.Checksum = new byte[16];
if (initialAssociatedText != null)
{
ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
}
}
protected virtual int ProcessNonce(byte[] N)
{
byte[] nonce = new byte[16];
Array.Copy(N, 0, nonce, nonce.Length - N.Length, N.Length);
nonce[0] = (byte)(macSize << 4);
nonce[15 - N.Length] |= 1;
int bottom = nonce[15] & 0x3F;
nonce[15] &= 0xC0;
/*
* When used with incrementing nonces, the cipher is only applied once every 64 inits.
*/
if (KtopInput == null || !Arrays.AreEqual(nonce, KtopInput))
{
byte[] Ktop = new byte[16];
KtopInput = nonce;
hashCipher.ProcessBlock(KtopInput, 0, Ktop, 0);
Array.Copy(Ktop, 0, Stretch, 0, 16);
for (int i = 0; i < 8; ++i)
{
Stretch[16 + i] = (byte)(Ktop[i] ^ Ktop[i + 1]);
}
}
return bottom;
}
public virtual int GetBlockSize()
{
return BLOCK_SIZE;
}
public virtual byte[] GetMac()
{
return Arrays.Clone(macBlock);
}
public virtual int GetOutputSize(int len)
{
int totalData = len + mainBlockPos;
if (forEncryption)
{
return totalData + macSize;
}
return totalData < macSize ? 0 : totalData - macSize;
}
public virtual int GetUpdateOutputSize(int len)
{
int totalData = len + mainBlockPos;
if (!forEncryption)
{
if (totalData < macSize)
{
return 0;
}
totalData -= macSize;
}
return totalData - totalData % BLOCK_SIZE;
}
public virtual void ProcessAadByte(byte input)
{
hashBlock[hashBlockPos] = input;
if (++hashBlockPos == hashBlock.Length)
{
ProcessHashBlock();
}
}
public virtual void ProcessAadBytes(byte[] input, int off, int len)
{
for (int i = 0; i < len; ++i)
{
hashBlock[hashBlockPos] = input[off + i];
if (++hashBlockPos == hashBlock.Length)
{
ProcessHashBlock();
}
}
}
public virtual int ProcessByte(byte input, byte[] output, int outOff)
{
mainBlock[mainBlockPos] = input;
if (++mainBlockPos == mainBlock.Length)
{
ProcessMainBlock(output, outOff);
return BLOCK_SIZE;
}
return 0;
}
public virtual int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff)
{
int resultLen = 0;
for (int i = 0; i < len; ++i)
{
mainBlock[mainBlockPos] = input[inOff + i];
if (++mainBlockPos == mainBlock.Length)
{
ProcessMainBlock(output, outOff + resultLen);
resultLen += BLOCK_SIZE;
}
}
return resultLen;
}
public virtual int DoFinal(byte[] output, int outOff)
{
/*
* For decryption, get the tag from the end of the message
*/
byte[] tag = null;
if (!forEncryption) {
if (mainBlockPos < macSize)
throw new InvalidCipherTextException("data too short");
mainBlockPos -= macSize;
tag = new byte[macSize];
Array.Copy(mainBlock, mainBlockPos, tag, 0, macSize);
}
/*
* HASH: Process any final partial block; compute final hash value
*/
if (hashBlockPos > 0)
{
OCB_extend(hashBlock, hashBlockPos);
UpdateHASH(L_Asterisk);
}
/*
* OCB-ENCRYPT/OCB-DECRYPT: Process any final partial block
*/
if (mainBlockPos > 0)
{
if (forEncryption)
{
OCB_extend(mainBlock, mainBlockPos);
Xor(Checksum, mainBlock);
}
Xor(OffsetMAIN, L_Asterisk);
byte[] Pad = new byte[16];
hashCipher.ProcessBlock(OffsetMAIN, 0, Pad, 0);
Xor(mainBlock, Pad);
Check.OutputLength(output, outOff, mainBlockPos, "Output buffer too short");
Array.Copy(mainBlock, 0, output, outOff, mainBlockPos);
if (!forEncryption)
{
OCB_extend(mainBlock, mainBlockPos);
Xor(Checksum, mainBlock);
}
}
/*
* OCB-ENCRYPT/OCB-DECRYPT: Compute raw tag
*/
Xor(Checksum, OffsetMAIN);
Xor(Checksum, L_Dollar);
hashCipher.ProcessBlock(Checksum, 0, Checksum, 0);
Xor(Checksum, Sum);
this.macBlock = new byte[macSize];
Array.Copy(Checksum, 0, macBlock, 0, macSize);
/*
* Validate or append tag and reset this cipher for the next run
*/
int resultLen = mainBlockPos;
if (forEncryption)
{
Check.OutputLength(output, outOff, resultLen + macSize, "Output buffer too short");
// Append tag to the message
Array.Copy(macBlock, 0, output, outOff + resultLen, macSize);
resultLen += macSize;
}
else
{
// Compare the tag from the message with the calculated one
if (!Arrays.ConstantTimeAreEqual(macBlock, tag))
throw new InvalidCipherTextException("mac check in OCB failed");
}
Reset(false);
return resultLen;
}
public virtual void Reset()
{
Reset(true);
}
protected virtual void Clear(byte[] bs)
{
if (bs != null)
{
Array.Clear(bs, 0, bs.Length);
}
}
protected virtual byte[] GetLSub(int n)
{
while (n >= L.Count)
{
L.Add(OCB_double((byte[]) L[L.Count - 1]));
}
return (byte[])L[n];
}
protected virtual void ProcessHashBlock()
{
/*
* HASH: Process any whole blocks
*/
UpdateHASH(GetLSub(OCB_ntz(++hashBlockCount)));
hashBlockPos = 0;
}
protected virtual void ProcessMainBlock(byte[] output, int outOff)
{
Check.DataLength(output, outOff, BLOCK_SIZE, "Output buffer too short");
/*
* OCB-ENCRYPT/OCB-DECRYPT: Process any whole blocks
*/
if (forEncryption)
{
Xor(Checksum, mainBlock);
mainBlockPos = 0;
}
Xor(OffsetMAIN, GetLSub(OCB_ntz(++mainBlockCount)));
Xor(mainBlock, OffsetMAIN);
mainCipher.ProcessBlock(mainBlock, 0, mainBlock, 0);
Xor(mainBlock, OffsetMAIN);
Array.Copy(mainBlock, 0, output, outOff, 16);
if (!forEncryption)
{
Xor(Checksum, mainBlock);
Array.Copy(mainBlock, BLOCK_SIZE, mainBlock, 0, macSize);
mainBlockPos = macSize;
}
}
protected virtual void Reset(bool clearMac)
{
hashCipher.Reset();
mainCipher.Reset();
Clear(hashBlock);
Clear(mainBlock);
hashBlockPos = 0;
mainBlockPos = 0;
hashBlockCount = 0;
mainBlockCount = 0;
Clear(OffsetHASH);
Clear(Sum);
Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
Clear(Checksum);
if (clearMac)
{
macBlock = null;
}
if (initialAssociatedText != null)
{
ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
}
}
protected virtual void UpdateHASH(byte[] LSub)
{
Xor(OffsetHASH, LSub);
Xor(hashBlock, OffsetHASH);
hashCipher.ProcessBlock(hashBlock, 0, hashBlock, 0);
Xor(Sum, hashBlock);
}
protected static byte[] OCB_double(byte[] block)
{
byte[] result = new byte[16];
int carry = ShiftLeft(block, result);
/*
* NOTE: This construction is an attempt at a constant-time implementation.
*/
result[15] ^= (byte)(0x87 >> ((1 - carry) << 3));
return result;
}
protected static void OCB_extend(byte[] block, int pos)
{
block[pos] = (byte) 0x80;
while (++pos < 16)
{
block[pos] = 0;
}
}
protected static int OCB_ntz(long x)
{
if (x == 0)
{
return 64;
}
int n = 0;
ulong ux = (ulong)x;
while ((ux & 1UL) == 0UL)
{
++n;
ux >>= 1;
}
return n;
}
protected static int ShiftLeft(byte[] block, byte[] output)
{
int i = 16;
uint bit = 0;
while (--i >= 0)
{
uint b = block[i];
output[i] = (byte) ((b << 1) | bit);
bit = (b >> 7) & 1;
}
return (int)bit;
}
protected static void Xor(byte[] block, byte[] val)
{
for (int i = 15; i >= 0; --i)
{
block[i] ^= val[i];
}
}
}
}
#endif
| |
//! \file ImageGBP.cs
//! \date 2018 Aug 27
//! \brief SVIU System image format.
//
// Copyright (C) 2018 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using GameRes.Utility;
namespace GameRes.Formats.Sviu
{
internal class GbpMetaData : ImageMetaData
{
public int HeaderSize;
public int DataOffset;
public int Method;
}
[Export(typeof(ImageFormat))]
public class GbpFormat : ImageFormat
{
public override string Tag { get { return "GBP"; } }
public override string Description { get { return "SVIU system image format"; } }
public override uint Signature { get { return 0x50425947; } } // 'GYBP'
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
var header = file.ReadHeader (0x14);
file.Seek (-0x13, SeekOrigin.End);
var key = file.ReadBytes (0x13);
for (int i = 4; i < 0x14; i += 2)
{
header[i] ^= key[0x10];
header[i+1] ^= key[0x11];
}
for (int i = 0; i < 0x10; ++i)
{
header[i+4] -= key[i];
}
return new GbpMetaData {
Width = header.ToUInt16 (0xE),
Height = header.ToUInt16 (0x10),
BPP = header.ToUInt16 (0x12),
HeaderSize = header.ToInt32 (4),
DataOffset = header.ToInt32 (8),
Method = header.ToUInt16 (0xC),
};
// 0x14 -> 32-bit checksum after encryption
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var reader = new GbpReader (file, (GbpMetaData)info);
var pixels = reader.Unpack();
return ImageData.Create (info, reader.Format, null, pixels);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("GbpFormat.Write not implemented");
}
}
internal class GbpReader
{
IBinaryStream m_input;
GbpMetaData m_info;
byte[] m_output;
int m_width;
int m_height;
int m_channels;
public PixelFormat Format { get; private set; }
public GbpReader (IBinaryStream input, GbpMetaData info)
{
m_input = input;
m_info = info;
if (32 == info.BPP)
Format = PixelFormats.Bgra32;
else
Format = PixelFormats.Bgr32;
m_width = (int)m_info.Width;
m_height = (int)m_info.Height;
m_output = new byte[4 * m_width * m_height];
m_channels = m_info.BPP / 8;
bits_pos = new int[m_channels+1];
data_pos = new int[m_channels+1];
}
public byte[] Unpack ()
{
ReadOffsetsTable();
if (3 == m_info.Method)
UnpackBlocks();
else
UnpackFlat();
return m_output;
}
byte[] m_frame = new byte[0x1000];
int[] bits_pos;
int[] data_pos;
void ReadOffsetsTable ()
{
m_input.Position = m_info.HeaderSize;
bits_pos[0] = m_info.HeaderSize + 4 * m_channels;
for (int i = 0; i < m_channels; ++i)
{
bits_pos[i+1] = bits_pos[i] + m_input.ReadInt32();
}
m_input.Position = m_info.DataOffset;
data_pos[0] = m_info.DataOffset + 4 * m_channels;
for (int i = 0; i < m_channels; ++i)
{
data_pos[i+1] = data_pos[i] + m_input.ReadInt32();
}
}
void UnpackFlat ()
{
var channel = new byte[m_width * m_height];
for (int i = 0; i < 3; ++i)
{
m_input.Position = bits_pos[i];
var bits = m_input.ReadBytes (bits_pos[i+1] - bits_pos[i]);
m_input.Position = data_pos[i];
if (1 == m_info.Method)
{
int bits_src = 0;
int bit_mask = 0x80;
int cdst = 0;
while (cdst < channel.Length)
{
if (0 == bit_mask)
{
++bits_src;
bit_mask = 0x80;
}
if ((bits[bits_src] & bit_mask) != 0)
{
int offset = m_input.ReadUInt16();
int count = (offset & 0xF) + 3;
offset = (offset >> 4) + 1;
Binary.CopyOverlapped (channel, cdst - offset, cdst, count);
cdst += count;
}
else
{
channel[cdst++] = m_input.ReadUInt8();
}
bit_mask >>= 1;
}
}
else if (2 == m_info.Method)
{
LzssUnpack (bits, 0, channel, channel.Length);
}
int dst = i;
byte accum = 0;
for (int csrc = 0; csrc < channel.Length; ++csrc)
{
accum += channel[csrc];
m_output[dst] = accum;
dst += 4;
}
}
if (4 == m_channels)
{
m_input.Position = data_pos[3];
int dst = 3;
while (dst < m_output.Length)
{
byte a = m_input.ReadUInt8();
int count = 1;
if (a == 0 || a == 0xFF)
{
count += m_input.ReadUInt8();
}
while (count --> 0)
{
m_output[dst] = a;
dst += 4;
}
}
}
}
void UnpackBlocks ()
{
var channel = new byte[m_width * m_height];
int stride = m_width * 4;
int block_stride = stride * 8;
for (int i = 0; i < m_channels; ++i)
{
m_input.Position = bits_pos[i];
int block_bits_length = m_input.ReadInt32();
int block_data_length = m_input.ReadInt32();
int chunk_count = m_input.ReadInt32();
var bits = m_input.ReadBytes (bits_pos[i+1] - bits_pos[i] - 12);
int bits_src = block_bits_length + block_data_length;
m_input.Position = data_pos[i];
LzssUnpack (bits, bits_src, channel, chunk_count);
int csrc = 0;
bits_src = 0;
int block_src = block_bits_length;
int dst_block = i;
int bit_mask = 0x80;
for (int y = 0; y < m_height; y += 8)
{
int block_height = Math.Min (8, m_height - y);
int dst_block_x = dst_block;
for (int x = 0; x < m_width; x += 8)
{
int block_width = Math.Min (8, m_width - x);
if (0 == bit_mask)
{
bit_mask = 0x80;
++bits_src;
}
int dst_row = dst_block_x;
if ((bit_mask & bits[bits_src]) != 0)
{
byte b = bits[block_src++];
for (int by = 0; by < block_height; ++by)
{
int dst = dst_row;
for (int bx = 0; bx < block_width; ++bx)
{
m_output[dst] = b;
dst += 4;
}
dst_row += stride;
}
}
else
{
for (int by = 0; by < block_height; ++by)
{
int dst = dst_row;
for (int bx = 0; bx < block_width; ++bx)
{
m_output[dst] = channel[csrc++];
dst += 4;
}
dst_row += stride;
}
}
dst_block_x += 32;
bit_mask >>= 1;
}
dst_block += block_stride;
}
}
}
void LzssUnpack (byte[] ctl_bits, int bits_src, byte[] output, int output_length)
{
for (int j = 0; j < m_frame.Length; ++j)
m_frame[j] = 0;
int dst = 0;
int bit_mask = 0x80;
int frame_pos = 0xFEE;
while (dst < output_length)
{
if (0 == bit_mask)
{
bit_mask = 0x80;
++bits_src;
}
if ((bit_mask & ctl_bits[bits_src]) != 0)
{
int offset = m_input.ReadUInt16();
int count = (offset & 0xF) + 3;
offset >>= 4;
while (count --> 0)
{
byte v = m_frame[offset++ & 0xFFF];
output[dst++] = m_frame[frame_pos++ & 0xFFF] = v;
}
}
else
{
output[dst++] = m_frame[frame_pos++ & 0xFFF] = m_input.ReadUInt8();
}
bit_mask >>= 1;
}
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
#if CORE || GDI
using System.Drawing;
using System.Drawing.Drawing2D;
using GdiFontFamily = System.Drawing.FontFamily;
using GdiFont = System.Drawing.Font;
using GdiFontStyle = System.Drawing.FontStyle;
#endif
#if WPF
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using WpfFontFamily = System.Windows.Media.FontFamily;
using WpfTypeface = System.Windows.Media.Typeface;
using WpfGlyphTypeface = System.Windows.Media.GlyphTypeface;
using WpfStyleSimulations = System.Windows.Media.StyleSimulations;
#endif
using PdfSharp.Drawing;
#pragma warning disable 1591
// ReSharper disable RedundantNameQualifier
namespace PdfSharp.Fonts
{
/// <summary>
/// Default platform specific font resolving.
/// </summary>
public static class PlatformFontResolver
{
/// <summary>
/// Resolves the typeface by generating a font resolver info.
/// </summary>
/// <param name="familyName">Name of the font family.</param>
/// <param name="isBold">Indicates whether a bold font is requested.</param>
/// <param name="isItalic">Indicates whether an italic font is requested.</param>
public static FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
{
FontResolvingOptions fontResolvingOptions = new FontResolvingOptions(FontHelper.CreateStyle(isBold, isItalic));
return ResolveTypeface(familyName, fontResolvingOptions, XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions));
}
/// <summary>
/// Internal implementation.
/// </summary>
internal static FontResolverInfo ResolveTypeface(string familyName, FontResolvingOptions fontResolvingOptions, string typefaceKey)
{
// Internally we often have the typeface key already.
if (string.IsNullOrEmpty(typefaceKey))
typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions);
// The user may call ResolveTypeface anytime from anywhere, so check cache in FontFactory in the first place.
FontResolverInfo fontResolverInfo;
if (FontFactory.TryGetFontResolverInfoByTypefaceKey(typefaceKey, out fontResolverInfo))
return fontResolverInfo;
// Let the platform create the requested font source and save both PlattformResolverInfo
// and XFontSource in FontFactory cache.
// It is possible that we already have the correct font source. E.g. we already have the regular typeface in cache
// and looking now for the italic typeface, but no such font exists. In this case we get the regular font source
// and cache again it with the italic typeface key. Furthermore in glyph typeface style simulation for italic is set.
#if (CORE || GDI) && !WPF
GdiFont gdiFont;
XFontSource fontSource = CreateFontSource(familyName, fontResolvingOptions, out gdiFont, typefaceKey);
#endif
#if WPF && !SILVERLIGHT
WpfFontFamily wpfFontFamily;
WpfTypeface wpfTypeface;
WpfGlyphTypeface wpfGlyphTypeface;
XFontSource fontSource = CreateFontSource(familyName, fontResolvingOptions, out wpfFontFamily, out wpfTypeface, out wpfGlyphTypeface, typefaceKey);
#endif
#if SILVERLIGHT
//GlyphTypeface wpfGlyphTypeface;
XFontSource fontSource = null;//CreateFontSource(familyName, isBold, isItalic, out wpfGlyphTypeface, typefaceKey);
#endif
#if NETFX_CORE || UWP
//GlyphTypeface wpfGlyphTypeface;
XFontSource fontSource = null;//CreateFontSource(familyName, isBold, isItalic, out wpfGlyphTypeface, typefaceKey);
#endif
// If no such font exists return null. PDFsharp will fail.
if (fontSource == null)
return null;
//#if (CORE || GDI) && !WPF
// // TODO: Support style simulation for GDI+ platform fonts.
// fontResolverInfo = new PlatformFontResolverInfo(typefaceKey, false, false, gdiFont);
//#endif
if (fontResolvingOptions.OverrideStyleSimulations)
{
#if (CORE || GDI) && !WPF
// TODO: Support style simulation for GDI+ platform fonts.
fontResolverInfo = new PlatformFontResolverInfo(typefaceKey, fontResolvingOptions.MustSimulateBold, fontResolvingOptions.MustSimulateItalic, gdiFont);
#endif
#if WPF && !SILVERLIGHT
fontResolverInfo = new PlatformFontResolverInfo(typefaceKey, fontResolvingOptions.MustSimulateBold, fontResolvingOptions.MustSimulateItalic,
wpfFontFamily, wpfTypeface, wpfGlyphTypeface);
#endif
}
else
{
#if (CORE || GDI) && !WPF
bool mustSimulateBold = gdiFont.Bold && !fontSource.Fontface.os2.IsBold;
bool mustSimulateItalic = gdiFont.Italic && !fontSource.Fontface.os2.IsItalic;
fontResolverInfo = new PlatformFontResolverInfo(typefaceKey, mustSimulateBold, mustSimulateItalic, gdiFont);
#endif
#if WPF && !SILVERLIGHT
// WPF knows what styles have to be simulated.
bool mustSimulateBold = (wpfGlyphTypeface.StyleSimulations & WpfStyleSimulations.BoldSimulation) == WpfStyleSimulations.BoldSimulation;
bool mustSimulateItalic = (wpfGlyphTypeface.StyleSimulations & WpfStyleSimulations.ItalicSimulation) == WpfStyleSimulations.ItalicSimulation;
// Weird behavior of WPF is fixed here in case we request a bold italic typeface.
// If only italic is available, bold is simulated based on italic.
// If only bold is available, italic is simulated based on bold.
// But if both bold and italic is available, italic face is used and bold is simulated.
// The latter case is reversed here, i.e. bold face is used and italic is simulated.
if (fontResolvingOptions.IsBoldItalic && mustSimulateBold && !mustSimulateItalic)
{
// Try to get the bold typeface.
string typefaceKeyBold = XGlyphTypeface.ComputeKey(familyName, true, false);
FontResolverInfo infoBold = ResolveTypeface(familyName,
new FontResolvingOptions(FontHelper.CreateStyle(true, false)), typefaceKeyBold);
// Use it if it does not base on simulateion.
if (infoBold != null && infoBold.StyleSimulations == XStyleSimulations.None)
{
// Use existing bold typeface and simualte italic.
fontResolverInfo = new PlatformFontResolverInfo(typefaceKeyBold, false, true,
wpfFontFamily, wpfTypeface, wpfGlyphTypeface);
}
else
{
// Simulate both.
fontResolverInfo = new PlatformFontResolverInfo(typefaceKey, true, true,
wpfFontFamily, wpfTypeface, wpfGlyphTypeface);
}
}
else
{
fontResolverInfo = new PlatformFontResolverInfo(typefaceKey, mustSimulateBold, mustSimulateItalic,
wpfFontFamily, wpfTypeface, wpfGlyphTypeface);
}
#endif
}
#if SILVERLIGHT
fontResolverInfo = null; //new PlattformResolverInfo(typefaceKey, false, false, wpfGlyphTypeface);
#endif
FontFactory.CacheFontResolverInfo(typefaceKey, fontResolverInfo);
// Register font data under the platform specific face name.
// Already done in CreateFontSource.
// FontFactory.CacheNewFontSource(typefaceKey, fontSource);
return fontResolverInfo;
}
#if (CORE_WITH_GDI || GDI) && !WPF
/// <summary>
/// Create a GDI+ font and use its handle to retrieve font data using native calls.
/// </summary>
internal static XFontSource CreateFontSource(string familyName, FontResolvingOptions fontResolvingOptions, out GdiFont font, string typefaceKey)
{
if (string.IsNullOrEmpty(typefaceKey))
typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions);
#if true_
if (familyName == "Cambria")
Debug-Break.Break();
#endif
GdiFontStyle gdiStyle = (GdiFontStyle)(fontResolvingOptions.FontStyle & XFontStyle.BoldItalic);
// Create a 10 point GDI+ font as an exemplar.
XFontSource fontSource;
font = FontHelper.CreateFont(familyName, 10, gdiStyle, out fontSource);
if (fontSource != null)
{
Debug.Assert(font != null);
// Case: Font was created by a GDI+ private font collection.
#if true
#if DEBUG
XFontSource existingFontSource;
Debug.Assert(FontFactory.TryGetFontSourceByTypefaceKey(typefaceKey, out existingFontSource) &&
ReferenceEquals(fontSource, existingFontSource));
#endif
#else
// Win32 API cannot get font data from fonts created by private font collection,
// because this is handled internally in GDI+.
// Therefore the font source was created when the private font is added to the private font collection.
if (!FontFactory.TryGetFontSourceByTypefaceKey(typefaceKey, out fontSource))
{
// Simplify styles.
// (The code is written for clarity - do not rearrange for optimization)
if (font.Bold && font.Italic)
{
if (FontFactory.TryGetFontSourceByTypefaceKey(XGlyphTypeface.ComputeKey(font.Name, true, false), out fontSource))
{
// Use bold font.
FontFactory.CacheExistingFontSourceWithNewTypefaceKey(typefaceKey, fontSource);
}
else if (FontFactory.TryGetFontSourceByTypefaceKey(XGlyphTypeface.ComputeKey(font.Name, false, true), out fontSource))
{
// Use italic font.
FontFactory.CacheExistingFontSourceWithNewTypefaceKey(typefaceKey, fontSource);
}
else if (FontFactory.TryGetFontSourceByTypefaceKey(XGlyphTypeface.ComputeKey(font.Name, false, false), out fontSource))
{
// Use regular font.
FontFactory.CacheExistingFontSourceWithNewTypefaceKey(typefaceKey, fontSource);
}
}
else if (font.Bold || font.Italic)
{
// Use regular font.
if (FontFactory.TryGetFontSourceByTypefaceKey(XGlyphTypeface.ComputeKey(font.Name, false, false), out fontSource))
{
FontFactory.CacheExistingFontSourceWithNewTypefaceKey(typefaceKey, fontSource);
}
}
else
{
if (FontFactory.TryGetFontSourceByTypefaceKey(XGlyphTypeface.ComputeKey(font.Name, false, false), out fontSource))
{
// Should never come here...
FontFactory.CacheExistingFontSourceWithNewTypefaceKey(typefaceKey, fontSource);
}
}
}
#endif
}
else
{
// Get or create the font source and cache it unter the specified typeface key.
fontSource = XFontSource.GetOrCreateFromGdi(typefaceKey, font);
}
return fontSource;
}
#endif
#if WPF && !SILVERLIGHT
/// <summary>
/// Create a WPF GlyphTypeface and retrieve font data from it.
/// </summary>
internal static XFontSource CreateFontSource(string familyName, FontResolvingOptions fontResolvingOptions,
out WpfFontFamily wpfFontFamily, out WpfTypeface wpfTypeface, out WpfGlyphTypeface wpfGlyphTypeface, string typefaceKey)
{
if (string.IsNullOrEmpty(typefaceKey))
typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions);
XFontStyle style = fontResolvingOptions.FontStyle;
#if DEBUG
if (StringComparer.OrdinalIgnoreCase.Compare(familyName, "Segoe UI Semilight") == 0
&& (style & XFontStyle.BoldItalic) == XFontStyle.Italic)
familyName.GetType();
#endif
// Use WPF technique to create font data.
wpfTypeface = XPrivateFontCollection.TryCreateTypeface(familyName, style, out wpfFontFamily);
#if DEBUG__
if (wpfTypeface != null)
{
WpfGlyphTypeface glyphTypeface;
ICollection<WpfTypeface> list = wpfFontFamily.GetTypefaces();
foreach (WpfTypeface tf in list)
{
if (!tf.TryGetGlyphTypeface(out glyphTypeface))
Debug-Break.Break();
}
//if (!WpfTypeface.TryGetGlyphTypeface(out glyphTypeface))
// throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName));
}
#endif
if (wpfFontFamily == null)
wpfFontFamily = new WpfFontFamily(familyName);
if (wpfTypeface == null)
wpfTypeface = FontHelper.CreateTypeface(wpfFontFamily, style);
// Let WPF choose the right glyph typeface.
if (!wpfTypeface.TryGetGlyphTypeface(out wpfGlyphTypeface))
throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName));
// Get or create the font source and cache it unter the specified typeface key.
XFontSource fontSource = XFontSource.GetOrCreateFromWpf(typefaceKey, wpfGlyphTypeface);
return fontSource;
}
#endif
#if SILVERLIGHT
/// <summary>
/// Silverlight has no access to the bytes of its fonts and threrefore return null.
/// </summary>
internal static XFontSource CreateFontSource(string familyName, bool isBold, bool isItalic)
{
// PDFsharp does not provide a default font because this would blow up the assembly
// unneccessarily if the font is not needed. Provide your own font resolver to generate
// PDF files containing text.
return null;
}
#endif
#if NETFX_CORE
internal static XFontSource CreateFontSource(string familyName, bool isBold, bool isItalic, string typefaceKey)
{
throw new NotImplementedException();
}
#endif
}
}
| |
namespace FP.SqlAst.Generators {
using System;
using System.Collections.Generic;
using System.Text;
public class PostgreSqlGenerator {
public string Generate(SelectQuery query, Dictionary<string, object> parameters) {
var visitor = new Visitor(parameters);
query.Accept(visitor);
return visitor.QueryString;
}
public class Visitor : SqlAstVisitorBase {
private readonly StringBuilder builder;
public Dictionary<string, object> Parameters { get; private set; }
public string QueryString {
get { return this.builder.ToString(); }
}
public Visitor(Dictionary<string, object> parameters) {
this.Parameters = parameters;
this.builder = new StringBuilder();
}
public override void VisitQueryProjection(IEnumerable<Column> columns) {
this.builder.Append("SELECT ");
this.WriteColumnNames(columns);
}
private void WriteColumnNames(IEnumerable<Column> columns) {
foreach (var column in columns) {
column.Accept(this);
this.builder.Append(", ");
}
this.builder.Remove(this.builder.Length - 2, 2);
}
public override void VisitQueryFrom(RecordSet @from) {
this.builder.Append(" FROM ");
var usingSubquery = @from is SelectQuery;
if (usingSubquery) {
this.builder.Append("(");
}
from.Accept(this);
if (usingSubquery) {
this.builder.Append(") as \"" + @from.Alias + "\"");
}
}
public override void VisitTable(Table element) {
this.builder.Append("\"" + element.Name + "\"");
}
public override void VisitAllColumns(AllColumns element) {
this.builder.Append("*");
}
public override void VisitNamedColumn(NamedColumn element) {
if (element.Base != null)
{
this.builder.Append("\"");
this.builder.Append(element.Base);
this.builder.Append("\".");
}
this.builder.Append("\"");
this.builder.Append(element.Name);
this.builder.Append("\"");
}
public override void VisitRowNumberColumn(RowNumberColumn rowNumberColumn) {
throw new NotSupportedException("RowNumberColumn not supported");
}
public override void VisitQueryCondition(Condition condition) {
this.builder.Append(" WHERE ");
condition.Accept(this);
}
public override void VisitGroupBy(List<SqlAstElement> groupBy)
{
this.builder.Append(" GROUP BY ");
foreach (var element in groupBy)
{
element.Accept(this);
this.builder.Append(", ");
}
this.builder.Remove(this.builder.Length - 2, 2);
}
public override void VisitBetween(BetweenCondition betweenCondition) {
betweenCondition.Value.Accept(this);
this.builder.Append(" BETWEEN ");
betweenCondition.Left.Accept(this);
this.builder.Append(" AND ");
betweenCondition.Right.Accept(this);
}
public override void VisitColumnReference(ColumnReference columnReference) {
if (columnReference.Base != null)
{
this.builder.Append("\"");
this.builder.Append(columnReference.Base);
this.builder.Append("\".");
}
this.builder.Append("\"");
this.builder.Append(columnReference.ColumnName);
this.builder.Append("\"");
}
public override void VisitConstant(ConstantValue constantValue) {
var paramName = "p" + this.Parameters.Keys.Count;
this.Parameters.Add(paramName, constantValue.Value);
this.builder.Append("@").Append(paramName);
}
public override void VisitBinaryCondition(BinaryCondition binaryCondition)
{
this.builder.Append("(");
binaryCondition.Left.Accept(this);
this.builder.Append(")");
this.builder.Append(" ").Append(binaryCondition.Operator).Append(" ");
this.builder.Append("(");
binaryCondition.Right.Accept(this);
this.builder.Append(")");
}
public override void VisitFunctionCall(FunctionCall functionCall)
{
this.builder.Append(functionCall.FunctionName).Append("(");
foreach (var element in functionCall.Arguments) {
element.Accept(this);
this.builder.Append(", ");
}
this.builder.Remove(this.builder.Length - 2, 2);
this.builder.Append(")");
}
public override void VisitColumnWithAlias(AliasColumn aliasColumn)
{
this.builder.Append("(");
aliasColumn.InnerColumn.Accept(this);
this.builder.Append(")")
.Append(" as \"").Append(aliasColumn.Alias).Append("\"");
}
public override void VisitJoins(List<Join> joins)
{
foreach (var @join in joins)
{
@join.Accept(this);
}
}
public override void VisitJoin(Join @join)
{
this.builder.Append(" ").Append(@join.Type.ToUpper()).Append(" JOIN ");
if (@join.RecordSet is SelectQuery)
{
this.builder.Append("(");
}
@join.RecordSet.Accept(this);
if (@join.RecordSet is SelectQuery) {
this.builder.Append(")");
}
if (@join.Alias != null)
{
this.builder.Append(" AS ").Append(@join.Alias);
}
this.builder.Append(" ON ");
@join.Condition.Accept(this);
}
public override void VisitInCondition(InCondition inCondition)
{
this.builder.Append("(");
inCondition.Value.Accept(this);
this.builder.Append(") IN (");
foreach (var value in inCondition.Values)
{
value.Accept(this);
this.builder.Append(", ");
}
this.builder.Remove(this.builder.Length - 2, 2);
this.builder.Append(")");
}
}
}
}
| |
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;
using Microsoft.Xna.Framework.Storage;
namespace CH11___Storage
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
// the one and only game texture
Texture2D m_Texture;
// coordinates of the images within the texture
Rectangle m_rectSave = new Rectangle(0, 0, 64, 26);
Rectangle m_rectLoad = new Rectangle(0, 28, 64, 26);
Rectangle m_rectArrow = new Rectangle(0, 54, 25, 32);
Rectangle m_rectStamp = new Rectangle(6, 89, 33, 31);
// instance of our game data object
GameData m_data = new GameData();
// position of the arror
Vector2 m_cursor = Vector2.One * 200.0f;
// location of the buttons
Vector2 m_posButtonSave = new Vector2(64, 64);
Vector2 m_posButtonLoad = new Vector2(64, 94);
// about to save or load data?
bool m_pressedSave = false;
bool m_pressedLoad = false;
// storage API references
StorageDevice m_storage = null;
IAsyncResult m_resultStorage = null;
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);
// run at full speed
IsFixedTimeStep = false;
// set screen size
InitScreen();
base.Initialize();
}
// screen constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
// screen-related init tasks
public void InitScreen()
{
// back buffer
graphics.PreferredBackBufferHeight = SCREEN_HEIGHT;
graphics.PreferredBackBufferWidth = SCREEN_WIDTH;
graphics.PreferMultiSampling = false;
graphics.ApplyChanges();
}
/// <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 our game graphics
m_Texture = Content.Load<Texture2D>(@"media\game");
}
/// <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)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// get a reference to the input states, and process them
GamePadState pad1 = GamePad.GetState(PlayerIndex.One);
KeyboardState key1 = Keyboard.GetState();
ProcessInput(pad1, key1);
base.Update(gameTime);
}
protected void ProcessInput(GamePadState pad1, KeyboardState key1)
{
// is the player moving left or right?
if (pad1.ThumbSticks.Left.X < 0)
{
m_cursor.X += pad1.ThumbSticks.Left.X * 3.0f;
}
else if (key1.IsKeyDown(Keys.Left))
{
m_cursor.X -= 3.0f;
}
else if (pad1.ThumbSticks.Left.X > 0)
{
m_cursor.X += pad1.ThumbSticks.Left.X * 3.0f;
}
else if (key1.IsKeyDown(Keys.Right))
{
m_cursor.X += 3.0f;
}
// is the player moving up or down?
if (pad1.ThumbSticks.Left.Y < 0)
{
m_cursor.Y -= pad1.ThumbSticks.Left.Y * 3.0f;
}
else if (key1.IsKeyDown(Keys.Down))
{
m_cursor.Y += 3.0f;
}
else if (pad1.ThumbSticks.Left.Y > 0)
{
m_cursor.Y -= pad1.ThumbSticks.Left.Y * 3.0f;
}
else if (key1.IsKeyDown(Keys.Up))
{
m_cursor.Y -= 3.0f;
}
// is the player pressing the clear button?
if (pad1.Buttons.Start == ButtonState.Pressed ||
key1.IsKeyDown(Keys.Enter))
{
// clear our list of stamps
m_data.Stamps.Clear();
}
// is the player pressing the action button?
if (pad1.Buttons.A == ButtonState.Pressed ||
key1.IsKeyDown(Keys.Space))
{
// only register a save or load if there's not
// a save or load currently in progress
if (m_resultStorage == null)
{
// clear the button press states
m_pressedSave = false;
m_pressedLoad = false;
// is player pressing the save button?
if (InRect(m_cursor, m_rectSave, m_posButtonSave))
{
m_pressedSave = true;
}
// is player pressing the load button?
else if (InRect(m_cursor, m_rectLoad, m_posButtonLoad))
{
m_pressedLoad = true;
}
// add a new stamp to our list
else if (!m_data.Stamps.Contains(m_cursor))
{
m_data.Stamps.Add(m_cursor);
}
}
}
// the player isn't pressing the action button
else
{
// there is no load or save in progress
if (m_resultStorage == null)
{
// the player just released the action button
if (m_pressedLoad || m_pressedSave)
{
// show the storage guide on Xbox, has no
// effect on Windows
m_resultStorage =
//Guide.BeginShowStorageDeviceSelector(null, null);
StorageDevice.BeginShowSelector(null, null);
}
}
// there is a load or save in progress
else
{
// has the player selected a device?
if (m_resultStorage.IsCompleted)
{
// get a reference to the selected device
m_storage =
//Guide.EndShowStorageDeviceSelector(m_resultStorage);
StorageDevice.EndShowSelector(m_resultStorage);
// save was requested, save our data
if (m_pressedSave)
{
GameStorage.Save(m_storage, m_data, "test01");
}
// load was requested, load our data
else if (m_pressedLoad)
{
m_data = GameStorage.Load(m_storage, "test01");
}
// reset up our load / save state data
m_storage = null;
m_resultStorage = null;
m_pressedSave = false;
m_pressedLoad = false;
}
}
}
}
// determine whether or not the cursor is over a button
protected bool InRect(Vector2 cursor, Rectangle rect, Vector2 loc)
{
// move the rect to the cursor position
rect.X = (int)Math.Round(loc.X);
rect.Y = (int)Math.Round(loc.Y);
// check the cursor position against the button rect
return
cursor.X >= rect.Left && cursor.X <= rect.Right &&
cursor.Y >= rect.Top && cursor.Y <= rect.Bottom;
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
// draw all of the stamps that the player has made
DrawStamps();
// if the player is pressing the save button, highlight it
if (m_pressedSave)
{
spriteBatch.Draw(
m_Texture, m_posButtonSave, m_rectSave, Color.Goldenrod);
}
// draw the normal save button
else
{
spriteBatch.Draw(
m_Texture, m_posButtonSave, m_rectSave, Color.White);
}
// if the player is pressing the load button, highlight it
if (m_pressedLoad)
{
spriteBatch.Draw(
m_Texture, m_posButtonLoad, m_rectLoad, Color.Goldenrod);
}
// draw the normal load button
else
{
spriteBatch.Draw(
m_Texture, m_posButtonLoad, m_rectLoad, Color.White);
}
// draw the cursor
spriteBatch.Draw(m_Texture, m_cursor, m_rectArrow, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
// used to calc the center of the stamp
private Vector2 m_StampOffset = Vector2.Zero;
protected void DrawStamps()
{
// center the stamp on the cursor location
m_StampOffset.X = 0 - m_rectStamp.Width / 2;
m_StampOffset.Y = 0 - m_rectStamp.Height / 2;
// draw each stamp in our list
foreach (Vector2 pos in m_data.Stamps)
{
spriteBatch.Draw(
m_Texture, pos + m_StampOffset, m_rectStamp, Color.White);
}
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.IO;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
namespace Google.Protobuf
{
public class CodedInputStreamTest
{
/// <summary>
/// Helper to construct a byte array from a bunch of bytes. The inputs are
/// actually ints so that I can use hex notation and not get stupid errors
/// about precision.
/// </summary>
private static byte[] Bytes(params int[] bytesAsInts)
{
byte[] bytes = new byte[bytesAsInts.Length];
for (int i = 0; i < bytesAsInts.Length; i++)
{
bytes[i] = (byte) bytesAsInts[i];
}
return bytes;
}
/// <summary>
/// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64()
/// </summary>
private static void AssertReadVarint(byte[] data, ulong value)
{
CodedInputStream input = new CodedInputStream(data);
Assert.AreEqual((uint) value, input.ReadRawVarint32());
input = new CodedInputStream(data);
Assert.AreEqual(value, input.ReadRawVarint64());
Assert.IsTrue(input.IsAtEnd);
// Try different block sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
Assert.AreEqual((uint) value, input.ReadRawVarint32());
input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
Assert.AreEqual(value, input.ReadRawVarint64());
Assert.IsTrue(input.IsAtEnd);
}
// Try reading directly from a MemoryStream. We want to verify that it
// doesn't read past the end of the input, so write an extra byte - this
// lets us test the position at the end.
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(data, 0, data.Length);
memoryStream.WriteByte(0);
memoryStream.Position = 0;
Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
Assert.AreEqual(data.Length, memoryStream.Position);
}
/// <summary>
/// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
/// expects them to fail with an InvalidProtocolBufferException whose
/// description matches the given one.
/// </summary>
private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
{
CodedInputStream input = new CodedInputStream(data);
var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
Assert.AreEqual(expected.Message, exception.Message);
input = new CodedInputStream(data);
exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
Assert.AreEqual(expected.Message, exception.Message);
// Make sure we get the same error when reading directly from a Stream.
exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
Assert.AreEqual(expected.Message, exception.Message);
}
[Test]
public void ReadVarint()
{
AssertReadVarint(Bytes(0x00), 0);
AssertReadVarint(Bytes(0x01), 1);
AssertReadVarint(Bytes(0x7f), 127);
// 14882
AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
// 2961488830
AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x0bL << 28));
// 64-bit
// 7256456126
AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x1bL << 28));
// 41256202580718336
AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
(0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
// 11964378330978735131
AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
(0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
(0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
(0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
// Failures
AssertReadVarintFailure(
InvalidProtocolBufferException.MalformedVarint(),
Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
0x00));
AssertReadVarintFailure(
InvalidProtocolBufferException.TruncatedMessage(),
Bytes(0x80));
}
/// <summary>
/// Parses the given bytes using ReadRawLittleEndian32() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertReadLittleEndian32(byte[] data, uint value)
{
CodedInputStream input = new CodedInputStream(data);
Assert.AreEqual(value, input.ReadRawLittleEndian32());
Assert.IsTrue(input.IsAtEnd);
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
{
input = new CodedInputStream(
new SmallBlockInputStream(data, blockSize));
Assert.AreEqual(value, input.ReadRawLittleEndian32());
Assert.IsTrue(input.IsAtEnd);
}
}
/// <summary>
/// Parses the given bytes using ReadRawLittleEndian64() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertReadLittleEndian64(byte[] data, ulong value)
{
CodedInputStream input = new CodedInputStream(data);
Assert.AreEqual(value, input.ReadRawLittleEndian64());
Assert.IsTrue(input.IsAtEnd);
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
{
input = new CodedInputStream(
new SmallBlockInputStream(data, blockSize));
Assert.AreEqual(value, input.ReadRawLittleEndian64());
Assert.IsTrue(input.IsAtEnd);
}
}
[Test]
public void ReadLittleEndian()
{
AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
0x123456789abcdef0L);
AssertReadLittleEndian64(
Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
}
[Test]
public void DecodeZigZag32()
{
Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(0));
Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(1));
Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(2));
Assert.AreEqual(-2, ParsingPrimitives.DecodeZigZag32(3));
Assert.AreEqual(0x3FFFFFFF, ParsingPrimitives.DecodeZigZag32(0x7FFFFFFE));
Assert.AreEqual(unchecked((int) 0xC0000000), ParsingPrimitives.DecodeZigZag32(0x7FFFFFFF));
Assert.AreEqual(0x7FFFFFFF, ParsingPrimitives.DecodeZigZag32(0xFFFFFFFE));
Assert.AreEqual(unchecked((int) 0x80000000), ParsingPrimitives.DecodeZigZag32(0xFFFFFFFF));
}
[Test]
public void DecodeZigZag64()
{
Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(0));
Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(1));
Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(2));
Assert.AreEqual(-2, ParsingPrimitives.DecodeZigZag64(3));
Assert.AreEqual(0x000000003FFFFFFFL, ParsingPrimitives.DecodeZigZag64(0x000000007FFFFFFEL));
Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), ParsingPrimitives.DecodeZigZag64(0x000000007FFFFFFFL));
Assert.AreEqual(0x000000007FFFFFFFL, ParsingPrimitives.DecodeZigZag64(0x00000000FFFFFFFEL));
Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), ParsingPrimitives.DecodeZigZag64(0x00000000FFFFFFFFL));
Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, ParsingPrimitives.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
Assert.AreEqual(unchecked((long) 0x8000000000000000L), ParsingPrimitives.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
}
[Test]
public void ReadWholeMessage_VaryingBlockSizes()
{
TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
byte[] rawBytes = message.ToByteArray();
Assert.AreEqual(rawBytes.Length, message.CalculateSize());
TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes);
Assert.AreEqual(message, message2);
// Try different block sizes.
for (int blockSize = 1; blockSize < 256; blockSize *= 2)
{
message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
Assert.AreEqual(message, message2);
}
}
[Test]
public void ReadHugeBlob()
{
// Allocate and initialize a 1MB blob.
byte[] blob = new byte[1 << 20];
for (int i = 0; i < blob.Length; i++)
{
blob[i] = (byte) i;
}
// Make a message containing it.
var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) };
// Serialize and parse it. Make sure to parse from an InputStream, not
// directly from a ByteString, so that CodedInputStream uses buffered
// reading.
TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString());
Assert.AreEqual(message, message2);
}
[Test]
public void ReadMaliciouslyLargeBlob()
{
MemoryStream ms = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(ms);
uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
output.WriteRawVarint32(tag);
output.WriteRawVarint32(0x7FFFFFFF);
output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
output.Flush();
ms.Position = 0;
CodedInputStream input = new CodedInputStream(ms);
Assert.AreEqual(tag, input.ReadTag());
Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
}
internal static TestRecursiveMessage MakeRecursiveMessage(int depth)
{
if (depth == 0)
{
return new TestRecursiveMessage { I = 5 };
}
else
{
return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
}
}
internal static void AssertMessageDepth(TestRecursiveMessage message, int depth)
{
if (depth == 0)
{
Assert.IsNull(message.A);
Assert.AreEqual(5, message.I);
}
else
{
Assert.IsNotNull(message.A);
AssertMessageDepth(message.A, depth - 1);
}
}
[Test]
public void MaliciousRecursion()
{
ByteString atRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit).ToByteString();
ByteString beyondRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit + 1).ToByteString();
AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(atRecursiveLimit), CodedInputStream.DefaultRecursionLimit);
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(beyondRecursiveLimit));
CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(atRecursiveLimit.ToByteArray()), 1000000, CodedInputStream.DefaultRecursionLimit - 1);
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
}
[Test]
public void SizeLimit()
{
// Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
// apply to the latter case.
MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray());
CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100);
Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input));
}
/// <summary>
/// Tests that if we read an string that contains invalid UTF-8, no exception
/// is thrown. Instead, the invalid bytes are replaced with the Unicode
/// "replacement character" U+FFFD.
/// </summary>
[Test]
public void ReadInvalidUtf8()
{
MemoryStream ms = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(ms);
uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
output.WriteRawVarint32(tag);
output.WriteRawVarint32(1);
output.WriteRawBytes(new byte[] {0x80});
output.Flush();
ms.Position = 0;
CodedInputStream input = new CodedInputStream(ms);
Assert.AreEqual(tag, input.ReadTag());
string text = input.ReadString();
Assert.AreEqual('\ufffd', text[0]);
}
/// <summary>
/// A stream which limits the number of bytes it reads at a time.
/// We use this to make sure that CodedInputStream doesn't screw up when
/// reading in small blocks.
/// </summary>
private sealed class SmallBlockInputStream : MemoryStream
{
private readonly int blockSize;
public SmallBlockInputStream(byte[] data, int blockSize)
: base(data)
{
this.blockSize = blockSize;
}
public override int Read(byte[] buffer, int offset, int count)
{
return base.Read(buffer, offset, Math.Min(count, blockSize));
}
}
[Test]
public void TestNegativeEnum()
{
byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
CodedInputStream input = new CodedInputStream(bytes);
Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum());
Assert.IsTrue(input.IsAtEnd);
}
//Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
[Test]
public void TestSlowPathAvoidance()
{
using (var ms = new MemoryStream())
{
CodedOutputStream output = new CodedOutputStream(ms);
output.WriteTag(1, WireFormat.WireType.LengthDelimited);
output.WriteBytes(ByteString.CopyFrom(new byte[100]));
output.WriteTag(2, WireFormat.WireType.LengthDelimited);
output.WriteBytes(ByteString.CopyFrom(new byte[100]));
output.Flush();
ms.Position = 0;
CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false);
uint tag = input.ReadTag();
Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
Assert.AreEqual(100, input.ReadBytes().Length);
tag = input.ReadTag();
Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
Assert.AreEqual(100, input.ReadBytes().Length);
}
}
[Test]
public void Tag0Throws()
{
var input = new CodedInputStream(new byte[] { 0 });
Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag());
}
[Test]
public void SkipGroup()
{
// Create an output stream with a group in:
// Field 1: string "field 1"
// Field 2: group containing:
// Field 1: fixed int32 value 100
// Field 2: string "ignore me"
// Field 3: nested group containing
// Field 1: fixed int64 value 1000
// Field 3: string "field 3"
var stream = new MemoryStream();
var output = new CodedOutputStream(stream);
output.WriteTag(1, WireFormat.WireType.LengthDelimited);
output.WriteString("field 1");
// The outer group...
output.WriteTag(2, WireFormat.WireType.StartGroup);
output.WriteTag(1, WireFormat.WireType.Fixed32);
output.WriteFixed32(100);
output.WriteTag(2, WireFormat.WireType.LengthDelimited);
output.WriteString("ignore me");
// The nested group...
output.WriteTag(3, WireFormat.WireType.StartGroup);
output.WriteTag(1, WireFormat.WireType.Fixed64);
output.WriteFixed64(1000);
// Note: Not sure the field number is relevant for end group...
output.WriteTag(3, WireFormat.WireType.EndGroup);
// End the outer group
output.WriteTag(2, WireFormat.WireType.EndGroup);
output.WriteTag(3, WireFormat.WireType.LengthDelimited);
output.WriteString("field 3");
output.Flush();
stream.Position = 0;
// Now act like a generated client
var input = new CodedInputStream(stream);
Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
Assert.AreEqual("field 1", input.ReadString());
Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
input.SkipLastField(); // Should consume the whole group, including the nested one.
Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag());
Assert.AreEqual("field 3", input.ReadString());
}
[Test]
public void SkipGroup_WrongEndGroupTag()
{
// Create an output stream with:
// Field 1: string "field 1"
// Start group 2
// Field 3: fixed int32
// End group 4 (should give an error)
var stream = new MemoryStream();
var output = new CodedOutputStream(stream);
output.WriteTag(1, WireFormat.WireType.LengthDelimited);
output.WriteString("field 1");
// The outer group...
output.WriteTag(2, WireFormat.WireType.StartGroup);
output.WriteTag(3, WireFormat.WireType.Fixed32);
output.WriteFixed32(100);
output.WriteTag(4, WireFormat.WireType.EndGroup);
output.Flush();
stream.Position = 0;
// Now act like a generated client
var input = new CodedInputStream(stream);
Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
Assert.AreEqual("field 1", input.ReadString());
Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
}
[Test]
public void RogueEndGroupTag()
{
// If we have an end-group tag without a leading start-group tag, generated
// code will just call SkipLastField... so that should fail.
var stream = new MemoryStream();
var output = new CodedOutputStream(stream);
output.WriteTag(1, WireFormat.WireType.EndGroup);
output.Flush();
stream.Position = 0;
var input = new CodedInputStream(stream);
Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag());
Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
}
[Test]
public void EndOfStreamReachedWhileSkippingGroup()
{
var stream = new MemoryStream();
var output = new CodedOutputStream(stream);
output.WriteTag(1, WireFormat.WireType.StartGroup);
output.WriteTag(2, WireFormat.WireType.StartGroup);
output.WriteTag(2, WireFormat.WireType.EndGroup);
output.Flush();
stream.Position = 0;
// Now act like a generated client
var input = new CodedInputStream(stream);
input.ReadTag();
Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
}
[Test]
public void RecursionLimitAppliedWhileSkippingGroup()
{
var stream = new MemoryStream();
var output = new CodedOutputStream(stream);
for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
{
output.WriteTag(1, WireFormat.WireType.StartGroup);
}
for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
{
output.WriteTag(1, WireFormat.WireType.EndGroup);
}
output.Flush();
stream.Position = 0;
// Now act like a generated client
var input = new CodedInputStream(stream);
Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag());
Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
}
[Test]
public void Construction_Invalid()
{
Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null));
Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0));
Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null));
Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10));
}
[Test]
public void CreateWithLimits_InvalidLimits()
{
var stream = new MemoryStream();
Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1));
Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0));
}
[Test]
public void Dispose_DisposesUnderlyingStream()
{
var memoryStream = new MemoryStream();
Assert.IsTrue(memoryStream.CanRead);
using (var cis = new CodedInputStream(memoryStream))
{
}
Assert.IsFalse(memoryStream.CanRead); // Disposed
}
[Test]
public void Dispose_WithLeaveOpen()
{
var memoryStream = new MemoryStream();
Assert.IsTrue(memoryStream.CanRead);
using (var cis = new CodedInputStream(memoryStream, true))
{
}
Assert.IsTrue(memoryStream.CanRead); // We left the stream open
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace Microsoft.AspNetCore.SignalR.Infrastructure
{
// A string equality comparer based on the SipHash-2-4 algorithm. Key differences:
// (a) we output 32-bit hashes instead of 64-bit hashes, and
// (b) we don't care about endianness since hashes are used only in hash tables
// and aren't returned to user code.
//
// Meant to serve as a replacement for StringComparer.Ordinal.
// Derivative work of https://github.com/tanglebones/ch-siphash.
internal unsafe sealed class SipHashBasedStringEqualityComparer : IEqualityComparer<string>
{
private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();
// the 128-bit secret key
private readonly ulong _k0;
private readonly ulong _k1;
public SipHashBasedStringEqualityComparer()
: this(GenerateRandomKeySegment(), GenerateRandomKeySegment())
{
}
// for unit testing
internal SipHashBasedStringEqualityComparer(ulong k0, ulong k1)
{
_k0 = k0;
_k1 = k1;
}
public bool Equals(string x, string y)
{
return String.Equals(x, y);
}
private static ulong GenerateRandomKeySegment()
{
byte[] bytes = new byte[sizeof(ulong)];
_rng.GetBytes(bytes);
return (ulong)BitConverter.ToInt64(bytes, 0);
}
public int GetHashCode(string obj)
{
if (obj == null)
{
return 0;
}
fixed (char* pChars = obj)
{
// treat input as an opaque blob, convert char count to byte count
return GetHashCode((byte*)pChars, checked((uint)obj.Length * sizeof(char)));
}
}
// for unit testing
internal int GetHashCode(byte* bytes, uint len)
{
// Assume SipHash-2-4 is a strong PRF, therefore truncation to 32 bits is acceptable.
return (int)SipHash_2_4_UlongCast_ForcedInline(bytes, len, _k0, _k1);
}
private static unsafe ulong SipHash_2_4_UlongCast_ForcedInline(byte* finb, uint inlen, ulong k0, ulong k1)
{
var v0 = 0x736f6d6570736575 ^ k0;
var v1 = 0x646f72616e646f6d ^ k1;
var v2 = 0x6c7967656e657261 ^ k0;
var v3 = 0x7465646279746573 ^ k1;
var b = ((ulong)inlen) << 56;
if (inlen > 0)
{
var inb = finb;
var left = inlen & 7;
var end = inb + inlen - left;
var linb = (ulong*)finb;
var lend = (ulong*)end;
for (; linb < lend; ++linb)
{
v3 ^= *linb;
v0 += v1;
v1 = (v1 << 13) | (v1 >> (64 - 13));
v1 ^= v0;
v0 = (v0 << 32) | (v0 >> (64 - 32));
v2 += v3;
v3 = (v3 << 16) | (v3 >> (64 - 16));
v3 ^= v2;
v0 += v3;
v3 = (v3 << 21) | (v3 >> (64 - 21));
v3 ^= v0;
v2 += v1;
v1 = (v1 << 17) | (v1 >> (64 - 17));
v1 ^= v2;
v2 = (v2 << 32) | (v2 >> (64 - 32));
v0 += v1;
v1 = (v1 << 13) | (v1 >> (64 - 13));
v1 ^= v0;
v0 = (v0 << 32) | (v0 >> (64 - 32));
v2 += v3;
v3 = (v3 << 16) | (v3 >> (64 - 16));
v3 ^= v2;
v0 += v3;
v3 = (v3 << 21) | (v3 >> (64 - 21));
v3 ^= v0;
v2 += v1;
v1 = (v1 << 17) | (v1 >> (64 - 17));
v1 ^= v2;
v2 = (v2 << 32) | (v2 >> (64 - 32));
v0 ^= *linb;
}
for (var i = 0; i < left; ++i)
{
b |= ((ulong)end[i]) << (8 * i);
}
}
v3 ^= b;
v0 += v1;
v1 = (v1 << 13) | (v1 >> (64 - 13));
v1 ^= v0;
v0 = (v0 << 32) | (v0 >> (64 - 32));
v2 += v3;
v3 = (v3 << 16) | (v3 >> (64 - 16));
v3 ^= v2;
v0 += v3;
v3 = (v3 << 21) | (v3 >> (64 - 21));
v3 ^= v0;
v2 += v1;
v1 = (v1 << 17) | (v1 >> (64 - 17));
v1 ^= v2;
v2 = (v2 << 32) | (v2 >> (64 - 32));
v0 += v1;
v1 = (v1 << 13) | (v1 >> (64 - 13));
v1 ^= v0;
v0 = (v0 << 32) | (v0 >> (64 - 32));
v2 += v3;
v3 = (v3 << 16) | (v3 >> (64 - 16));
v3 ^= v2;
v0 += v3;
v3 = (v3 << 21) | (v3 >> (64 - 21));
v3 ^= v0;
v2 += v1;
v1 = (v1 << 17) | (v1 >> (64 - 17));
v1 ^= v2;
v2 = (v2 << 32) | (v2 >> (64 - 32));
v0 ^= b;
v2 ^= 0xff;
v0 += v1;
v1 = (v1 << 13) | (v1 >> (64 - 13));
v1 ^= v0;
v0 = (v0 << 32) | (v0 >> (64 - 32));
v2 += v3;
v3 = (v3 << 16) | (v3 >> (64 - 16));
v3 ^= v2;
v0 += v3;
v3 = (v3 << 21) | (v3 >> (64 - 21));
v3 ^= v0;
v2 += v1;
v1 = (v1 << 17) | (v1 >> (64 - 17));
v1 ^= v2;
v2 = (v2 << 32) | (v2 >> (64 - 32));
v0 += v1;
v1 = (v1 << 13) | (v1 >> (64 - 13));
v1 ^= v0;
v0 = (v0 << 32) | (v0 >> (64 - 32));
v2 += v3;
v3 = (v3 << 16) | (v3 >> (64 - 16));
v3 ^= v2;
v0 += v3;
v3 = (v3 << 21) | (v3 >> (64 - 21));
v3 ^= v0;
v2 += v1;
v1 = (v1 << 17) | (v1 >> (64 - 17));
v1 ^= v2;
v2 = (v2 << 32) | (v2 >> (64 - 32));
v0 += v1;
v1 = (v1 << 13) | (v1 >> (64 - 13));
v1 ^= v0;
v0 = (v0 << 32) | (v0 >> (64 - 32));
v2 += v3;
v3 = (v3 << 16) | (v3 >> (64 - 16));
v3 ^= v2;
v0 += v3;
v3 = (v3 << 21) | (v3 >> (64 - 21));
v3 ^= v0;
v2 += v1;
v1 = (v1 << 17) | (v1 >> (64 - 17));
v1 ^= v2;
v2 = (v2 << 32) | (v2 >> (64 - 32));
v0 += v1;
v1 = (v1 << 13) | (v1 >> (64 - 13));
v1 ^= v0;
v0 = (v0 << 32) | (v0 >> (64 - 32));
v2 += v3;
v3 = (v3 << 16) | (v3 >> (64 - 16));
v3 ^= v2;
v0 += v3;
v3 = (v3 << 21) | (v3 >> (64 - 21));
v3 ^= v0;
v2 += v1;
v1 = (v1 << 17) | (v1 >> (64 - 17));
v1 ^= v2;
v2 = (v2 << 32) | (v2 >> (64 - 32));
return v0 ^ v1 ^ v2 ^ v3;
}
}
}
| |
//
// MessageView.cs
//
// Author:
// Prashant Cholachagudda <pvc@outlook.com>
//
// Copyright (c) 2013 Prashant Cholachagudda
//
// 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 UIKit;
using CoreGraphics;
using System;
using Foundation;
using System.Drawing;
namespace MessageBar
{
public class MessageView : UIView
{
static UIFont TitleFont;
static UIFont DescriptionFont;
static UIColor TitleColor;
const float Padding = 10.0f;
const int IOS7Identifier = 7;
readonly nfloat IconSize = 36.0f;
const float TextOffset = 2.0f;
static readonly UIColor DescriptionColor = null;
float height;
nfloat width;
NSString Title { get; set; }
new NSString Description { get; set; }
MessageType MessageType { get; set; }
public Action OnDismiss { get; set; }
public bool Hit { get; set; }
public float Height {
get {
if (height == 0) {
CGSize titleLabelSize = TitleSize ();
CGSize descriptionLabelSize = DescriptionSize ();
height = (float)Math.Max ((Padding * 2) + titleLabelSize.Height + descriptionLabelSize.Height, (Padding * 2) + IconSize);
}
return height;
}
private set {
height = value;
}
}
public nfloat Width {
get {
if (width == 0) {
width = GetStatusBarFrame ().Width;
}
return width;
}
private set {
width = value;
}
}
internal IStyleSheetProvider StylesheetProvider { get; set; }
nfloat AvailableWidth {
get {
nfloat maxWidth = (Width - (Padding * 3) - IconSize);
return maxWidth;
}
}
static MessageView ()
{
TitleFont = UIFont.BoldSystemFontOfSize (16.0f);
DescriptionFont = UIFont.SystemFontOfSize (14.0f);
TitleColor = UIColor.FromWhiteAlpha (1.0f, 1.0f);
DescriptionColor = UIColor.FromWhiteAlpha (1.0f, 1.0f);
}
internal MessageView (string title, string description, MessageType type)
: this ((NSString)title, (NSString)description, type)
{
}
internal MessageView (NSString title, NSString description, MessageType type)
: base (CGRect.Empty)
{
BackgroundColor = UIColor.Clear;
ClipsToBounds = false;
UserInteractionEnabled = true;
Title = title;
Description = description;
MessageType = type;
Height = 0.0f;
Width = 0.0f;
Hit = false;
NSNotificationCenter.DefaultCenter.AddObserver (UIDevice.OrientationDidChangeNotification, OrientationChanged);
}
void OrientationChanged (NSNotification notification)
{
Frame = new CGRect (Frame.X, Frame.Y, GetStatusBarFrame ().Width, Frame.Height);
SetNeedsDisplay ();
}
CGRect GetStatusBarFrame ()
{
var windowFrame = OrientFrame (UIApplication.SharedApplication.KeyWindow.Frame);
var statusFrame = OrientFrame (UIApplication.SharedApplication.StatusBarFrame);
return new CGRect (windowFrame.X, windowFrame.Y, windowFrame.Width, statusFrame.Height);
}
CGRect OrientFrame (CGRect frame)
{
//This size has already inverted in iOS8, but not on simulator, seems odd
if (!IsRunningiOS8OrLater () && (IsDeviceLandscape (UIDevice.CurrentDevice.Orientation) || IsStatusBarLandscape (UIApplication.SharedApplication.StatusBarOrientation))) {
frame = new CGRect (frame.X, frame.Y, frame.Height, frame.Width);
}
return frame;
}
bool IsDeviceLandscape (UIDeviceOrientation orientation)
{
return orientation == UIDeviceOrientation.LandscapeLeft || orientation == UIDeviceOrientation.LandscapeRight;
}
bool IsStatusBarLandscape (UIInterfaceOrientation orientation)
{
return orientation == UIInterfaceOrientation.LandscapeLeft || orientation == UIInterfaceOrientation.LandscapeRight;
}
public override void Draw (CGRect rect)
{
var context = UIGraphics.GetCurrentContext ();
MessageBarStyleSheet styleSheet = StylesheetProvider.StyleSheetForMessageView (this);
context.SaveState ();
styleSheet.BackgroundColorForMessageType (MessageType).SetColor ();
context.FillRect (rect);
context.RestoreState ();
context.SaveState ();
context.BeginPath ();
context.MoveTo (0, rect.Size.Height);
context.SetStrokeColor (styleSheet.StrokeColorForMessageType (MessageType).CGColor);
context.SetLineWidth (1);
context.AddLineToPoint (rect.Size.Width, rect.Size.Height);
context.StrokePath ();
context.RestoreState ();
context.SaveState ();
nfloat xOffset = Padding;
nfloat yOffset = Padding;
styleSheet.IconImageForMessageType (MessageType).Draw (new CGRect (xOffset, yOffset, IconSize, IconSize));
context.SaveState ();
yOffset -= TextOffset;
xOffset += IconSize + Padding;
CGSize titleLabelSize = TitleSize ();
if (string.IsNullOrEmpty (Title) && !string.IsNullOrEmpty (Description)) {
yOffset = (float)(Math.Ceiling ((double)rect.Size.Height * 0.5) - Math.Ceiling ((double)titleLabelSize.Height * 0.5) - TextOffset);
}
TitleColor.SetColor ();
var titleRectangle = new CGRect (xOffset, yOffset, titleLabelSize.Width, titleLabelSize.Height);
Title.DrawString (titleRectangle, TitleFont, UILineBreakMode.TailTruncation, UITextAlignment.Left);
yOffset += titleLabelSize.Height;
CGSize descriptionLabelSize = DescriptionSize ();
DescriptionColor.SetColor ();
var descriptionRectangle = new CGRect (xOffset, yOffset, descriptionLabelSize.Width, descriptionLabelSize.Height);
Description.DrawString (descriptionRectangle, DescriptionFont, UILineBreakMode.TailTruncation, UITextAlignment.Left);
}
CGSize TitleSize ()
{
var boundedSize = new SizeF ((float)AvailableWidth, float.MaxValue);
CGSize titleLabelSize;
if (!IsRunningiOS7OrLater ()) {
var attr = new UIStringAttributes (NSDictionary.FromObjectAndKey (TitleFont, (NSString)TitleFont.Name));
titleLabelSize = Title.GetBoundingRect (
boundedSize, NSStringDrawingOptions.TruncatesLastVisibleLine, attr, null).Size;
} else {
titleLabelSize = Title.StringSize (TitleFont, boundedSize, UILineBreakMode.TailTruncation);
}
return titleLabelSize;
}
CGSize DescriptionSize ()
{
var boundedSize = new CGSize (AvailableWidth, float.MaxValue);
CGSize descriptionLabelSize;
if (!IsRunningiOS7OrLater ()) {
var attr = new UIStringAttributes (NSDictionary.FromObjectAndKey (TitleFont, (NSString)TitleFont.Name));
descriptionLabelSize = Description.GetBoundingRect (
boundedSize, NSStringDrawingOptions.TruncatesLastVisibleLine, attr, null)
.Size;
} else {
descriptionLabelSize = Description.StringSize (
DescriptionFont, boundedSize, UILineBreakMode.TailTruncation);
}
return descriptionLabelSize;
}
bool IsRunningiOS7OrLater ()
{
string systemVersion = UIDevice.CurrentDevice.SystemVersion;
return IsRunningiOS8OrLater () || systemVersion.Contains ("7");
}
bool IsRunningiOS8OrLater ()
{
var systemVersion = int.Parse (UIDevice.CurrentDevice.SystemVersion.Substring (0, 1));
return systemVersion >= 8;
}
public override bool Equals (object obj)
{
if (!(obj is MessageView))
return false;
var messageView = (MessageView)obj;
return this.Title == messageView.Title && this.MessageType == messageView.MessageType && this.Description == messageView.Description;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.