context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Text;
#if FRB_MDX
using Microsoft.DirectX;
using Microsoft.DirectX.DirectInput;
#else
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
#endif
using FlatRedBall;
using FlatRedBall.Math;
using FlatRedBall.Math.Geometry;
#if !SILVERLIGHT
using FlatRedBall.Graphics;
#endif
namespace FlatRedBall.Input
{
#if !FRB_MDX
public delegate void ModifyMouseState(ref MouseState mouseState);
#endif
public class Mouse : IEquatable<Mouse>
{
#region Enums
public enum MouseButtons
{
LeftButton = 0,
RightButton = 1,
MiddleButton = 2,
XButton1 = 3,
XButton2 = 4
// Once extra buttons are added, modify the NumberOfButtons const below
}
#endregion
#region Fields
#region Static and Const Fields
public const int NumberOfButtons = (int)MouseButtons.XButton2 + 1;
public const float MaximumSecondsBetweenClickForDoubleClick = .25f;
#endregion
#region XNA and MDX-type Fields
#if !XBOX360
MouseState mMouseState;
MouseState mLastFrameMouseState = new MouseState();
#if SILVERLIGHT
MouseState mTemporaryMouseState = new MouseState();
#endif
#endif
#if FRB_MDX
BufferedDataCollection mMouseBufferedData;
MouseOffset[] mMouseOffset;
Device mMouseDevice;
System.Windows.Forms.Control mOwner;
#endif
#endregion
Dictionary<MouseButtons, DelegateBasedPressableInput> mButtons = new Dictionary<MouseButtons, DelegateBasedPressableInput>();
int mThisFrameRepositionX;
int mThisFrameRepositionY;
int mLastFrameRepositionX;
int mLastFrameRepositionY;
float mXVelocity;
float mYVelocity;
//bool mClearUntilNextClick = false;
double[] mLastClickTime;
double[] mLastPushTime;
bool[] mDoubleClick;
bool[] mDoublePush;
#if FRB_MDX
static bool[] mMouseButtonClicked;
static bool[] mMouseButtonPushed;
#endif
bool mWindowsCursorVisible = true;
#region XML docs
/// <summary>
/// The camera-relative X coordinate position of the Mouse at 100 units away.
/// </summary>
#endregion
float mXAt100Units;
float mYAt100Units;
int mLastWheel;
PositionedObject mGrabbedPositionedObject;
float mGrabbedPositionedObjectRelativeX;
float mGrabbedPositionedObjectRelativeY;
bool mActive = true;
bool mWasJustCleared = false;
#endregion
#region Properties
public bool AnyButtonPushed()
{
bool valueToReturn = false;
for (int i = 0; i < NumberOfButtons; i++)
{
valueToReturn |= ButtonPushed((MouseButtons)i);
}
return valueToReturn;
}
#if !XBOX360
public MouseState MouseState
{
get
{
return mMouseState;
}
}
public bool Active
{
get { return mActive; }
set
{
mActive = value;
}
}
#region XML Docs
/// <summary>
/// Grabs a PositionedObject. The PositionedObject will automatically update
/// its position according to mouse movement while the reference remains.
/// </summary>
#endregion
public PositionedObject GrabbedPositionedObject
{
get { return mGrabbedPositionedObject; }
set
{
if (value != null)
{
mGrabbedPositionedObjectRelativeX = value.X - WorldXAt(value.Z);
mGrabbedPositionedObjectRelativeY = value.Y - WorldYAt(value.Z);
}
mGrabbedPositionedObject = value;
}
}
DelegateBased1DInput scrollWheel;
public I1DInput ScrollWheel
{
get
{
#if FRB_MDX
throw new NotImplementedException();
#else
if(scrollWheel == null)
{
scrollWheel = new DelegateBased1DInput(
() => mMouseState.ScrollWheelValue / 120.0f,
() => ScrollWheelChange
);
}
return scrollWheel;
#endif
}
}
public float ScrollWheelChange
{
get
{
#if MONODROID
return InputManager.TouchScreen.PinchRatioChange;
#else
return (mMouseState.ScrollWheelValue - mLastWheel)/120.0f;
#endif
}
}
#endif
#if !WINDOWS_PHONE && !SILVERLIGHT && !MONOGAME
public bool IsOwnerFocused
{
get
{
#if XBOX360
return true;
#else
//bool value = false;
System.Windows.Forms.Control control = FlatRedBallServices.Owner;
bool returnValue = false;
while (true)
{
if (control == null)
{
returnValue = false;
break;
}
else if (control.Focused)
{
returnValue = true;
break;
}
control = control.Parent;
}
return returnValue;
#endif
}
}
#endif
#region XML Docs
/// <summary>
/// Returns the client rectangle-relative X pixel coordinate of the cursor.
/// </summary>
#endregion
public int X
{
get
{
#if FRB_MDX
return mOwner.PointToClient( System.Windows.Forms.Cursor.Position ).X;
#elif XBOX360
return 0;
#else
return mMouseState.X;
#endif
}
}
#region XML Docs
/// <summary>
/// Returns the client rectangle-Y pixel coordinate of the cursor.
/// </summary>
#endregion
public int Y
{
get
{
#if FRB_MDX
return mOwner.PointToClient( System.Windows.Forms.Cursor.Position ).Y;
#elif XBOX360
return 0;
#else
return mMouseState.Y;
#endif
}
}
#if !XBOX360
#region XML Docs
/// <summary>
/// The number of pixels that the mouse has moved on the
/// X axis during the last frame.
/// </summary>
#endregion
public int XChange
{
get
{
#if FRB_MDX
return mMouseState.X;
#else
return mMouseState.X - mLastFrameMouseState.X + mLastFrameRepositionX;
#endif
}
}
#region XML Docs
/// <summary>
/// The number of pixels that the mouse has moved on the
/// Y axis during the last frame.
/// </summary>
#endregion
public int YChange
{
get
{
#if FRB_MDX
return mMouseState.Y;
#else
return mMouseState.Y - mLastFrameMouseState.Y + mLastFrameRepositionY;
#endif
}
}
#region XML Docs
/// <summary>
/// The rate of change of the X property in
/// pixels per second.
/// </summary>
#endregion
public float XVelocity
{
get { return mXVelocity; }
}
#region XML Docs
/// <summary>
/// The rate of change of the Y property in
/// pixels per second.
/// </summary>
#endregion
public float YVelocity
{
get { return mYVelocity; }
}
#endif
#endregion
#region Events
#if !FRB_MDX
public static event ModifyMouseState ModifyMouseState;
#endif
#endregion
#region Methods
#region Constructor/Initialize
#if FRB_MDX
internal Mouse(System.Windows.Forms.Control owner, bool useWindowsCursor)
{
// This is needed to hide and show the Windows cursor
mOwner = owner;
mLastClickTime = new double[NumberOfButtons];
mLastPushTime = new double[NumberOfButtons];
mDoubleClick = new bool[NumberOfButtons];
mDoublePush = new bool[NumberOfButtons];
mMouseButtonClicked = new bool[NumberOfButtons];
mMouseButtonPushed = new bool[NumberOfButtons];
mMouseOffset = new MouseOffset[NumberOfButtons];
mMouseOffset[(int)MouseButtons.LeftButton] = MouseOffset.Button0;
mMouseOffset[(int)MouseButtons.RightButton] = MouseOffset.Button1;
mMouseOffset[(int)MouseButtons.MiddleButton] = MouseOffset.Button2;
mMouseOffset[(int)MouseButtons.XButton1] = MouseOffset.Button3;
mMouseOffset[(int)MouseButtons.XButton2] = MouseOffset.Button4;
mMouseDevice = new Device(SystemGuid.Mouse);
mMouseDevice.SetDataFormat(DeviceDataFormat.Mouse);
if (useWindowsCursor)
{
mWindowsCursorVisible = true;
mMouseDevice.SetCooperativeLevel(owner, CooperativeLevelFlags.Foreground |
CooperativeLevelFlags.NonExclusive);
}
else
{
mWindowsCursorVisible = false;
mMouseDevice.SetCooperativeLevel(owner, CooperativeLevelFlags.Foreground |
CooperativeLevelFlags.Exclusive);
}
try
{ mMouseDevice.Acquire(); }
catch (InputLostException)
{
// return;
}
catch (OtherApplicationHasPriorityException)
{
// return;
}
catch (System.ArgumentException)
{
}
// i don't know why this doesn't work, but input still works without it.
mMouseDevice.Properties.BufferSize = 5;
}
#else
internal Mouse(IntPtr windowHandle)
{
#if SILVERLIGHT
//SilverArcade.SilverSprite.Input.Mouse.WindowHandle = windowHandle;
mLastFrameMouseState = new MouseState();
mMouseState = new MouseState();
Microsoft.Xna.Framework.Input.Mouse.CreatesNewState = false;
#elif !MONOGAME
Microsoft.Xna.Framework.Input.Mouse.WindowHandle = windowHandle;
#endif
mLastClickTime = new double[NumberOfButtons];
mLastPushTime = new double[NumberOfButtons];
mDoubleClick = new bool[NumberOfButtons];
mDoublePush = new bool[NumberOfButtons];
}
#endif
internal void Initialize()
{
}
#endregion
#region Public Methods
public IPressableInput GetButton(MouseButtons button)
{
if(mButtons.ContainsKey(button) == false)
{
mButtons[button] = new DelegateBasedPressableInput(
() => this.ButtonDown(button),
() => this.ButtonPushed(button),
() => this.ButtonReleased(button)
);
}
return mButtons[button];
}
#region Button state methods (pushed, down, released, double clicked)
public bool ButtonPushed(MouseButtons button)
{
#if !XBOX360
//Removed checking for focus to keep consistent with the other mouse events.
//Checking should now be done manually
// bool isOwnerFocused = true;
//#if !WINDOWS_PHONE && !SILVERLIGHT && !MONODROID
// isOwnerFocused = IsOwnerFocused;
//#endif
if (mActive == false || InputManager.mIgnorePushesThisFrame) // || !isOwnerFocused)
return false;
#if FRB_MDX
if (mMouseBufferedData != null)
{
foreach (Microsoft.DirectX.DirectInput.BufferedData d in mMouseBufferedData)
{
if (d.Offset == (int)mMouseOffset[(int)button])
{
if ((d.Data & 0x80) != 0)
{
return true;
}
}
}
}
return false;
#else
switch (button)
{
case MouseButtons.LeftButton:
return !InputManager.CurrentFrameInputSuspended && mMouseState.LeftButton == ButtonState.Pressed && mLastFrameMouseState.LeftButton == ButtonState.Released;
case MouseButtons.RightButton:
return !InputManager.CurrentFrameInputSuspended && mMouseState.RightButton == ButtonState.Pressed && mLastFrameMouseState.RightButton == ButtonState.Released;
#if !SILVERLIGHT
case MouseButtons.MiddleButton:
return !InputManager.CurrentFrameInputSuspended && mMouseState.MiddleButton == ButtonState.Pressed && mLastFrameMouseState.MiddleButton == ButtonState.Released;
case MouseButtons.XButton1:
return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton1 == ButtonState.Pressed && mLastFrameMouseState.XButton1 == ButtonState.Released;
case MouseButtons.XButton2:
return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton2 == ButtonState.Pressed && mLastFrameMouseState.XButton2 == ButtonState.Released;
#endif
default:
return false;
}
#endif
#else
return false;
#endif
}
public bool ButtonReleased(MouseButtons button)
{
#if !XBOX360
// Silverlight has a null mMouseState at the beginning, so check for that.
bool isMouseStateNull = false;
#if SILVERLIGHT
isMouseStateNull = mMouseState == null;
#endif
if (mActive == false || isMouseStateNull)
return false;
#if FRB_MDX
return mMouseButtonClicked[(int)button];
#else
switch (button)
{
case MouseButtons.LeftButton:
return !InputManager.CurrentFrameInputSuspended &&
mMouseState.LeftButton == ButtonState.Released && mLastFrameMouseState.LeftButton == ButtonState.Pressed;
case MouseButtons.RightButton:
return !InputManager.CurrentFrameInputSuspended &&
mMouseState.RightButton == ButtonState.Released && mLastFrameMouseState.RightButton == ButtonState.Pressed;
#if !SILVERLIGHT
case MouseButtons.MiddleButton:
return !InputManager.CurrentFrameInputSuspended && mMouseState.MiddleButton == ButtonState.Released && mLastFrameMouseState.MiddleButton == ButtonState.Pressed;
case MouseButtons.XButton1:
return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton1 == ButtonState.Released && mLastFrameMouseState.XButton1 == ButtonState.Pressed;
case MouseButtons.XButton2:
return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton2 == ButtonState.Released && mLastFrameMouseState.XButton2 == ButtonState.Pressed;
#endif
default:
return false;
}
#endif
#else
return false;
#endif
}
public bool ButtonDown(MouseButtons button)
{
#if XBOX360
return false;
#else
if (mActive == false)
return false;
#if FRB_MDX
byte[] tempMouseButton = mMouseState.GetMouseButtons();
if (tempMouseButton != null && tempMouseButton.Length != 0)
return mMouseState.GetMouseButtons()[(int)button] != 0;
else
return false;
#else
switch (button)
{
case MouseButtons.LeftButton:
return !InputManager.CurrentFrameInputSuspended && mMouseState.LeftButton == ButtonState.Pressed;
case MouseButtons.RightButton:
return !InputManager.CurrentFrameInputSuspended && mMouseState.RightButton == ButtonState.Pressed;
#if !SILVERLIGHT
case MouseButtons.MiddleButton:
return !InputManager.CurrentFrameInputSuspended && mMouseState.MiddleButton == ButtonState.Pressed;
case MouseButtons.XButton1:
return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton1 == ButtonState.Pressed;
case MouseButtons.XButton2:
return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton2 == ButtonState.Pressed;
#endif
default:
return false;
}
#endif
#endif
}
#if !XBOX360
public bool ButtonDoubleClicked(MouseButtons button)
{
return mActive && !InputManager.CurrentFrameInputSuspended && mDoubleClick[(int)button];
}
public bool ButtonDoublePushed(MouseButtons button)
{
return mActive && !InputManager.CurrentFrameInputSuspended && mDoublePush[(int)button];
}
#endif
#endregion
//public void ClearUntilNextClick()
//{
// Clear();
// mClearUntilNextClick = true;
//}
public void Clear()
{
mWasJustCleared = true;
#if !XBOX360
#if FRB_MDX
for (int i = 0; i < mMouseButtonClicked.Length; i++)
mMouseButtonClicked[i] = false;
for (int i = 0; i < mMouseButtonPushed.Length; i++)
mMouseButtonPushed[i] = false;
for (int i = 0; i < mDoubleClick.Length; i++)
mDoubleClick[i] = false;
for (int i = 0; i < mDoublePush.Length; i++)
mDoublePush[i] = false;
mMouseState = new MouseState();
mMouseBufferedData = null;
#else
mMouseState = new MouseState();
mLastFrameMouseState = new MouseState();
#endif
#if SILVERLIGHT
mTemporaryMouseState = new MouseState();
#endif
#endif
}
#if !XBOX360
Vector3 mDefaultUpVector = new Vector3(0, 1, 0);
public void ControlPositionedObjectOrbit(PositionedObject positionedObject,
Vector3 orbitCenter, bool requireMiddleMouse)
{
ControlPositionedObjectOrbit(positionedObject, orbitCenter, requireMiddleMouse,
mDefaultUpVector);
}
public void ControlPositionedObjectOrbit(PositionedObject positionedObject,
Vector3 orbitCenter, bool requireMiddleMouse, Vector3 upVector)
{
const float coefficient = .00016f;
if (!requireMiddleMouse || this.ButtonDown(MouseButtons.MiddleButton))
{
if (XVelocity != 0)
{
float angleToRotateBy = -coefficient * XVelocity;
#if FRB_MDX
angleToRotateBy *= -1;
#endif
#if FRB_MDX
Matrix rotationMatrix = Matrix.RotationAxis(
upVector, angleToRotateBy);
#else
Matrix rotationMatrix = Matrix.CreateFromAxisAngle(upVector, angleToRotateBy);
#endif
positionedObject.Position -= orbitCenter;
MathFunctions.TransformVector(ref positionedObject.Position, ref rotationMatrix);
positionedObject.Position += orbitCenter;
//float x = positionedObject.X;
//float z = positionedObject.Z;
//FlatRedBall.Math.MathFunctions.RotatePointAroundPoint(
// orbitCenter.X, orbitCenter.Z, ref x, ref z, angleToRotateBy);
//positionedObject.X = x;
//positionedObject.Z = z;
}
if (YVelocity != 0)
{
Vector3 relativePosition = positionedObject.Position - orbitCenter;
#if FRB_MDX
Matrix transformation = Matrix.RotationAxis(
positionedObject.RotationMatrix.Right(), coefficient * YVelocity);
#else
Matrix transformation = Matrix.CreateFromAxisAngle(
positionedObject.RotationMatrix.Right, coefficient * -YVelocity);
#endif
FlatRedBall.Math.MathFunctions.TransformVector(
ref relativePosition, ref transformation);
positionedObject.Position = relativePosition + orbitCenter;
}
}
#if FRB_MDX
Vector3 forward = Vector3.Normalize(orbitCenter - positionedObject.Position);
Matrix matrix = positionedObject.RotationMatrix;
matrix.M31 = forward.X;
matrix.M32 = forward.Y;
matrix.M33 = forward.Z;
Vector3 right = Vector3.Normalize(Vector3.Cross(upVector, forward));
matrix.M11 = right.X;
matrix.M12 = right.Y;
matrix.M13 = right.Z;
Vector3 up = Vector3.Normalize(Vector3.Cross(forward, right));
matrix.M21 = up.X;
matrix.M22 = up.Y;
matrix.M23 = up.Z;
positionedObject.UpdateRotationValuesAccordingToMatrix(matrix);
// to fix accumulation and weird math issues:
positionedObject.RotationZ = positionedObject.RotationZ;
#else
Vector3 relativePositionForView = orbitCenter - positionedObject.Position;
// Vic says: Why do we invert? Well, because the CreateLookAt matrix method creates
// a matrix by which you multiply everything in the world to simulate the camera looking
// at an object. But we don't want to rotate the world to look like the camera is looking
// at a point - instead we want to rotate the camera so that it actually is looking at the point.
// FlatRedBall will take care of the actual inverting when it goes to draw the world.
positionedObject.RotationMatrix = Matrix.Invert(Matrix.CreateLookAt(new Vector3(), relativePositionForView, upVector));
#endif
#if !SILVERLIGHT
if (this.ScrollWheelChange != 0)
{
float scrollCoefficient = (positionedObject.Position - orbitCenter).Length() * .125f;
#if FRB_MDX
positionedObject.Position += scrollCoefficient *
this.ScrollWheelChange * positionedObject.RotationMatrix.Forward();
#else
positionedObject.Position += scrollCoefficient *
this.ScrollWheelChange * positionedObject.RotationMatrix.Forward;
#endif
}
#endif
}
#endif
#if !XBOX360
public Ray GetMouseRay(Camera camera)
{
#if FRB_MDX
// Not sure if this works for non-default Cameras
return MathFunctions.GetRay(this.mXAt100Units, this.mYAt100Units, camera);
#else
return MathFunctions.GetRay(X, Y, 1, camera);
//if (InputManager.Keyboard.KeyPushed(Keys.D))
//{
// int m = 3;
//}
//int screenX = X;
//int screenY = Y;
//Matrix matrix = Matrix.Invert(camera.TransformationMatrix);
//Matrix transformationMatrix = Matrix.CreateTranslation(camera.Position);
//Vector3 absoluteRayEnd = Renderer.GraphicsDevice.Viewport.Unproject(new Vector3(screenX, screenY, 1),
// camera.GetProjectionMatrix(), camera.GetLookAtMatrix(false), Matrix.Identity);
//Vector3 directionRay = absoluteRayEnd;
////Vector3 directionRay = absoluteRayEnd - camera.Position;
//directionRay.Normalize();
//return new Ray(camera.Position, directionRay);
#endif
}
#endif
public void HideNativeWindowsCursor()
{
#if FRB_MDX
if (mWindowsCursorVisible)
{
System.Windows.Forms.Cursor.Hide();
mWindowsCursorVisible = false;
try
{
mMouseDevice.Unacquire();
mMouseDevice.SetCooperativeLevel(mOwner, CooperativeLevelFlags.Foreground |
CooperativeLevelFlags.Exclusive);
mMouseDevice.Acquire();
}
catch (Exception)
{
}
}
#endif
}
#region XML Docs
/// <summary>
/// Returns whether the Mouse is over the argument Circle.
/// </summary>
/// <param name="circle">The Circle to check.</param>
/// <returns>Whether the mouse is over the argument Circle.</returns>
#endregion
public bool IsOn(Circle circle)
{
return circle.IsPointInside(WorldXAt(0), WorldYAt(0));
}
public bool IsOn(Circle circle, Camera camera)
{
return circle.IsPointInside(WorldXAt(0, camera), WorldYAt(0, camera));
}
public bool IsOn(Polygon polygon)
{
return polygon.IsPointInside(WorldXAt(polygon.Z), WorldYAt(polygon.Z));
}
public bool IsOn(Polygon polygon, Camera camera)
{
return polygon.IsPointInside(WorldXAt(polygon.Z, camera), WorldYAt(polygon.Z, camera));
}
public bool IsOn(AxisAlignedRectangle rectangle)
{
return rectangle.IsPointInside(WorldXAt(0), WorldYAt(0));
}
public bool IsOn(AxisAlignedRectangle rectangle, Camera camera)
{
return rectangle.IsPointInside(WorldXAt(0, camera), WorldYAt(0, camera));
}
public bool IsOn(Camera camera)
{
return X > camera.LeftDestination && X < camera.RightDestination &&
Y > camera.TopDestination && Y < camera.BottomDestination;
}
#if !XBOX360
public bool IsOn3D(FlatRedBall.Graphics.Text text, bool relativeToCamera)
{
Vector3 offset = new Vector3();
switch (text.HorizontalAlignment)
{
case FlatRedBall.Graphics.HorizontalAlignment.Left:
offset.X = text.ScaleX;
break;
case FlatRedBall.Graphics.HorizontalAlignment.Right:
offset.X = -text.ScaleX;
break;
}
switch (text.VerticalAlignment)
{
case FlatRedBall.Graphics.VerticalAlignment.Top:
offset.Y = -text.ScaleY;
break;
case FlatRedBall.Graphics.VerticalAlignment.Bottom:
offset.Y = text.ScaleY;
break;
}
text.Position += offset;
bool value = IsOn3D<FlatRedBall.Graphics.Text>(text, relativeToCamera);
text.Position -= offset;
return value;
}
#endif
#if !XBOX360
public bool IsOn3D<T>(T objectToTest, bool relativeToCamera) where T : IPositionable, IRotatable, IReadOnlyScalable
{
Vector3 temporaryVector = new Vector3();
return IsOn3D<T>(objectToTest, false, SpriteManager.Camera, ref temporaryVector);
}
public bool IsOn3D<T>(T objectToTest, bool relativeToCamera, ref Vector3 intersectionPoint)
where T : IPositionable, IRotatable, IReadOnlyScalable
{
return IsOn3D(objectToTest, relativeToCamera, SpriteManager.Camera, ref intersectionPoint);
}
public bool IsOn3D<T>(T objectToTest, bool relativeToCamera, Camera camera)
where T : IPositionable, IRotatable, IReadOnlyScalable
{
Vector3 temporaryVector = new Vector3();
return IsOn3D(objectToTest, relativeToCamera, camera, ref temporaryVector);
}
/// <summary>
/// Determines whether the Mouse is over the objectToTest argument.
/// </summary>
/// <remarks>
/// If a Text object is passed this method will only work appropriately if
/// the Text object has centered text. See the IsOn3D overload which takes a Text argument.
/// </remarks>
/// <typeparam name="T">The type of the first argument.</typeparam>
/// <param name="objectToTest">The object to test if the mouse is on.</param>
/// <param name="relativeToCamera">Whether the object's Position is relative to the Camera.</param>
/// <param name="camera"></param>
/// <param name="intersectionPoint">The point where the intersection between the ray casted from the
/// mouse into the distance and the argument objectToTest occurred.</param>
/// <returns>Whether the mouse is over the argument objectToTest</returns>
public bool IsOn3D<T>(T objectToTest, bool relativeToCamera, Camera camera, ref Vector3 intersectionPoint)
where T : IPositionable, IRotatable, IReadOnlyScalable
{
if (camera == SpriteManager.Camera)
{
return MathFunctions.IsOn3D<T>(
objectToTest,
relativeToCamera,
this.GetMouseRay(SpriteManager.Camera),
camera,
ref intersectionPoint);
}
else
{
float xAt100Units = 0;
float yAt100Units = 0;
FlatRedBall.Math.MathFunctions.WindowToAbsolute(
X - camera.DestinationRectangle.Left,
Y - camera.DestinationRectangle.Top,
ref xAt100Units, ref yAt100Units,
FlatRedBall.Math.MathFunctions.ForwardVector3.Z * 100, camera,
Camera.CoordinateRelativity.RelativeToCamera);
return MathFunctions.IsOn3D<T>(
objectToTest,
relativeToCamera,
this.GetMouseRay(SpriteManager.Camera),
camera,
ref intersectionPoint);
}
}
#endif
public bool IsInGameWindow()
{
#if SILVERLIGHT
return Microsoft.Xna.Framework.Input.Mouse.IsOnGameWindow;
#else
// Not sure why we do greater than 0 instead of greater than or equal to
// 0. On W8 the cursor initially starts at 0,0 and that is in the window,
// so we want to consider 0 inside.
return X >= 0 && X < FlatRedBallServices.ClientWidth &&
Y >= 0 && Y < FlatRedBallServices.ClientHeight;
#endif
}
#if !SILVERLIGHT && !XBOX360 && !WINDOWS_PHONE && !MONOGAME
public void SetScreenPosition(int newX, int newY)
{
// The velocity should not change when positions are set.
mThisFrameRepositionX += newX - System.Windows.Forms.Cursor.Position.X;
mThisFrameRepositionY += newY - System.Windows.Forms.Cursor.Position.Y;
System.Windows.Forms.Cursor.Position = new System.Drawing.Point(
newX,
newY);
}
#endif
public void ShowNativeWindowsCursor()
{
if (mWindowsCursorVisible == false)
{
#if FRB_MDX
System.Windows.Forms.Cursor.Show();
mWindowsCursorVisible = true;
try
{
mMouseDevice.Unacquire();
mMouseDevice.SetCooperativeLevel(mOwner, CooperativeLevelFlags.Foreground |
CooperativeLevelFlags.NonExclusive);
mMouseDevice.Acquire();
}
catch (Exception)
{
}
#endif
}
}
public override string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
#if !XBOX360
stringBuilder.Append("Internal MouseState:").Append(mMouseState.ToString());
#endif
stringBuilder.Append("\nWorldX at 100 units: ").Append(mXAt100Units);
stringBuilder.Append("\nWorldY at 100 units: ").Append(mYAt100Units);
#if !SILVERLIGHT && !XBOX360
stringBuilder.Append("\nScrollWheel: ").Append(ScrollWheelChange);
#endif
return stringBuilder.ToString();
}
#region World Values At
public float WorldXAt(float zValue)
{
return WorldXAt(zValue, SpriteManager.Camera);
}
public float WorldXAt(float zValue, Camera camera)
{
if (camera.Orthogonal == false)
{
if (camera == SpriteManager.Camera)
{
return camera.X +
FlatRedBall.Math.MathFunctions.ForwardVector3.Z * (zValue - camera.Z) * mXAt100Units / 100.0f;
}
else
{
float xAt100Units = 0;
float yAt100Units = 0;
#if !SILVERLIGHT
FlatRedBall.Math.MathFunctions.WindowToAbsolute(
X - camera.DestinationRectangle.Left,
Y - camera.DestinationRectangle.Top,
ref xAt100Units, ref yAt100Units,
FlatRedBall.Math.MathFunctions.ForwardVector3.Z * 100, camera,
Camera.CoordinateRelativity.RelativeToCamera);
#endif
return camera.X +
FlatRedBall.Math.MathFunctions.ForwardVector3.Z * (zValue - camera.Z) * xAt100Units / 100.0f;
}
}
else
{
return camera.X - camera.OrthogonalWidth / 2.0f + // left border
((X - camera.DestinationRectangle.Left) *camera.OrthogonalWidth/camera.DestinationRectangle.Width );
}
}
public float WorldYAt(float zValue)
{
return WorldYAt(zValue, SpriteManager.Camera);
}
public float WorldYAt(float zValue, Camera camera)
{
if (camera.Orthogonal == false)
{
if (camera == SpriteManager.Camera)
{
return camera.Y +
FlatRedBall.Math.MathFunctions.ForwardVector3.Z * (zValue - camera.Z) * mYAt100Units / 100;
}
else
{
float xAt100Units = 0;
float yAt100Units = 0;
#if !SILVERLIGHT
FlatRedBall.Math.MathFunctions.WindowToAbsolute(
X - camera.DestinationRectangle.Left,
Y - camera.DestinationRectangle.Top,
ref xAt100Units, ref yAt100Units,
FlatRedBall.Math.MathFunctions.ForwardVector3.Z * 100, camera,
Camera.CoordinateRelativity.RelativeToCamera);
#endif
return camera.Y +
FlatRedBall.Math.MathFunctions.ForwardVector3.Z * (zValue - camera.Z) * yAt100Units / 100;
}
}
else
{
return camera.Y + camera.OrthogonalHeight / 2.0f -
((Y - camera.TopDestination) * camera.OrthogonalHeight / camera.DestinationRectangle.Height);
}
}
#if !XBOX360
public float WorldXChangeAt(float zPosition)
{
int change = mMouseState.X - mLastFrameMouseState.X + mLastFrameRepositionX;
float resultX;
float dummy;
MathFunctions.ScreenToAbsoluteDistance(change, 0, out resultX, out dummy, zPosition, SpriteManager.Camera);
return resultX;
}
public float WorldYChangeAt(float zPosition)
{
int change = mMouseState.Y - mLastFrameMouseState.Y + mLastFrameRepositionY;
float resultY;
float dummy;
MathFunctions.ScreenToAbsoluteDistance(0, change, out dummy, out resultY, zPosition, SpriteManager.Camera);
return resultY;
}
#endif
#endregion
//#endif
#endregion
#if !XBOX360
#region Internal Methods
#if FRB_MDX
// These methods are called when the user hides and shows the cursor.
// FlatRedBallServices calls these methods.
internal void ReacquireExclusive()
{
try
{
mMouseDevice.Unacquire();
mMouseDevice.SetCooperativeLevel(mOwner, CooperativeLevelFlags.Foreground |
CooperativeLevelFlags.Exclusive);
mMouseDevice.Acquire();
}
catch (Exception)
{
// no big deal
}
}
internal void ReacquireNonExclusive()
{
try
{
mMouseDevice.Unacquire();
mMouseDevice.SetCooperativeLevel(mOwner, CooperativeLevelFlags.Foreground |
CooperativeLevelFlags.NonExclusive);
mMouseDevice.Acquire();
}
catch (Exception)
{
// no big deal
}
}
#endif
internal void Update(float secondDifference, double currentTime)
{
#if SILVERLIGHT
// Vic says - The temporary is needed so that clicking and pushing works properly
mLastFrameMouseState.X = mTemporaryMouseState.X;
mLastFrameMouseState.Y = mTemporaryMouseState.Y;
mLastFrameMouseState.LeftButton = mTemporaryMouseState.LeftButton;
mLastFrameMouseState.RightButton = mTemporaryMouseState.RightButton;
mTemporaryMouseState.X = mMouseState.X;
mTemporaryMouseState.Y = mMouseState.Y;
mTemporaryMouseState.LeftButton = mMouseState.LeftButton;
mTemporaryMouseState.RightButton = mMouseState.RightButton;
#else
mLastFrameMouseState = mMouseState;
#endif
mLastFrameRepositionX = mThisFrameRepositionX;
mLastFrameRepositionY = mThisFrameRepositionY;
mThisFrameRepositionX = 0;
mThisFrameRepositionY = 0;
#if FRB_MDX
mMouseBufferedData = null;
if (mMouseDevice.Properties.BufferSize != 0)
{
do
{// Try to get the current state
try
{
if (mMouseBufferedData != null)
mMouseBufferedData.Clear();
mMouseState = mMouseDevice.CurrentMouseState;
mMouseBufferedData = mMouseDevice.GetBufferedData();
break; // everything's ok, so we get out
}
catch (DirectXException)
{ // let the application handle Windows messages
try
{
System.Windows.Forms.Application.DoEvents();
}
catch (DirectXException)
{
continue;
}
// Try to get reacquire the mouse and don't care about exceptions
try { mMouseDevice.Acquire(); }
catch (InputLostException) { continue; }
catch (OtherApplicationHasPriorityException) { break; }
}
}
while (true); // Do this until it's successful
}
for (int i = 0; i < mMouseButtonClicked.Length; i++)
{
mMouseButtonClicked[i] = false;
mMouseButtonPushed[i] = false;
mDoubleClick[i] = false;
mDoublePush[i] = false;
}
if (mMouseBufferedData != null)
{
foreach (Microsoft.DirectX.DirectInput.BufferedData d in mMouseBufferedData)
{
for (int i = 0; i < mMouseOffset.Length; i++)
{
if (d.Offset == (int)mMouseOffset[i])
{
if ((d.Data & 0x80) == 0)
{
mMouseButtonClicked[i] = true;
if (TimeManager.CurrentTime - mLastClickTime[i] < .25f)
mDoubleClick[i] = true;
mLastClickTime[i] = TimeManager.CurrentTime;
break;
}
if ((d.Data & 0x80) == 0x80)
{
mMouseButtonPushed[i] = true;
if (TimeManager.CurrentTime - mLastPushTime[i] < .25f)
mDoublePush[i] = true;
mLastPushTime[i] = TimeManager.CurrentTime;
break;
}
}
}
}
}
mXVelocity = (mMouseState.X) / secondDifference;
mYVelocity = (mMouseState.Y) / secondDifference;
#else
XnaAndSilverlightSpecificUpdateLogic(secondDifference, currentTime);
#endif
//if (mClearUntilNextClick)
//{
// if (ButtonReleased(MouseButtons.LeftButton))
// {
// mClearUntilNextClick = false;
// }
// Clear();
//}
//else
{
FlatRedBall.Math.MathFunctions.WindowToAbsolute(
X - SpriteManager.Camera.DestinationRectangle.Left,
Y - SpriteManager.Camera.DestinationRectangle.Top,
ref mXAt100Units, ref mYAt100Units,
FlatRedBall.Math.MathFunctions.ForwardVector3.Z * 100, SpriteManager.Camera,
Camera.CoordinateRelativity.RelativeToCamera);
if (mGrabbedPositionedObject != null)
{
mGrabbedPositionedObject.X = WorldXAt(mGrabbedPositionedObject.Z) + mGrabbedPositionedObjectRelativeX;
mGrabbedPositionedObject.Y = WorldYAt(mGrabbedPositionedObject.Z) + mGrabbedPositionedObjectRelativeY;
}
}
}
private void XnaAndSilverlightSpecificUpdateLogic(float secondDifference, double currentTime)
{
#if FRB_XNA
mLastWheel = mMouseState.ScrollWheelValue;
#endif
#if SILVERLIGHT
mMouseState = Microsoft.Xna.Framework.Input.Mouse.GetState();
if (mMouseState == null)
{
// This is null the first frame.
mMouseState = new MouseState();
}
#elif FRB_XNA
mMouseState = Microsoft.Xna.Framework.Input.Mouse.GetState();
if (ModifyMouseState != null)
{
ModifyMouseState(ref mMouseState);
}
#if WINDOWS_8
// MonoGame behaves slightly
// differently compared to XNA.
// If the user runs the game in full
// screen in XNA (on the PC) then the
// back buffer size is set to the resolution
// of the game *as well as the display mode*.
// However, Windows 8 does not allow you to change
// the display mode, so the display mode always remains
// the native size of the device regardless of what the user
// does in regards to resolution and fullscreen. The MonoGame
// team decided to not change this - they want to use the actual
// display mode, which means the mouse will always return values based
// on the current resolution. This causes problems in FRB so I think I'm
// going to scale it.
if (
(FlatRedBallServices.GraphicsOptions.ResolutionWidth != FlatRedBallServices.Game.Window.ClientBounds.Width ||
FlatRedBallServices.GraphicsOptions.ResolutionHeight != FlatRedBallServices.Game.Window.ClientBounds.Height)
)
{
float scaleX = FlatRedBallServices.GraphicsOptions.ResolutionWidth / (float)FlatRedBallServices.Game.Window.ClientBounds.Width;
float scaleY = FlatRedBallServices.GraphicsOptions.ResolutionHeight / (float)FlatRedBallServices.Game.Window.ClientBounds.Height;
mMouseState = new MouseState(
FlatRedBall.Math.MathFunctions.RoundToInt(mMouseState.X * scaleX),
FlatRedBall.Math.MathFunctions.RoundToInt(mMouseState.Y * scaleY),
mMouseState.ScrollWheelValue,
mMouseState.LeftButton,
mMouseState.MiddleButton,
mMouseState.RightButton,
mMouseState.XButton1,
mMouseState.XButton2);
}
#endif
#endif
if (mWasJustCleared)
{
#if FRB_XNA
mLastWheel = mMouseState.ScrollWheelValue;
#endif
mWasJustCleared = false;
}
#region Update Double Click/Push
for (int i = 0; i < NumberOfButtons; i++)
{
mDoubleClick[i] = false;
mDoublePush[i] = false;
MouseButtons asMouseButton = (MouseButtons)i;
if (ButtonReleased(asMouseButton))
{
if (currentTime - mLastClickTime[i] < MaximumSecondsBetweenClickForDoubleClick)
{
mDoubleClick[i] = true;
}
mLastClickTime[i] = currentTime;
}
if (ButtonPushed(asMouseButton))
{
if (currentTime - mLastPushTime[i] < MaximumSecondsBetweenClickForDoubleClick)
{
mDoublePush[i] = true;
}
mLastPushTime[i] = currentTime;
}
}
#endregion
if (secondDifference != 0)
{
// If it's 0, then it means that this is the first frame. Just skip over
// setting velocity if that's the case.
mXVelocity = (mMouseState.X - mLastFrameMouseState.X) / secondDifference;
mYVelocity = (mMouseState.Y - mLastFrameMouseState.Y) / secondDifference;
}
}
#endregion
#region Private
// Not sure why this is here, but
// I don't think we use it
//struct VertexPositionNormal
//{
// public Vector3 Position;
// public Vector3 Normal;
//}
#endregion
#endif
#endregion
#region IEquatable<Mouse> Members
bool IEquatable<Mouse>.Equals(Mouse other)
{
return this == other;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// HeaderOperations operations.
/// </summary>
internal partial class HeaderOperations : Microsoft.Rest.IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IHeaderOperations
{
/// <summary>
/// Initializes a new instance of the HeaderOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal HeaderOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the
/// header of the request
/// </summary>
/// <param name='fooClientRequestId'>
/// The fooRequestId
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<HeaderCustomNamedRequestIdHeaders>> CustomNamedRequestIdWithHttpMessagesAsync(string fooClientRequestId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (fooClientRequestId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fooClientRequestId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("fooClientRequestId", fooClientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestId", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestId").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", System.Guid.NewGuid().ToString());
}
if (fooClientRequestId != null)
{
if (_httpRequest.Headers.Contains("foo-client-request-id"))
{
_httpRequest.Headers.Remove("foo-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId);
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<HeaderCustomNamedRequestIdHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("foo-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HeaderCustomNamedRequestIdHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the
/// header of the request, via a parameter group
/// </summary>
/// <param name='headerCustomNamedRequestIdParamGroupingParameters'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<HeaderCustomNamedRequestIdParamGroupingHeaders>> CustomNamedRequestIdParamGroupingWithHttpMessagesAsync(HeaderCustomNamedRequestIdParamGroupingParameters headerCustomNamedRequestIdParamGroupingParameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (headerCustomNamedRequestIdParamGroupingParameters == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "headerCustomNamedRequestIdParamGroupingParameters");
}
if (headerCustomNamedRequestIdParamGroupingParameters != null)
{
headerCustomNamedRequestIdParamGroupingParameters.Validate();
}
string fooClientRequestId = default(string);
if (headerCustomNamedRequestIdParamGroupingParameters != null)
{
fooClientRequestId = headerCustomNamedRequestIdParamGroupingParameters.FooClientRequestId;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("fooClientRequestId", fooClientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestIdParamGrouping", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestIdParamGrouping").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (fooClientRequestId != null)
{
if (_httpRequest.Headers.Contains("foo-client-request-id"))
{
_httpRequest.Headers.Remove("foo-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<HeaderCustomNamedRequestIdParamGroupingHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("foo-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HeaderCustomNamedRequestIdParamGroupingHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Hosting
{
/// <summary>
/// A mutable collection of <see cref="ComposablePartCatalog"/>s.
/// </summary>
/// <remarks>
/// This type is thread safe.
/// </remarks>
public class AggregateCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged
{
private ComposablePartCatalogCollection _catalogs = null;
private volatile int _isDisposed = 0;
/// <summary>
/// Initializes a new instance of the <see cref="AggregateCatalog"/> class.
/// </summary>
public AggregateCatalog()
: this((IEnumerable<ComposablePartCatalog>)null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateCatalog"/> class
/// with the specified catalogs.
/// </summary>
/// <param name="catalogs">
/// An <see cref="Array"/> of <see cref="ComposablePartCatalog"/> objects to add to the
/// <see cref="AggregateCatalog"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="catalogs"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
/// </exception>
public AggregateCatalog(params ComposablePartCatalog[] catalogs)
: this((IEnumerable<ComposablePartCatalog>)catalogs)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateCatalog"/> class
/// with the specified catalogs.
/// </summary>
/// <param name="catalogs">
/// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartCatalog"/> objects to add
/// to the <see cref="AggregateCatalog"/>; or <see langword="null"/> to
/// create an <see cref="AggregateCatalog"/> that is empty.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
/// </exception>
public AggregateCatalog(IEnumerable<ComposablePartCatalog> catalogs)
{
Requires.NullOrNotNullElements(catalogs, nameof(catalogs));
_catalogs = new ComposablePartCatalogCollection(catalogs, OnChanged, OnChanging);
}
/// <summary>
/// Notify when the contents of the Catalog has changed.
/// </summary>
public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed
{
add
{
_catalogs.Changed += value;
}
remove
{
_catalogs.Changed -= value;
}
}
/// <summary>
/// Notify when the contents of the Catalog has changing.
/// </summary>
public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing
{
add
{
_catalogs.Changing += value;
}
remove
{
_catalogs.Changing -= value;
}
}
/// <summary>
/// Returns the export definitions that match the constraint defined by the specified definition.
/// </summary>
/// <param name="definition">
/// The <see cref="ImportDefinition"/> that defines the conditions of the
/// <see cref="ExportDefinition"/> objects to return.
/// </param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the
/// <see cref="ExportDefinition"/> objects and their associated
/// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined
/// by <paramref name="definition"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="definition"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="AggregateCatalog"/> has been disposed of.
/// </exception>
public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
{
ThrowIfDisposed();
Requires.NotNull(definition, nameof(definition));
// We optimize for the case where the result is comparible with the requested cardinality, though we do remain correct in all cases.
// We do so to avoid any unnecessary allocations
IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> result = null;
List<Tuple<ComposablePartDefinition, ExportDefinition>> aggregateResult = null;
foreach (var catalog in _catalogs)
{
var catalogExports = catalog.GetExports(definition);
if (catalogExports != ComposablePartCatalog._EmptyExportsList)
{
// ideally this is is the case we will always hit
if (result == null)
{
result = catalogExports;
}
else
{
// sadly the result has already been assigned, which means we are in the aggregate case
if (aggregateResult == null)
{
aggregateResult = new List<Tuple<ComposablePartDefinition, ExportDefinition>>(result);
result = aggregateResult;
}
aggregateResult.AddRange(catalogExports);
}
}
}
return result ?? ComposablePartCatalog._EmptyExportsList;
}
/// <summary>
/// Gets the underlying catalogs of the catalog.
/// </summary>
/// <value>
/// An <see cref="ICollection{T}"/> of underlying <see cref="ComposablePartCatalog"/> objects
/// of the <see cref="AggregateCatalog"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// The <see cref="AggregateCatalog"/> has been disposed of.
/// </exception>
public ICollection<ComposablePartCatalog> Catalogs
{
get
{
ThrowIfDisposed();
Contract.Ensures(Contract.Result<ICollection<ComposablePartCatalog>>() != null);
return _catalogs;
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
// NOTE : According to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0420, the warning is bogus when used with Interlocked API.
#pragma warning disable 420
if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0)
#pragma warning restore 420
{
_catalogs.Dispose();
}
}
}
finally
{
base.Dispose(disposing);
}
}
public override IEnumerator<ComposablePartDefinition> GetEnumerator()
{
return _catalogs.SelectMany(catalog => catalog).GetEnumerator();
}
/// <summary>
/// Raises the <see cref="INotifyComposablePartCatalogChanged.Changed"/> event.
/// </summary>
/// <param name="e">
/// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
/// </param>
protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
{
_catalogs.OnChanged(this, e);
}
/// <summary>
/// Raises the <see cref="INotifyComposablePartCatalogChanged.Changing"/> event.
/// </summary>
/// <param name="e">
/// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
/// </param>
protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
{
_catalogs.OnChanging(this, e);
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed == 1)
{
throw ExceptionBuilder.CreateObjectDisposed(this);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u32 = System.UInt32;
namespace System.Data.SQLite
{
internal partial class Sqlite3
{
/*
** 2001 September 22
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of generic hash-tables
** used in SQLite.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include <assert.h>
/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
*/
static void sqlite3HashInit(Hash pNew)
{
Debug.Assert(pNew != null);
pNew.first = null;
pNew.count = 0;
pNew.htsize = 0;
pNew.ht = null;
}
/* Remove all entries from a hash table. Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
static void sqlite3HashClear(Hash pH)
{
HashElem elem; /* For looping over all elements of the table */
Debug.Assert(pH != null);
elem = pH.first;
pH.first = null;
//sqlite3_free( ref pH.ht );
pH.ht = null;
pH.htsize = 0;
while (elem != null)
{
HashElem next_elem = elem.next;
////sqlite3_free(ref elem );
elem = next_elem;
}
pH.count = 0;
}
/*
** The hashing function.
*/
static u32 strHash(string z, int nKey)
{
int h = 0;
Debug.Assert(nKey >= 0);
int _z = 0;
while (nKey > 0)
{
h = (h << 3) ^ h ^ ((_z < z.Length) ? (int)sqlite3UpperToLower[(byte)z[_z++]] : 0);
nKey--;
}
return (u32)h;
}
/* Link pNew element into the hash table pH. If pEntry!=0 then also
** insert pNew into the pEntry hash bucket.
*/
static void insertElement(
Hash pH, /* The complete hash table */
_ht pEntry, /* The entry into which pNew is inserted */
HashElem pNew /* The element to be inserted */
)
{
HashElem pHead; /* First element already in pEntry */
if (pEntry != null)
{
pHead = pEntry.count != 0 ? pEntry.chain : null;
pEntry.count++;
pEntry.chain = pNew;
}
else
{
pHead = null;
}
if (pHead != null)
{
pNew.next = pHead;
pNew.prev = pHead.prev;
if (pHead.prev != null)
{
pHead.prev.next = pNew;
}
else
{
pH.first = pNew;
}
pHead.prev = pNew;
}
else
{
pNew.next = pH.first;
if (pH.first != null)
{
pH.first.prev = pNew;
}
pNew.prev = null;
pH.first = pNew;
}
}
/* Resize the hash table so that it cantains "new_size" buckets.
**
** The hash table might fail to resize if sqlite3_malloc() fails or
** if the new size is the same as the prior size.
** Return TRUE if the resize occurs and false if not.
*/
static bool rehash(ref Hash pH, u32 new_size)
{
_ht[] new_ht; /* The new hash table */
HashElem elem;
HashElem next_elem; /* For looping over existing elements */
#if SQLITE_MALLOC_SOFT_LIMIT
if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
}
if( new_size==pH->htsize ) return false;
#endif
/* There is a call to sqlite3Malloc() inside rehash(). If there is
** already an allocation at pH.ht, then if this malloc() fails it
** is benign (since failing to resize a hash table is a performance
** hit only, not a fatal error).
*/
sqlite3BeginBenignMalloc();
new_ht = new _ht[new_size]; //(struct _ht )sqlite3Malloc( new_size*sizeof(struct _ht) );
for (int i = 0; i < new_size; i++)
new_ht[i] = new _ht();
sqlite3EndBenignMalloc();
if (new_ht == null)
return false;
//sqlite3_free( ref pH.ht );
pH.ht = new_ht;
// pH.htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
//memset(new_ht, 0, new_size*sizeof(struct _ht));
pH.htsize = new_size;
for (elem = pH.first, pH.first = null; elem != null; elem = next_elem)
{
u32 h = strHash(elem.pKey, elem.nKey) % new_size;
next_elem = elem.next;
insertElement(pH, new_ht[h], elem);
}
return true;
}
/* This function (for internal use only) locates an element in an
** hash table that matches the given key. The hash for this key has
** already been computed and is passed as the 4th parameter.
*/
static HashElem findElementGivenHash(
Hash pH, /* The pH to be searched */
string pKey, /* The key we are searching for */
int nKey, /* Bytes in key (not counting zero terminator) */
u32 h /* The hash for this key. */
)
{
HashElem elem; /* Used to loop thru the element list */
int count; /* Number of elements left to test */
if (pH.ht != null && pH.ht[h] != null)
{
_ht pEntry = pH.ht[h];
elem = pEntry.chain;
count = (int)pEntry.count;
}
else
{
elem = pH.first;
count = (int)pH.count;
}
while (count-- > 0 && ALWAYS(elem))
{
if (elem.nKey == nKey && elem.pKey.Equals(pKey, StringComparison.InvariantCultureIgnoreCase))
{
return elem;
}
elem = elem.next;
}
return null;
}
/* Remove a single entry from the hash table given a pointer to that
** element and a hash on the element's key.
*/
static void removeElementGivenHash(
Hash pH, /* The pH containing "elem" */
ref HashElem elem, /* The element to be removed from the pH */
u32 h /* Hash value for the element */
)
{
_ht pEntry;
if (elem.prev != null)
{
elem.prev.next = elem.next;
}
else
{
pH.first = elem.next;
}
if (elem.next != null)
{
elem.next.prev = elem.prev;
}
if (pH.ht != null && pH.ht[h] != null)
{
pEntry = pH.ht[h];
if (pEntry.chain == elem)
{
pEntry.chain = elem.next;
}
pEntry.count--;
Debug.Assert(pEntry.count >= 0);
}
//sqlite3_free( ref elem );
pH.count--;
if (pH.count <= 0)
{
Debug.Assert(pH.first == null);
Debug.Assert(pH.count == 0);
sqlite3HashClear(pH);
}
}
/* Attempt to locate an element of the hash table pH with a key
** that matches pKey,nKey. Return the data for this element if it is
** found, or NULL if there is no match.
*/
static T sqlite3HashFind<T>(Hash pH, string pKey, int nKey, T nullType) where T : class
{
HashElem elem; /* The element that matches key */
u32 h; /* A hash on key */
Debug.Assert(pH != null);
Debug.Assert(pKey != null);
Debug.Assert(nKey >= 0);
if (pH.ht != null)
{
h = strHash(pKey, nKey) % pH.htsize;
}
else
{
h = 0;
}
elem = findElementGivenHash(pH, pKey, nKey, h);
return elem != null ? (T)elem.data : nullType;
}
/* Insert an element into the hash table pH. The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created and NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance. If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
static T sqlite3HashInsert<T>(ref Hash pH, string pKey, int nKey, T data) where T : class
{
u32 h; /* the hash of the key modulo hash table size */
HashElem elem; /* Used to loop thru the element list */
HashElem new_elem; /* New element added to the pH */
Debug.Assert(pH != null);
Debug.Assert(pKey != null);
Debug.Assert(nKey >= 0);
if (pH.htsize != 0)
{
h = strHash(pKey, nKey) % pH.htsize;
}
else
{
h = 0;
}
elem = findElementGivenHash(pH, pKey, nKey, h);
if (elem != null)
{
T old_data = (T)elem.data;
if (data == null)
{
removeElementGivenHash(pH, ref elem, h);
}
else
{
elem.data = data;
elem.pKey = pKey;
Debug.Assert(nKey == elem.nKey);
}
return old_data;
}
if (data == null)
return data;
new_elem = new HashElem();//(HashElem)sqlite3Malloc( sizeof(HashElem) );
if (new_elem == null)
return data;
new_elem.pKey = pKey;
new_elem.nKey = nKey;
new_elem.data = data;
pH.count++;
if (pH.count >= 10 && pH.count > 2 * pH.htsize)
{
if (rehash(ref pH, pH.count * 2))
{
Debug.Assert(pH.htsize > 0);
h = strHash(pKey, nKey) % pH.htsize;
}
}
if (pH.ht != null)
{
insertElement(pH, pH.ht[h], new_elem);
}
else
{
insertElement(pH, null, new_elem);
}
return null;
}
}
}
| |
// 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 MoveMaskVector128Byte()
{
var test = new SimdScalarUnaryOpConvertTest__MoveMaskVector128Byte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimdScalarUnaryOpConvertTest__MoveMaskVector128Byte
{
private struct TestStruct
{
public Vector128<Byte> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimdScalarUnaryOpConvertTest__MoveMaskVector128Byte testClass)
{
var result = Sse2.MoveMask(_fld);
testClass.ValidateResult(_fld, result);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data = new Byte[Op1ElementCount];
private static Vector128<Byte> _clsVar;
private Vector128<Byte> _fld;
private SimdScalarUnaryOpTest__DataTable<Byte> _dataTable;
static SimdScalarUnaryOpConvertTest__MoveMaskVector128Byte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimdScalarUnaryOpConvertTest__MoveMaskVector128Byte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new SimdScalarUnaryOpTest__DataTable<Byte>(_data, LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.MoveMask(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr)
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.MoveMask(
Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr))
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.MoveMask(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr))
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MoveMask), new Type[] { typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr)
});
ValidateResult(_dataTable.inArrayPtr, (Int32)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MoveMask), new Type[] { typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr))
});
ValidateResult(_dataTable.inArrayPtr, (Int32)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MoveMask), new Type[] { typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr))
});
ValidateResult(_dataTable.inArrayPtr, (Int32)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.MoveMask(
_clsVar
);
ValidateResult(_clsVar, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr);
var result = Sse2.MoveMask(firstOp);
ValidateResult(firstOp, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr));
var result = Sse2.MoveMask(firstOp);
ValidateResult(firstOp, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr));
var result = Sse2.MoveMask(firstOp);
ValidateResult(firstOp, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimdScalarUnaryOpConvertTest__MoveMaskVector128Byte();
var result = Sse2.MoveMask(test._fld);
ValidateResult(test._fld, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.MoveMask(_fld);
ValidateResult(_fld, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.MoveMask(test._fld);
ValidateResult(test._fld, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> firstOp, Int32 result, [CallerMemberName] string method = "")
{
Byte[] inArray = new Byte[Op1ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), firstOp);
ValidateResult(inArray, result, method);
}
private void ValidateResult(void* firstOp, Int32 result, [CallerMemberName] string method = "")
{
Byte[] inArray = new Byte[Op1ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray, result, method);
}
private void ValidateResult(Byte[] firstOp, Int32 result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (((firstOp[0] & 128) == 0) != ((result & 1) == 0))
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.MoveMask)}<Int32>(Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: result");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
#region Copyright
// Copyright 2014 Myrcon Pty. Ltd.
//
// 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.IO;
using System.Net;
using System.Net.Sockets;
namespace Potato.Net.Shared {
public class TcpClient : Client {
/// <summary>
/// The open client connection.
/// </summary>
protected System.Net.Sockets.TcpClient Client;
/// <summary>
/// The stream to read and write data to.
/// </summary>
protected Stream Stream;
/// <summary>
/// Buffer for the data currently being read from the stream. This is appended to the received buffer.
/// </summary>
protected IPacketStream PacketStream;
/// <summary>
/// How much data should be read when peeking for the full packet size.
/// </summary>
protected virtual long ReadPacketPeekShiftSize {
get { return this.PacketSerializer != null ? this.PacketSerializer.PacketHeaderSize : 0; }
}
protected TcpClient() : base() {
this.ReceivedBuffer = new byte[this.BufferSize];
this.PacketStream = new PacketStream();
}
/// <summary>
/// Return for when the packet has been written (or an error occurs during write) to the
/// server.
/// </summary>
/// <param name="ar"></param>
protected void SendAsynchronousCallback(IAsyncResult ar) {
IPacketWrapper packet = (IPacketWrapper)ar.AsyncState;
if (this.Stream != null) {
try {
this.Stream.EndWrite(ar);
this.OnPacketSent(packet);
}
catch (SocketException se) {
this.Shutdown(se);
}
catch (Exception e) {
this.Shutdown(e);
}
}
}
/// <summary>
/// Sends a packet to the server asynchronously
/// </summary>
/// <param name="wrapper"></param>
public override IPacket Send(IPacketWrapper wrapper) {
IPacket sent = null;
if (wrapper != null) {
if (this.BeforePacketSend(wrapper) == false && this.Stream != null) {
byte[] bytePacket = this.PacketSerializer.Serialize(wrapper);
if (bytePacket != null && bytePacket.Length > 0) {
try {
this.Stream.BeginWrite(bytePacket, 0, bytePacket.Length, this.SendAsynchronousCallback, wrapper);
sent = wrapper.Packet;
}
catch (Exception e) {
this.Shutdown(e);
}
}
}
}
return sent;
}
/// <summary>
/// Attempts to read a single packet from the PacketStream
/// </summary>
/// <returns>A completed packet, or null if no packet could be read.</returns>
protected virtual IPacketWrapper ReadPacket() {
IPacketWrapper wrapper = null;
byte[] header = this.PacketStream.PeekShift((uint)this.ReadPacketPeekShiftSize);
if (header != null) {
long packetSize = this.PacketSerializer.ReadPacketSize(header);
byte[] packetData = this.PacketStream.PeekShift((uint)packetSize);
if (packetData != null && packetData.Length > 0) {
wrapper = this.PacketSerializer.Deserialize(packetData);
wrapper.Packet.RemoteEndPoint = this.RemoteEndPoint;
this.PacketStream.Shift((uint)packetSize);
}
}
return wrapper;
}
protected virtual void ReadCallback(IAsyncResult ar) {
if (this.Stream != null) {
try {
int bytesRead = this.Stream.EndRead(ar);
if (bytesRead > 0) {
this.PacketStream.Push(this.ReceivedBuffer, bytesRead);
IPacketWrapper wrapper = null;
// Keep reading until we no longer have packets to deserialize.
while ((wrapper = this.ReadPacket()) != null) {
// Dispatch the completed packet.
try {
this.BeforePacketDispatch(wrapper);
this.OnPacketReceived(wrapper);
}
catch (Exception e) {
this.Shutdown(e);
}
}
// If we've recieved the maxmimum garbage, scrap it all and shutdown the connection.
// We went really wrong somewhere..
if (this.ReceivedBuffer != null && this.ReceivedBuffer.Length >= this.MaxGarbageBytes) {
this.ReceivedBuffer = null;
this.Shutdown(new Exception("Exceeded maximum garbage packet"));
}
else if (this.Stream != null) {
this.BeginRead();
}
}
else {
this.Shutdown();
}
}
catch (Exception e) {
this.Shutdown(e);
}
}
else {
this.Shutdown(new Exception("No stream exists during receive"));
}
}
/// <summary>
/// Starts reading on a network stream
/// </summary>
/// <returns></returns>
public override IAsyncResult BeginRead() {
return this.Stream != null ? this.Stream.BeginRead(this.ReceivedBuffer, 0, this.ReceivedBuffer.Length, this.ReadCallback, this) : null;
}
/// <summary>
/// Callback when attempting to connect to the server.
/// </summary>
/// <param name="ar"></param>
private void ConnectedCallback(IAsyncResult ar) {
try {
this.Client.EndConnect(ar);
this.Client.NoDelay = true;
this.ConnectionState = ConnectionState.ConnectionConnected;
this.LocalEndPoint = (IPEndPoint)this.Client.Client.LocalEndPoint;
this.RemoteEndPoint = (IPEndPoint)this.Client.Client.RemoteEndPoint;
this.Stream = this.Client.GetStream();
this.BeginRead();
this.ConnectionState = ConnectionState.ConnectionReady;
}
catch (SocketException se) {
this.Shutdown(se);
}
catch {
this.Shutdown(new Exception("Could not establish connection to endpoint"));
}
}
/// <summary>
/// Attempts a connection to a server, provided we are not currently backing off from an offline server.
/// </summary>
public override void Connect() {
if (this.MarkManager.RemoveExpiredMarks().IsValidMarkWindow() == true) {
this.MarkManager.Mark();
if (this.Options.Hostname != null && this.Options.Port != 0) {
try {
this.ReceivedBuffer = new byte[this.BufferSize];
this.PacketStream = new PacketStream();
this.SequenceNumber = 0;
this.ConnectionState = ConnectionState.ConnectionConnecting;
this.Client = new System.Net.Sockets.TcpClient {
NoDelay = true
};
this.Client.BeginConnect(this.Options.Hostname, this.Options.Port, this.ConnectedCallback, this);
}
catch (SocketException se) {
this.Shutdown(se);
}
catch (Exception e) {
this.Shutdown(e);
}
}
}
}
/// <summary>
/// Shuts down the connection, first firing an event for an exception.
/// </summary>
/// <param name="e"></param>
public override void Shutdown(Exception e) {
if (this.Client != null) {
this.ShutdownConnection();
this.OnConnectionFailure(e);
}
}
/// <summary>
/// Shuts down the connection, first firing an event for a socket exception.
/// </summary>
/// <param name="se"></param>
public override void Shutdown(SocketException se) {
if (this.Client != null) {
this.ShutdownConnection();
this.OnSocketException(se);
}
}
/// <summary>
/// Shuts down the connection, closing streams etc.
/// </summary>
public override void Shutdown() {
if (this.Client != null) {
this.ShutdownConnection();
}
}
/// <summary>
/// Shuts down the connection, closing the Client.
/// </summary>
protected override void ShutdownConnection() {
lock (this.ShutdownConnectionLock) {
this.ConnectionState = ConnectionState.ConnectionDisconnecting;
if (this.Client != null) {
try {
if (this.Stream != null) {
this.Stream.Close();
this.Stream.Dispose();
this.Stream = null;
}
if (this.Client != null) {
this.Client.Close();
this.Client = null;
}
}
catch (SocketException se) {
this.OnSocketException(se);
}
catch (Exception e) {
this.OnConnectionFailure(e);
}
finally {
this.ConnectionState = ConnectionState.ConnectionDisconnected;
}
}
else {
// Nothing open, let's disconnect.
this.ConnectionState = ConnectionState.ConnectionDisconnected;
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Cache
{
/// <summary>
/// Cache metrics used to obtain statistics on cache itself.
/// </summary>
public interface ICacheMetrics
{
/// <summary>
/// The number of get requests that were satisfied by the cache.
/// </summary>
/// <returns>
/// The number of hits.
/// </returns>
long CacheHits { get; }
/// <summary>
/// This is a measure of cache efficiency.
/// </summary>
/// <returns>
/// The percentage of successful hits, as a decimal e.g 75.
/// </returns>
float CacheHitPercentage { get; }
/// <summary>
/// A miss is a get request that is not satisfied.
/// </summary>
/// <returns>
/// The number of misses.
/// </returns>
long CacheMisses { get; }
/// <summary>
/// Returns the percentage of cache accesses that did not find a requested entry in the cache.
/// </summary>
/// <returns>
/// The percentage of accesses that failed to find anything.
/// </returns>
float CacheMissPercentage { get; }
/// <summary>
/// The total number of requests to the cache. This will be equal to the sum of the hits and misses.
/// </summary>
/// <returns>
/// The number of gets.
/// </returns>
long CacheGets { get; }
/// <summary>
/// The total number of puts to the cache.
/// </summary>
/// <returns>
/// The number of puts.
/// </returns>
long CachePuts { get; }
/// <summary>
/// The total number of removals from the cache. This does not include evictions, where the cache itself
/// initiates the removal to make space.
/// </summary>
/// <returns>
/// The number of removals.
/// </returns>
long CacheRemovals { get; }
/// <summary>
/// The total number of evictions from the cache. An eviction is a removal initiated by the cache itself
/// to free up space. An eviction is not treated as a removal and does not appear in the removal counts.
/// </summary>
/// <returns>
/// The number of evictions.
/// </returns>
long CacheEvictions { get; }
/// <summary>
/// The mean time to execute gets.
/// </summary>
/// <returns>
/// The time in ms.
/// </returns>
float AverageGetTime { get; }
/// <summary>
/// The mean time to execute puts.
/// </summary>
/// <returns>
/// The time in s.
/// </returns>
float AveragePutTime { get; }
/// <summary>
/// The mean time to execute removes.
/// </summary>
/// <returns>
/// The time in ms.
/// </returns>
float AverageRemoveTime { get; }
/// <summary>
/// The mean time to execute tx commit.
/// </summary>
/// <returns>
/// The time in ms.
/// </returns>
float AverageTxCommitTime { get; }
/// <summary>
/// The mean time to execute tx rollbacks.
/// </summary>
/// <returns>
/// Number of transaction rollbacks.
/// </returns>
float AverageTxRollbackTime { get; }
/// <summary>
/// Gets total number of transaction commits.
/// </summary>
/// <returns>
/// Number of transaction commits.
/// </returns>
long CacheTxCommits { get; }
/// <summary>
/// Gets total number of transaction rollbacks.
/// </summary>
/// <returns>
/// Number of transaction rollbacks.
/// </returns>
long CacheTxRollbacks { get; }
/// <summary>
/// Gets cache name.
/// </summary>
/// <returns>
/// Cache name.
/// </returns>
string CacheName { get; }
/// <summary>
/// The total number of get requests to the off-heap memory.
/// </summary>
/// <returns>
/// The number of gets.
/// </returns>
long OffHeapGets { get; }
/// <summary>
/// The total number of put requests to the off-heap memory.
/// </summary>
/// <returns>
/// The number of puts.
/// </returns>
long OffHeapPuts { get; }
/// <summary>
/// The total number of removals from the off-heap memory. This does not include evictions.
/// </summary>
/// <returns>
/// The number of removals.
/// </returns>
long OffHeapRemovals { get; }
/// <summary>
/// The total number of evictions from the off-heap memory.
/// </summary>
/// <returns>
/// The number of evictions.
/// </returns>
long OffHeapEvictions { get; }
/// <summary>
/// The number of get requests that were satisfied by the off-heap memory.
/// </summary>
/// <returns>
/// The off-heap hits number.
/// </returns>
long OffHeapHits { get; }
/// <summary>
/// Gets the percentage of hits on off-heap memory.
/// </summary>
/// <returns>
/// The percentage of hits on off-heap memory.
/// </returns>
float OffHeapHitPercentage { get; }
/// <summary>
/// A miss is a get request that is not satisfied by off-heap memory.
/// </summary>
/// <returns>
/// The off-heap misses number.
/// </returns>
long OffHeapMisses { get; }
/// <summary>
/// Gets the percentage of misses on off-heap memory.
/// </summary>
/// <returns>
/// The percentage of misses on off-heap memory.
/// </returns>
float OffHeapMissPercentage { get; }
/// <summary>
/// Gets number of entries stored in off-heap memory.
/// </summary>
/// <returns>
/// Number of entries stored in off-heap memory.
/// </returns>
long OffHeapEntriesCount { get; }
/// <summary>
/// Gets the number of primary entries stored in off-heap memory.
/// </summary>
/// <returns>
/// Number of primary entries stored in off-heap memory.
/// </returns>
long OffHeapPrimaryEntriesCount { get; }
/// <summary>
/// Gets number of backup entries stored in off-heap memory.
/// </summary>
/// <returns>
/// Number of backup entries stored in off-heap memory.
/// </returns>
long OffHeapBackupEntriesCount { get; }
/// <summary>
/// Gets memory size allocated in off-heap.
/// </summary>
/// <returns>
/// Memory size allocated in off-heap.
/// </returns>
long OffHeapAllocatedSize { get; }
/// <summary>
/// Gets number of non-null values in the cache.
/// </summary>
/// <returns>
/// Number of non-null values in the cache.
/// </returns>
int Size { get; }
/// <summary>
/// Gets number of keys in the cache, possibly with null values.
/// </summary>
/// <returns>
/// Number of keys in the cache.
/// </returns>
int KeySize { get; }
/// <summary>
/// Returns true if this cache is empty.
/// </summary>
/// <returns>
/// True if this cache is empty.
/// </returns>
bool IsEmpty { get; }
/// <summary>
/// Gets current size of evict queue used to batch up evictions.
/// </summary>
/// <returns>
/// Current size of evict queue.
/// </returns>
int DhtEvictQueueCurrentSize { get; }
/// <summary>
/// Gets transaction per-thread map size.
/// </summary>
/// <returns>
/// Thread map size.
/// </returns>
int TxThreadMapSize { get; }
/// <summary>
/// Gets transaction per-Xid map size.
/// </summary>
/// <returns>
/// Transaction per-Xid map size.
/// </returns>
int TxXidMapSize { get; }
/// <summary>
/// Gets committed transaction queue size.
/// </summary>
/// <returns>
/// Committed transaction queue size.
/// </returns>
int TxCommitQueueSize { get; }
/// <summary>
/// Gets prepared transaction queue size.
/// </summary>
/// <returns>
/// Prepared transaction queue size.
/// </returns>
int TxPrepareQueueSize { get; }
/// <summary>
/// Gets start version counts map size.
/// </summary>
/// <returns>
/// Start version counts map size.
/// </returns>
int TxStartVersionCountsSize { get; }
/// <summary>
/// Gets number of cached committed transaction IDs.
/// </summary>
/// <returns>
/// Number of cached committed transaction IDs.
/// </returns>
int TxCommittedVersionsSize { get; }
/// <summary>
/// Gets number of cached rolled back transaction IDs.
/// </summary>
/// <returns>
/// Number of cached rolled back transaction IDs.
/// </returns>
int TxRolledbackVersionsSize { get; }
/// <summary>
/// Gets transaction DHT per-thread map size.
/// </summary>
/// <returns>
/// DHT thread map size.
/// </returns>
int TxDhtThreadMapSize { get; }
/// <summary>
/// Gets transaction DHT per-Xid map size.
/// </summary>
/// <returns>
/// Transaction DHT per-Xid map size.
/// </returns>
int TxDhtXidMapSize { get; }
/// <summary>
/// Gets committed DHT transaction queue size.
/// </summary>
/// <returns>
/// Committed DHT transaction queue size.
/// </returns>
int TxDhtCommitQueueSize { get; }
/// <summary>
/// Gets prepared DHT transaction queue size.
/// </summary>
/// <returns>
/// Prepared DHT transaction queue size.
/// </returns>
int TxDhtPrepareQueueSize { get; }
/// <summary>
/// Gets DHT start version counts map size.
/// </summary>
/// <returns>
/// DHT start version counts map size.
/// </returns>
int TxDhtStartVersionCountsSize { get; }
/// <summary>
/// Gets number of cached committed DHT transaction IDs.
/// </summary>
/// <returns>
/// Number of cached committed DHT transaction IDs.
/// </returns>
int TxDhtCommittedVersionsSize { get; }
/// <summary>
/// Gets number of cached rolled back DHT transaction IDs.
/// </summary>
/// <returns>
/// Number of cached rolled back DHT transaction IDs.
/// </returns>
int TxDhtRolledbackVersionsSize { get; }
/// <summary>
/// Returns true if write-behind is enabled.
/// </summary>
/// <returns>
/// True if write-behind is enabled.
/// </returns>
bool IsWriteBehindEnabled { get; }
/// <summary>
/// Gets the maximum size of the write-behind buffer. When the count of unique keys in write buffer exceeds
/// this value, the buffer is scheduled for write to the underlying store.
/// <para />
/// If this value is 0, then flush is performed only on time-elapsing basis.
/// </summary>
/// <returns>
/// Buffer size that triggers flush procedure.
/// </returns>
int WriteBehindFlushSize { get; }
/// <summary>
/// Gets the number of flush threads that will perform store update operations.
/// </summary>
/// <returns>
/// Count of worker threads.
/// </returns>
int WriteBehindFlushThreadCount { get; }
/// <summary>
/// Gets the cache flush frequency. All pending operations on the underlying store will be performed
/// within time interval not less then this value.
/// <para /> If this value is 0, then flush is performed only when buffer size exceeds flush size.
/// </summary>
/// <returns>
/// Flush frequency in milliseconds.
/// </returns>
long WriteBehindFlushFrequency { get; }
/// <summary>
/// Gets the maximum count of similar (put or remove) operations that can be grouped to a single batch.
/// </summary>
/// <returns>
/// Maximum size of batch.
/// </returns>
int WriteBehindStoreBatchSize { get; }
/// <summary>
/// Gets count of write buffer overflow events since initialization.
/// Each overflow event causes the ongoing flush operation to be performed synchronously.
/// </summary>
/// <returns>
/// Count of cache overflow events since start.
/// </returns>
int WriteBehindTotalCriticalOverflowCount { get; }
/// <summary>
/// Gets count of write buffer overflow events in progress at the moment.
/// Each overflow event causes the ongoing flush operation to be performed synchronously.
/// </summary>
/// <returns>
/// Count of cache overflow events since start.
/// </returns>
int WriteBehindCriticalOverflowCount { get; }
/// <summary>
/// Gets count of cache entries that are in a store-retry state.
/// An entry is assigned a store-retry state when underlying store failed due some reason
/// and cache has enough space to retain this entry till the next try.
/// </summary>
/// <returns>
/// Count of entries in store-retry state.
/// </returns>
int WriteBehindErrorRetryCount { get; }
/// <summary>
/// Gets count of entries that were processed by the write-behind store
/// and have not been flushed to the underlying store yet.
/// </summary>
/// <returns>
/// Total count of entries in cache store internal buffer.
/// </returns>
int WriteBehindBufferSize { get; }
/// <summary>
/// Determines the required type of keys for this cache, if any.
/// </summary>
/// <returns>
/// The fully qualified class name of the key type, or "java.lang.Object" if the type is undefined.
/// </returns>
string KeyType { get; }
/// <summary>
/// Determines the required type of values for this cache, if any.
/// </summary>
/// <returns>
/// The fully qualified class name of the value type, or "java.lang.Object" if the type is undefined.
/// </returns>
string ValueType { get; }
/// <summary>
/// Whether storeByValue true or storeByReference false. When true, both keys and values are stored by value.
/// <para />
/// When false, both keys and values are stored by reference. Caches stored by reference are capable of
/// mutation by any threads holding the reference.
/// The effects are:
/// - if the key is mutated, then the key may not be retrievable or removable
/// - if the value is mutated, then all threads in the JVM can potentially observe those mutations, subject
/// to the normal Java Memory Model rules.
/// Storage by reference only applies to the local heap.
/// If an entry is moved off heap it will need to be transformed into a representation.
/// Any mutations that occur after transformation may not be reflected in the cache.
/// <para />
/// When a cache is storeByValue, any mutation to the key or value does not affect the key of value
/// stored in the cache.
/// <para />
/// The default value is true.
/// </summary>
/// <returns>
/// True if the cache is store by value.
/// </returns>
bool IsStoreByValue { get; }
/// <summary>
/// Checks whether statistics collection is enabled in this cache.
/// <para />
/// The default value is false.
/// </summary>
/// <returns>
/// True if statistics collection is enabled.
/// </returns>
bool IsStatisticsEnabled { get; }
/// <summary>
/// Checks whether management is enabled on this cache.
/// <para />
/// The default value is false.
/// </summary>
/// <returns>
/// True if management is enabled.
/// </returns>
bool IsManagementEnabled { get; }
/// <summary>
/// Determines if a cache should operate in read-through mode.
/// <para />
/// The default value is false
/// </summary>
/// <returns>
/// True when a cache is in "read-through" mode.
/// </returns>
bool IsReadThrough { get; }
/// <summary>
/// Determines if a cache should operate in "write-through" mode.
/// <para />
/// Will appropriately cause the configured CacheWriter to be invoked.
/// <para />
/// The default value is false
/// </summary>
/// <returns>
/// True when a cache is in "write-through" mode.
/// </returns>
bool IsWriteThrough { get; }
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "No change to symbol"
[Fact]
public void C2CTypeSymbolUnchanged01()
{
var src1 = @"using System;
public delegate void DFoo(int p1, string p2);
namespace N1.N2
{
public interface IFoo { }
namespace N3
{
public class CFoo
{
public struct SFoo
{
public enum EFoo { Zero, One }
}
}
}
}
";
var src2 = @"using System;
public delegate void DFoo(int p1, string p2);
namespace N1.N2
{
public interface IFoo
{
// Add member
N3.CFoo GetClass();
}
namespace N3
{
public class CFoo
{
public struct SFoo
{
// Update member
public enum EFoo { Zero, One, Two }
}
// Add member
public void M(int n) { Console.WriteLine(n); }
}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")]
public void C2CErrorSymbolUnchanged01()
{
var src1 = @"public void Method() { }";
var src2 = @"
public void Method()
{
System.Console.WriteLine(12345);
}
";
var comp1 = CreateCompilationWithMscorlib(src1);
var comp2 = CreateCompilationWithMscorlib(src2);
var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
Assert.NotNull(symbol01);
Assert.NotNull(symbol02);
Assert.NotEqual(symbol01.Kind, SymbolKind.ErrorType);
Assert.NotEqual(symbol02.Kind, SymbolKind.ErrorType);
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact]
[WorkItem(820263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820263")]
public void PartialDefinitionAndImplementationResolveCorrectly()
{
var src = @"using System;
namespace NS
{
public partial class C1
{
partial void M() { }
partial void M();
}
}
";
var comp = CreateCompilationWithMscorlib(src, assemblyName: "Test");
var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type = ns.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var definition = type.GetMembers("M").First() as IMethodSymbol;
var implementation = definition.PartialImplementationPart;
// Assert that both the definition and implementation resolve back to themselves
Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None));
Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None));
}
[Fact]
[WorkItem(916341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916341")]
public void ExplicitIndexerImplementationResolvesCorrectly()
{
var src = @"
interface I
{
object this[int index] { get; }
}
interface I<T>
{
T this[int index] { get; }
}
class C<T> : I<T>, I
{
object I.this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
T I<T>.this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
}
";
var compilation = CreateCompilationWithMscorlib(src, assemblyName: "Test");
var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as NamedTypeSymbol;
var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol;
var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol;
AssertSymbolKeysEqual(indexer1, indexer2, SymbolKeyComparison.None, expectEqual: false);
Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, SymbolKeyComparison.None));
Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, SymbolKeyComparison.None));
}
[Fact]
public void RecursiveReferenceToConstructedGeneric()
{
var src1 =
@"using System.Collections.Generic;
class C
{
public void M<Z>(List<Z> list)
{
var v = list.Add(default(Z));
}
}";
var comp1 = CreateCompilationWithMscorlib(src1);
var comp2 = CreateCompilationWithMscorlib(src1);
var symbols1 = GetSourceSymbols(comp1, includeLocal: true).ToList();
var symbols2 = GetSourceSymbols(comp1, includeLocal: true).ToList();
// First, make sure that all the symbols in this file resolve properly
// to themselves.
ResolveAndVerifySymbolList(symbols1, symbols2, comp1);
// Now do this for the members of types we see. We want this
// so we hit things like the members of the constructed type
// List<Z>
var members1 = symbols1.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList();
var members2 = symbols2.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList();
ResolveAndVerifySymbolList(members1, members2, comp1);
}
#endregion
#region "Change to symbol"
[Fact]
public void C2CTypeSymbolChanged01()
{
var src1 = @"using System;
public delegate void DFoo(int p1);
namespace N1.N2
{
public interface IBase { }
public interface IFoo { }
namespace N3
{
public class CFoo
{
public struct SFoo
{
public enum EFoo { Zero, One }
}
}
}
}
";
var src2 = @"using System;
public delegate void DFoo(int p1, string p2); // add 1 more parameter
namespace N1.N2
{
public interface IBase { }
public interface IFoo : IBase // add base interface
{
}
namespace N3
{
public class CFoo : IFoo // impl interface
{
private struct SFoo // change modifier
{
internal enum EFoo : long { Zero, One } // change base class, and modifier
}
}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact]
public void C2CTypeSymbolChanged02()
{
var src1 = @"using System;
namespace NS
{
public class C1
{
public void M() {}
}
}
";
var src2 = @"
namespace NS
{
internal class C1 // add new C1
{
public string P { get; set; }
}
public class C2 // rename C1 to C2
{
public void M() {}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var typeSym02 = namespace2.GetTypeMembers("C2").Single() as NamedTypeSymbol;
// new C1 resolve to old C1
ResolveAndVerifySymbol(typeSym01, typeSym00, comp1);
// old C1 (new C2) NOT resolve to old C1
var symkey = SymbolKey.Create(typeSym02, CancellationToken.None);
var syminfo = symkey.Resolve(comp1);
Assert.Null(syminfo.Symbol);
}
[Fact]
public void C2CMemberSymbolChanged01()
{
var src1 = @"using System;
using System.Collections.Generic;
public class Test
{
private byte field = 123;
internal string P { get; set; }
public void M(ref int n) { }
event Action<string> myEvent;
}
";
var src2 = @"using System;
public class Test
{
internal protected byte field = 255; // change modifier and init-value
internal string P { get { return null; } } // remove 'set'
public int M(ref int n) { return 0; } // change ret type
event Action<string> myEvent // add add/remove
{
add { }
remove { }
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter)
.Where(s => !s.IsAccessor()).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter)
.Where(s => !s.IsAccessor()).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")]
[Fact]
public void C2CIndexerSymbolChanged01()
{
var src1 = @"using System;
using System.Collections.Generic;
public class Test
{
public string this[string p1] { set { } }
protected long this[long p1] { set { } }
}
";
var src2 = @"using System;
public class Test
{
internal string this[string p1] { set { } } // change modifier
protected long this[long p1] { get { return 0; } set { } } // add 'get'
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer);
var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer);
ResolveAndVerifySymbol(newSymbols.First(), originalSymbols.First(), comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(newSymbols.Last(), originalSymbols.Last(), comp1, SymbolKeyComparison.None);
}
[Fact]
public void C2CAssemblyChanged01()
{
var src = @"
namespace NS
{
public class C1
{
public void M() {}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly1");
var comp2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly2");
var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
// new C1 resolves to old C1 if we ignore assembly and module ids
ResolveAndVerifySymbol(typeSym02, typeSym01, comp1, SymbolKeyComparison.IgnoreAssemblyIds);
// new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids
Assert.Null(ResolveSymbol(typeSym02, comp1, SymbolKeyComparison.None));
}
[WpfFact(Skip = "530169"), WorkItem(530169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530169")]
public void C2CAssemblyChanged02()
{
var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}";
// same identity
var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly");
var comp2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly");
Symbol sym1 = comp1.Assembly;
Symbol sym2 = comp2.Assembly;
// Not ignoreAssemblyAndModules
ResolveAndVerifySymbol(sym1, sym2, comp2);
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds, true);
Assert.NotNull(ResolveSymbol(sym1, comp2, SymbolKeyComparison.IgnoreAssemblyIds));
// Module
sym1 = comp1.Assembly.Modules[0];
sym2 = comp2.Assembly.Modules[0];
ResolveAndVerifySymbol(sym1, sym2, comp2);
AssertSymbolKeysEqual(sym2, sym1, SymbolKeyComparison.IgnoreAssemblyIds, true);
Assert.NotNull(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds));
}
[Fact, WorkItem(530170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530170")]
public void C2CAssemblyChanged03()
{
var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}";
// -------------------------------------------------------
// different name
var compilation1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly1");
var compilation2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly2");
ISymbol assembly1 = compilation1.Assembly;
ISymbol assembly2 = compilation2.Assembly;
// different
AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.None, expectEqual: false);
Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.None));
// ignore means ALL assembly/module symbols have same ID
AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true);
// But can NOT be resolved
Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds));
// Module
var module1 = compilation1.Assembly.Modules[0];
var module2 = compilation2.Assembly.Modules[0];
// different
AssertSymbolKeysEqual(module1, module2, SymbolKeyComparison.None, expectEqual: false);
Assert.Null(ResolveSymbol(module1, compilation2, SymbolKeyComparison.None));
AssertSymbolKeysEqual(module2, module1, SymbolKeyComparison.IgnoreAssemblyIds);
Assert.Null(ResolveSymbol(module2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds));
}
[Fact, WorkItem(546254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546254")]
public void C2CAssemblyChanged04()
{
var src = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")]
public class C {}
";
var src2 = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")]
public class C {}
";
// different versions
var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Assembly");
Symbol sym1 = comp1.Assembly;
Symbol sym2 = comp2.Assembly;
// comment is changed to compare Name ONLY
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.None, expectEqual: true);
var resolved = ResolveSymbol(sym2, comp1, SymbolKeyComparison.None);
Assert.Equal(sym1, resolved);
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds);
Assert.Null(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
/// <summary>
/// System.Collections.Generic.IDictionary.ContainsKey(TKey)
/// </summary>
public class IDictionaryContainsKey
{
private int c_MINI_STRING_LENGTH = 1;
private int c_MAX_STRING_LENGTH = 20;
public static int Main(string[] args)
{
IDictionaryContainsKey testObj = new IDictionaryContainsKey();
TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.IDictionary.ContainsKey(TKey)");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Netativ]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Using Dictionary<TKey,TValue> which implemented the ContainsKey method in IDictionay<TKey,TValue> and TKey is int...";
const string c_TEST_ID = "P001";
Dictionary<int, int> dictionary = new Dictionary<int, int>();
int key = TestLibrary.Generator.GetInt32(-55);
int value = TestLibrary.Generator.GetInt32(-55);
((IDictionary<int, int>)dictionary).Add(key, value);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((IDictionary<int, int>)dictionary).ContainsKey(key))
{
string errorDesc = "Value is not false as expected: Actual is true";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Using Dictionary<TKey,TValue> which implemented the ContainsKey method in IDictionay<TKey,TValue> and TKey is String...";
const string c_TEST_ID = "P002";
Dictionary<String, String> dictionary = new Dictionary<String, String>();
String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
String value = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
dictionary.Add(key, value);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((IDictionary<String, String>)dictionary).ContainsKey(key))
{
string errorDesc = "Value is not false as expected: Actual is true";
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Using Dictionary<TKey,TValue> which implemented the ContainsKey method in IDictionay<TKey,TValue> and TKey is customer class...";
const string c_TEST_ID = "P003";
Dictionary<MyClass, MyClass> dictionary = new Dictionary<MyClass, MyClass>();
MyClass key = new MyClass();
MyClass value = new MyClass();
dictionary.Add(key, value);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((IDictionary<MyClass, MyClass>)dictionary).ContainsKey(key))
{
string errorDesc = "Value is not false as expected: Actual is true";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: Using Dictionary<TKey,TValue> which implemented the ContainsKey method in IDictionay<TKey,TValue> and TKey isn't contained in IDictionary...";
const string c_TEST_ID = "P004";
Dictionary<String, String> dictionary = new Dictionary<String, String>();
String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (((IDictionary<String, String>)dictionary).ContainsKey(key))
{
string errorDesc = "Value is not true as expected: Actual is false";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest5: Using customer class which implemented the ContainsKey method in IDictionay<TKey,TValue>...";
const string c_TEST_ID = "P005";
MyDictionary<int, int> dictionary = new MyDictionary<int, int>();
int key = TestLibrary.Generator.GetInt32(-55);
int value = TestLibrary.Generator.GetInt32(-55);
dictionary.Add(key, value);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((IDictionary<int, int>)dictionary).ContainsKey(key))
{
string errorDesc = "Value is not false as expected: Actual is true";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: Using Dictionary<TKey,TValue> which implemented the ContainsKey method in IDictionay<TKey,TValue> and Key is a null reference...";
const string c_TEST_ID = "N001";
Dictionary<String, int> dictionary = new Dictionary<String, int>();
String key = null;
int value = TestLibrary.Generator.GetInt32(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IDictionary<String, int>)dictionary).ContainsKey(key);
TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "The ArgumentNullException was not thrown as expected");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Help Class
public class MyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private int count;
private int capacity = 10;
public bool readOnly = false;
private KeyValuePair<TKey, TValue>[] keyvaluePair;
public MyDictionary()
{
count = 0;
keyvaluePair = new KeyValuePair<TKey, TValue>[capacity];
}
#region IDictionary<TKey,TValue> Members
public void Add(TKey key, TValue value)
{
if (readOnly)
throw new NotSupportedException();
if (ContainsKey(key))
throw new ArgumentException();
try
{
KeyValuePair<TKey, TValue> pair = new KeyValuePair<TKey, TValue>(key, value);
keyvaluePair[count] = pair;
count++;
}
catch (Exception en)
{
throw en;
}
}
public bool ContainsKey(TKey key)
{
bool exist = false;
if (key == null)
throw new ArgumentNullException();
foreach (KeyValuePair<TKey, TValue> pair in keyvaluePair)
{
if (pair.Key != null && pair.Key.Equals(key))
{
exist = true;
}
}
return exist;
}
public ICollection<TKey> Keys
{
get { throw new Exception("The method or operation is not implemented."); }
}
public bool Remove(TKey key)
{
throw new Exception("The method or operation is not implemented.");
}
public bool TryGetValue(TKey key, out TValue value)
{
throw new Exception("The method or operation is not implemented.");
}
public ICollection<TValue> Values
{
get { throw new Exception("The method or operation is not implemented."); }
}
public TValue this[TKey key]
{
get
{
if (!ContainsKey(key))
throw new KeyNotFoundException();
int index = -1;
for (int j = 0; j < count; j++)
{
KeyValuePair<TKey, TValue> pair = keyvaluePair[j];
if (pair.Key.Equals(key))
{
index = j;
break;
}
}
return keyvaluePair[index].Value;
}
set
{
if (readOnly)
throw new NotSupportedException();
if (ContainsKey(key))
{
int index = -1;
for (int j = 0; j < count; j++)
{
KeyValuePair<TKey, TValue> pair = keyvaluePair[j];
if (pair.Key.Equals(key))
{
index = j;
break;
}
}
KeyValuePair<TKey, TValue> newpair = new KeyValuePair<TKey, TValue>(key, value);
keyvaluePair[index] = newpair;
}
else
{
KeyValuePair<TKey, TValue> pair = new KeyValuePair<TKey, TValue>(key, value);
keyvaluePair[count] = pair;
count++;
}
}
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new Exception("The method or operation is not implemented.");
}
public void Clear()
{
throw new Exception("The method or operation is not implemented.");
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
throw new Exception("The method or operation is not implemented.");
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new Exception("The method or operation is not implemented.");
}
public int Count
{
get { return count; }
}
public bool IsReadOnly
{
get { throw new Exception("The method or operation is not implemented."); }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
public class MyClass
{ }
#endregion
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Common;
using ReactNative.Tracing;
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
namespace ReactNative.Modules.Storage
{
class AsyncStorageModule : NativeModuleBase
{
private readonly SemaphoreSlim _mutex = new SemaphoreSlim(1, 1);
private StorageFolder _cachedFolder;
public override string Name
{
get
{
return "AsyncLocalStorage";
}
}
[ReactMethod]
public async void multiGet(string[] keys, ICallback callback)
{
if (keys == null)
{
callback.Invoke(AsyncStorageHelpers.GetInvalidKeyError(null), null);
return;
}
var error = default(JObject);
var data = new JArray();
await _mutex.WaitAsync().ConfigureAwait(false);
try
{
foreach (var key in keys)
{
if (key == null)
{
error = AsyncStorageHelpers.GetInvalidKeyError(null);
break;
}
var value = await GetAsync(key).ConfigureAwait(false);
data.Add(new JArray(key, value));
}
}
catch (Exception ex)
{
error = AsyncStorageHelpers.GetError(ex);
}
finally
{
_mutex.Release();
}
if (error != null)
{
RnLog.Warn(ReactConstants.RNW, $"Error in AsyncStorageModule.multiGet: {error}");
callback.Invoke(error);
}
else
{
callback.Invoke(null, data);
}
}
[ReactMethod]
public async void multiSet(string[][] keyValueArray, ICallback callback)
{
if (keyValueArray == null || keyValueArray.Length == 0)
{
callback.Invoke(AsyncStorageHelpers.GetInvalidKeyError(null));
return;
}
var error = default(JObject);
await _mutex.WaitAsync().ConfigureAwait(false);
try
{
foreach (var pair in keyValueArray)
{
if (pair.Length != 2)
{
error = AsyncStorageHelpers.GetInvalidValueError(null);
break;
}
if (pair[0] == null)
{
error = AsyncStorageHelpers.GetInvalidKeyError(null);
break;
}
if (pair[1] == null)
{
error = AsyncStorageHelpers.GetInvalidValueError(pair[0]);
break;
}
error = await SetAsync(pair[0], pair[1]).ConfigureAwait(false);
if (error != null)
{
break;
}
}
}
catch (Exception ex)
{
error = AsyncStorageHelpers.GetError(ex);
}
finally
{
_mutex.Release();
}
if (error != null)
{
RnLog.Warn(ReactConstants.RNW, $"Error in AsyncStorageModule.multiSet: {error}");
callback.Invoke(error);
}
else
{
callback.Invoke();
}
}
[ReactMethod]
public async void multiRemove(string[] keys, ICallback callback)
{
if (keys == null || keys.Length == 0)
{
callback.Invoke(AsyncStorageHelpers.GetInvalidKeyError(null));
return;
}
var error = default(JObject);
await _mutex.WaitAsync().ConfigureAwait(false);
try
{
foreach (var key in keys)
{
if (key == null)
{
error = AsyncStorageHelpers.GetInvalidKeyError(null);
break;
}
error = await RemoveAsync(key).ConfigureAwait(false);
if (error != null)
{
break;
}
}
}
catch (Exception ex)
{
error = AsyncStorageHelpers.GetError(ex);
}
finally
{
_mutex.Release();
}
if (error != null)
{
RnLog.Warn(ReactConstants.RNW, $"Error in AsyncStorageModule.multiRemove: {error}");
callback.Invoke(error);
}
else
{
callback.Invoke();
}
}
[ReactMethod]
public async void multiMerge(string[][] keyValueArray, ICallback callback)
{
if (keyValueArray == null || keyValueArray.Length == 0)
{
callback.Invoke(AsyncStorageHelpers.GetInvalidKeyError(null));
return;
}
var error = default(JObject);
await _mutex.WaitAsync().ConfigureAwait(false);
try
{
foreach (var pair in keyValueArray)
{
if (pair.Length != 2)
{
error = AsyncStorageHelpers.GetInvalidValueError(null);
break;
}
if (pair[0] == null)
{
error = AsyncStorageHelpers.GetInvalidKeyError(null);
break;
}
if (pair[1] == null)
{
error = AsyncStorageHelpers.GetInvalidValueError(pair[0]);
break;
}
error = await MergeAsync(pair[0], pair[1]).ConfigureAwait(false);
if (error != null)
{
break;
}
}
}
catch (Exception ex)
{
error = AsyncStorageHelpers.GetError(ex);
}
finally
{
_mutex.Release();
}
if (error != null)
{
RnLog.Warn(ReactConstants.RNW, $"Error in AsyncStorageModule.multiMerge: {error}");
callback.Invoke(error);
}
else
{
callback.Invoke();
}
}
[ReactMethod]
public async void clear(ICallback callback)
{
var error = default(JObject);
await _mutex.WaitAsync().ConfigureAwait(false);
try
{
var storageFolder = await GetAsyncStorageFolder(false).ConfigureAwait(false);
if (storageFolder != null)
{
await storageFolder.DeleteAsync().AsTask().ConfigureAwait(false);
_cachedFolder = null;
}
}
catch (Exception ex)
{
error = AsyncStorageHelpers.GetError(ex);
}
finally
{
_mutex.Release();
}
if (error != null)
{
RnLog.Warn(ReactConstants.RNW, $"Error in AsyncStorageModule.clear: {error}");
callback.Invoke(error);
}
else
{
callback.Invoke();
}
}
[ReactMethod]
public async void getAllKeys(ICallback callback)
{
var error = default(JObject);
var keys = new JArray();
await _mutex.WaitAsync().ConfigureAwait(false);
try
{
var storageFolder = await GetAsyncStorageFolder(false).ConfigureAwait(false);
if (storageFolder != null)
{
var items = await storageFolder.GetItemsAsync().AsTask().ConfigureAwait(false);
foreach (var item in items)
{
var itemName = item.Name;
if (itemName.EndsWith(AsyncStorageHelpers.FileExtension))
{
keys.Add(AsyncStorageHelpers.GetKeyName(itemName));
}
}
}
}
catch (Exception ex)
{
error = AsyncStorageHelpers.GetError(ex);
}
finally
{
_mutex.Release();
}
if (error != null)
{
RnLog.Warn(ReactConstants.RNW, $"Error in AsyncStorageModule.getAllKeys: {error}");
callback.Invoke(error);
}
else
{
callback.Invoke(null, keys);
}
}
public override Task OnReactInstanceDisposeAsync()
{
_mutex.Dispose();
return Task.CompletedTask;
}
private async Task<string> GetAsync(string key)
{
var storageFolder = await GetAsyncStorageFolder(false).ConfigureAwait(false);
if (storageFolder != null)
{
var fileName = AsyncStorageHelpers.GetFileName(key);
var storageItem = await storageFolder.TryGetItemAsync(fileName).AsTask().ConfigureAwait(false);
if (storageItem != null)
{
var file = await storageFolder.GetFileAsync(fileName).AsTask().ConfigureAwait(false);
return await FileIO.ReadTextAsync(file).AsTask().ConfigureAwait(false);
}
}
return null;
}
private async Task<JObject> MergeAsync(string key, string value)
{
var oldValue = await GetAsync(key).ConfigureAwait(false);
var newValue = default(string);
if (oldValue == null)
{
newValue = value;
}
else
{
var oldJson = JObject.Parse(oldValue);
var newJson = JObject.Parse(value);
AsyncStorageHelpers.DeepMergeInto(oldJson, newJson);
newValue = oldJson.ToString(Formatting.None);
}
return await SetAsync(key, newValue).ConfigureAwait(false);
}
private async Task<JObject> RemoveAsync(string key)
{
var storageFolder = await GetAsyncStorageFolder(false).ConfigureAwait(false);
if (storageFolder != null)
{
var fileName = AsyncStorageHelpers.GetFileName(key);
var storageItem = await storageFolder.TryGetItemAsync(fileName).AsTask().ConfigureAwait(false);
if (storageItem != null)
{
await storageItem.DeleteAsync().AsTask().ConfigureAwait(false);
}
}
return null;
}
private async Task<JObject> SetAsync(string key, string value)
{
var storageFolder = await GetAsyncStorageFolder(true).ConfigureAwait(false);
var file = await storageFolder.CreateFileAsync(AsyncStorageHelpers.GetFileName(key), CreationCollisionOption.ReplaceExisting).AsTask().ConfigureAwait(false);
await FileIO.WriteTextAsync(file, value).AsTask().ConfigureAwait(false);
return default(JObject);
}
private async Task<StorageFolder> GetAsyncStorageFolder(bool createIfNotExists)
{
if (_cachedFolder == null)
{
var localFolder = ApplicationData.Current.LocalFolder;
var storageFolderItem = await localFolder.TryGetItemAsync(AsyncStorageHelpers.DirectoryName);
_cachedFolder = storageFolderItem != null || createIfNotExists
? await localFolder.CreateFolderAsync(AsyncStorageHelpers.DirectoryName, CreationCollisionOption.OpenIfExists)
: null;
}
return _cachedFolder;
}
}
}
| |
namespace TestManagmentSystem.Data.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using TestManagmentSystem.Common;
using TestManagmentSystem.Data.Models;
internal sealed class Configuration : DbMigrationsConfiguration<TestManagmentSystemDbContext>
{
private UserManager<User> userManager;
private IRandomGenerator random;
public Configuration()
{
AutomaticMigrationsEnabled = true;
// TODO: Remove in production
AutomaticMigrationDataLossAllowed = true;
this.random = new RandomGenerator();
}
protected override void Seed(TestManagmentSystemDbContext context)
{
this.userManager = new UserManager<User>(new UserStore<User>(context));
this.SeedRoles(context);
this.SeedUsers(context);
this.SeadTestedSystems(context);
this.SeedTestScenarios(context);
this.SeedIssues(context);
}
private void SeedIssues(TestManagmentSystemDbContext context)
{
if (context.Issues.Any())
{
return;
}
var users = context.Users.ToList();
var environments = context.SystemEnvironments.ToList();
var environmentsCount = environments.Count == 0 ? environments.Count : environments.Count - 1;
for (var i = 0; i < random.RandomNumber(5, 50); i++)
{
var environment = environments[random.RandomNumber(0, environmentsCount)];
var issue = new Issue()
{
Name = random.RandomString(5, 15),
Description = random.RandomString(10, 30),
DateSubmitted = new DateTime(random.RandomNumber(2010, 2015), random.RandomNumber(1, 12), random.RandomNumber(1, 28)),
Status = (IssueStatusType)random.RandomNumber(1, 5),
Priority = (IssuePriorityType)random.RandomNumber(1, 4),
User = users[random.RandomNumber(0, users.Count - 1)],
SystemEnvironment = environment,
};
if (random.RandomNumber(0, 10) > 3)
{
var testCases = context.TestCases.Where(c => c.TestScenario.SystemEnvironmentId == environment.Id).ToList();
var testCasesCount = testCases.Count == 0 ? testCases.Count : testCases.Count - 1;
if (testCasesCount > 0)
{
var testCase = testCases[random.RandomNumber(0, testCasesCount)];
issue.TestCase = testCase;
issue.Project = testCase.TestScenario.Project;
}
}
context.Issues.Add(issue);
}
context.SaveChanges();
}
private void SeedTestScenarios(TestManagmentSystemDbContext context)
{
if (context.TestScenarios.Any())
{
return;
}
foreach (var envoriment in context.SystemEnvironments.ToList())
{
var scenarioCount = random.RandomNumber(0, 3);
for (var i = 0; i < scenarioCount; i++)
{
Project project = null;
if (random.RandomNumber(0, 1) == 0)
{
var projects = context.Projects.Where(p => p.TestedSystemId == envoriment.TestedSystemId).ToList();
if (projects.Count > 0)
{
project = projects[random.RandomNumber(0, projects.Count - 1)];
}
}
var scenario = new TestScenario()
{
Name = random.RandomString(5, 15),
Description = random.RandomString(10, 30),
Type = (TestScenarioType)random.RandomNumber(1, 3),
SystemEnvironment = envoriment,
Project = project
};
SeedTestCases(context, scenario);
context.TestScenarios.Add(scenario);
}
}
context.SaveChanges();
}
private void SeedTestCases(TestManagmentSystemDbContext context, TestScenario scenario)
{
var caseCount = random.RandomNumber(0, 2);
for (var i = 0; i < caseCount; i++)
{
var testCase = new TestCase()
{
Name = random.RandomString(5, 15),
Description = random.RandomString(10, 30),
TestScenario = scenario,
};
SeedTestCaseSteps(context, testCase);
SeedTestResults(context, testCase);
context.TestCases.Add(testCase);
}
}
private void SeedTestResults(TestManagmentSystemDbContext context, TestCase testCase)
{
var testResult = random.RandomNumber(0, 2);
var users = context.Users.ToList();
for (var i = 0; i < testResult; i++)
{
var user = users[random.RandomNumber(0, users.Count - 1)];
var result = new TestResult()
{
Description = random.RandomString(5, 15),
Date = new DateTime(random.RandomNumber(2010, 2015), random.RandomNumber(1, 12), random.RandomNumber(1, 28)),
TestStatus = (TestResultStatusType)random.RandomNumber(1, 3),
TestCase = testCase,
User = user
};
context.TestResults.Add(result);
}
}
private void SeedTestCaseSteps(TestManagmentSystemDbContext context, TestCase testCase)
{
var stepCount = random.RandomNumber(1, 5);
for (var i = 0; i < stepCount; i++)
{
var step = new TestCaseStep()
{
Name = random.RandomString(5, 15),
Preconditions = random.RandomString(10, 50),
Actions = random.RandomString(10, 100),
PostConditions = random.RandomString(10, 50),
TestCase = testCase,
};
context.TestCaseSteps.Add(step);
}
}
private void SeedRoles(TestManagmentSystemDbContext context)
{
context.Roles.AddOrUpdate(x => x.Name, new IdentityRole(GlobalConstants.AdminRole));
context.SaveChanges();
}
private void SeedUsers(TestManagmentSystemDbContext context)
{
if (context.Users.Any())
{
return;
}
for (int i = 1; i <= 5; i++)
{
var username = "user" + i + "@tms.com";
var user = new User
{
Email = username,
UserName = username
};
this.userManager.Create(user, "123456");
}
var adminUser = new User
{
Email = "admin@tms.com",
UserName = "admin@tms.com"
};
this.userManager.Create(adminUser, "admin123");
this.userManager.AddToRole(adminUser.Id, GlobalConstants.AdminRole);
context.SaveChanges();
}
private void SeadTestedSystems(TestManagmentSystemDbContext context)
{
GeneratedTestedSystem(context, "Test Management System", "The product allows management of system and integration and UAT tests results");
GeneratedTestedSystem(context, "Pew Pew", "Very addictive online game. The title says it all");
GeneratedTestedSystem(context, "Our Intra-net", "The Company's intra-net site");
GeneratedTestedSystem(context, "Some other system", "Just Testing");
context.SaveChanges();
}
private void GeneratedTestedSystem(TestManagmentSystemDbContext context, string name, string description)
{
if (context.TestedSystems.Any())
{
return;
}
var testedSystem = new TestedSystem
{
Name = name,
Description = description,
};
SeadSystemEnvironments(testedSystem);
SeadProjects(testedSystem);
context.TestedSystems.AddOrUpdate(a => a.Name, testedSystem);
}
private void SeadProjects(TestedSystem testedSystem)
{
var projectsCount = random.RandomNumber(0, 5);
for (var i = 0; i < projectsCount; i++)
{
var startDate = new DateTime(random.RandomNumber(2010, 2015), random.RandomNumber(1, 12), random.RandomNumber(1, 28));
var endDate = startDate.AddDays(random.RandomNumber(60, 600));
var project = new Project()
{
Name = random.RandomString(5, 15),
Description = random.RandomString(10, 30),
StartDate = startDate,
EndDate = endDate,
Status = (ProjectStatusType)random.RandomNumber(1, 7)
};
testedSystem.Projects.Add(project);
}
}
private void SeadSystemEnvironments(TestedSystem testedSystem)
{
var environmentsCount = random.RandomNumber(1, 3);
for (var i = 0; i < environmentsCount; i++)
{
var systemEnvironment = new SystemEnvironment()
{
Name = random.RandomString(5, 15),
Description = random.RandomString(10, 30),
Type = (EnvironmentType)random.RandomNumber(1, 3),
Url = random.RandomString(10, 20)
};
testedSystem.Environments.Add(systemEnvironment);
}
}
}
}
| |
// CodeContracts
//
// 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.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Xml.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace CCVersions
{
class TFVersionSpec : ISourceManagerVersionSpec
{
readonly VersionSpec vs;
public TFVersionSpec(string value)
{
if (String.IsNullOrWhiteSpace(value))
{
this.vs = null;
}
else
{
this.vs = VersionSpec.ParseSingleSpec(value, null);
}
}
public TFVersionSpec(int changeset)
{
this.vs = new ChangesetVersionSpec(changeset);
}
public override string ToString()
{
if (this.vs == null)
return "NULL";
var res = this.vs.DisplayString;
Contract.Assume(res != null);
Contract.Assume(res.Length >= 1);
return res;
}
public long Id
{
get
{
if (this.vs == null)
return -1;
if (this.vs is ChangesetVersionSpec)
return (this.vs as ChangesetVersionSpec).ChangesetId;
long res;
if (Int64.TryParse(this.ToString().Substring(1), out res)) // assume ToString gives C1234
return res;
return -2;
}
}
public VersionSpec VersionSpec { get { return vs; } }
}
class TFSourceManager : ISourceManager
{
readonly string id;
readonly string uri;
string workingDirectory;
readonly string subPath;
readonly TfsTeamProjectCollection tpc;
readonly VersionControlServer vcServer;
Workspace workspace;
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(this.id != null);
Contract.Invariant(this.subPath != null);
Contract.Invariant(this.uri != null);
Contract.Invariant(this.vcServer != null);
Contract.Invariant(this.workspace != null || this.workingDirectory == null); // WorkingDirectory != null implies workspace != null
}
public static TFSourceManager Factory(XElement xConfig)
{
Contract.Requires(xConfig != null);
return new TFSourceManager(xConfig);
}
private TFSourceManager(XElement xConfig)
{
Contract.Requires(xConfig != null);
// Read the config.xml file
var xProtocol = xConfig.Element("protocol");
var protocol = xProtocol == null ? "http" : xProtocol.Value;
var xServer = xConfig.Element("server");
var server = xServer == null ? "localhost" : xServer.Value;
var xPort = xConfig.Element("port");
var port = xPort == null ? "8080" : xPort.Value;
var xPath = xConfig.Element("path");
var path = xPath == null ? "tfs" : xPath.Value;
var xSubPath = xConfig.Element("subpath");
this.subPath = xSubPath == null ? "" : xSubPath.Value;
// build the URL
this.uri = String.Format("{0}://{1}:{2}/{3}", protocol, server, port, path);
// Build the TFS objects
// The TFS needs a window were to show some dialogs, in the case of
this.tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(this.uri), new UICredentialsProvider(Program.TheMainForm));
this.vcServer = tpc.GetService<VersionControlServer>();
Contract.Assume(this.vcServer != null);
// build the ID
this.id = IDBuilder.FromUri("TF_", this.uri + '/' + this.subPath);
}
public string Id { get { return this.id; } }
public string WorkingDirectory
{
get { return this.workingDirectory; }
set {
Contract.Ensures(this.WorkingDirectory != null);
this.workingDirectory = value;
this.workspace = this.vcServer.TryGetWorkspace(this.WorkingDirectory);
if (this.workspace == null)
{
var name = String.Format("{0}-{1}", System.Environment.MachineName, System.Guid.NewGuid().ToString().Substring(0, 8));
this.workspace = this.vcServer.CreateWorkspace(name);
Contract.Assume(this.workspace != null);
this.workspace.Map("$/" + this.subPath, this.WorkingDirectory);
}
}
}
public ISourceManagerVersionSpec ParseVersionSpec(string value)
{
return new TFVersionSpec(value);
}
[Pure]
public IEnumerable<TFVersionSpec> VersionRange(TFVersionSpec First, TFVersionSpec Last)
{
Contract.Requires(First != null);
Contract.Requires(Last != null);
Contract.Ensures(Contract.Result<IEnumerable<TFVersionSpec>>() != null);
var history = this.vcServer.QueryHistory("$/" + this.subPath, VersionSpec.Latest, 0, RecursionType.Full, null, First.VersionSpec, Last.VersionSpec, Int32.MaxValue, false, false);
Contract.Assume(history != null);
return history.Cast<Changeset>().Select(changeSet => new TFVersionSpec(changeSet.ChangesetId)).Reverse();
}
public IEnumerable<ISourceManagerVersionSpec> VersionRange(ISourceManagerVersionSpec First, ISourceManagerVersionSpec Last, string filter = null)
{
Contract.Ensures(Contract.Result<IEnumerable<ISourceManagerVersionSpec>>() != null);
return VersionRange((TFVersionSpec)First, (TFVersionSpec)Last);
}
public IEnumerable<ISourceManagerVersionSpec> VersionRange(ISourceManagerVersionSpec First, int countAfter)
{
Contract.Ensures(Contract.Result<IEnumerable<ISourceManagerVersionSpec>>() != null);
return VersionRange((TFVersionSpec)First, new TFVersionSpec(null));
}
public IEnumerable<ISourceManagerVersionSpec> VersionRange(int countPrio, ISourceManagerVersionSpec Last)
{
Contract.Ensures(Contract.Result<IEnumerable<ISourceManagerVersionSpec>>() != null);
return VersionRange(new TFVersionSpec(null), (TFVersionSpec)Last);
}
public bool GetSources(TFVersionSpec Version)
{
Contract.Requires(Version != null);
Contract.Requires(this.WorkingDirectory != null);
var getStatus = this.workspace.Get(Version.VersionSpec, GetOptions.GetAll | GetOptions.Overwrite);
Contract.Assume(getStatus != null);
return getStatus.NumFailures == 0;
}
public bool GetSources(ISourceManagerVersionSpec Version)
{
return GetSources((TFVersionSpec)Version);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
using System.Numerics;
#endif
using System.Text;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JTokenWriterTest : TestFixtureBase
{
[Test]
public void ValueFormatting()
{
byte[] data = Encoding.UTF8.GetBytes("Hello world.");
JToken root;
using (JTokenWriter jsonWriter = new JTokenWriter())
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue('@');
jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
jsonWriter.WriteValue(true);
jsonWriter.WriteValue(10);
jsonWriter.WriteValue(10.99);
jsonWriter.WriteValue(0.99);
jsonWriter.WriteValue(0.000000000000000001d);
jsonWriter.WriteValue(0.000000000000000001m);
jsonWriter.WriteValue((string)null);
jsonWriter.WriteValue("This is a string.");
jsonWriter.WriteNull();
jsonWriter.WriteUndefined();
jsonWriter.WriteValue(data);
jsonWriter.WriteEndArray();
root = jsonWriter.Token;
}
CustomAssert.IsInstanceOfType(typeof(JArray), root);
Assert.AreEqual(13, root.Children().Count());
Assert.AreEqual("@", (string)root[0]);
Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", (string)root[1]);
Assert.AreEqual(true, (bool)root[2]);
Assert.AreEqual(10, (int)root[3]);
Assert.AreEqual(10.99, (double)root[4]);
Assert.AreEqual(0.99, (double)root[5]);
Assert.AreEqual(0.000000000000000001d, (double)root[6]);
Assert.AreEqual(0.000000000000000001m, (decimal)root[7]);
Assert.AreEqual(null, (string)root[8]);
Assert.AreEqual("This is a string.", (string)root[9]);
Assert.AreEqual(null, ((JValue)root[10]).Value);
Assert.AreEqual(null, ((JValue)root[11]).Value);
Assert.AreEqual(data, (byte[])root[12]);
}
[Test]
public void State()
{
using (JsonWriter jsonWriter = new JTokenWriter())
{
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
jsonWriter.WriteStartObject();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WritePropertyName("CPU");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
jsonWriter.WriteValue("Intel");
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WritePropertyName("Drives");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
jsonWriter.WriteStartArray();
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
jsonWriter.WriteValue(new BigInteger(123));
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#endif
jsonWriter.WriteValue(new byte[0]);
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteEnd();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
}
}
[Test]
public void WriteComment()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteComment("fail");
writer.WriteEndArray();
StringAssert.AreEqual(@"[
/*fail*/]", writer.Token.ToString());
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
[Test]
public void WriteBigInteger()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteValue(new BigInteger(123));
writer.WriteEndArray();
JValue i = (JValue)writer.Token[0];
Assert.AreEqual(new BigInteger(123), i.Value);
Assert.AreEqual(JTokenType.Integer, i.Type);
StringAssert.AreEqual(@"[
123
]", writer.Token.ToString());
}
#endif
[Test]
public void WriteRaw()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteRaw("fail");
writer.WriteRaw("fail");
writer.WriteEndArray();
// this is a bug. write raw shouldn't be autocompleting like this
// hard to fix without introducing Raw and RawValue token types
// meh
StringAssert.AreEqual(@"[
fail,
fail
]", writer.Token.ToString());
}
[Test]
public void WriteRawValue()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteRawValue("fail");
writer.WriteRawValue("fail");
writer.WriteEndArray();
StringAssert.AreEqual(@"[
fail,
fail
]", writer.Token.ToString());
}
[Test]
public void DateTimeZoneHandling()
{
JTokenWriter writer = new JTokenWriter
{
DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
};
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));
JValue value = (JValue)writer.Token;
DateTime dt = (DateTime)value.Value;
Assert.AreEqual(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc), dt);
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using Avalonia.Data;
using Avalonia.Logging;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Base.UnitTests
{
public class AvaloniaObjectTests_Direct
{
[Fact]
public void GetValue_Gets_Value()
{
var target = new Class1();
Assert.Equal("initial", target.GetValue(Class1.FooProperty));
}
[Fact]
public void GetValue_Gets_Value_NonGeneric()
{
var target = new Class1();
Assert.Equal("initial", target.GetValue((AvaloniaProperty)Class1.FooProperty));
}
[Fact]
public void GetValue_On_Unregistered_Property_Throws_Exception()
{
var target = new Class2();
Assert.Throws<ArgumentException>(() => target.GetValue(Class1.BarProperty));
}
[Fact]
public void SetValue_Sets_Value()
{
var target = new Class1();
target.SetValue(Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target.Foo);
}
[Fact]
public void SetValue_Sets_Value_NonGeneric()
{
var target = new Class1();
target.SetValue((AvaloniaProperty)Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target.Foo);
}
[Fact]
public void SetValue_NonGeneric_Coerces_UnsetValue_To_Default_Value()
{
var target = new Class1();
target.SetValue((AvaloniaProperty)Class1.BazProperty, AvaloniaProperty.UnsetValue);
Assert.Equal(-1, target.Baz);
}
[Fact]
public void SetValue_Raises_PropertyChanged()
{
var target = new Class1();
bool raised = false;
target.PropertyChanged += (s, e) =>
raised = e.Property == Class1.FooProperty &&
(string)e.OldValue == "initial" &&
(string)e.NewValue == "newvalue" &&
e.Priority == BindingPriority.LocalValue;
target.SetValue(Class1.FooProperty, "newvalue");
Assert.True(raised);
}
[Fact]
public void SetValue_Raises_Changed()
{
var target = new Class1();
bool raised = false;
Class1.FooProperty.Changed.Subscribe(e =>
raised = e.Property == Class1.FooProperty &&
(string)e.OldValue == "initial" &&
(string)e.NewValue == "newvalue" &&
e.Priority == BindingPriority.LocalValue);
target.SetValue(Class1.FooProperty, "newvalue");
Assert.True(raised);
}
[Fact]
public void SetValue_On_Unregistered_Property_Throws_Exception()
{
var target = new Class2();
Assert.Throws<ArgumentException>(() => target.SetValue(Class1.BarProperty, "value"));
}
[Fact]
public void GetObservable_Returns_Values()
{
var target = new Class1();
List<string> values = new List<string>();
target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x));
target.Foo = "newvalue";
Assert.Equal(new[] { "initial", "newvalue" }, values);
}
[Fact]
public void Bind_Binds_Property_Value()
{
var target = new Class1();
var source = new Subject<string>();
var sub = target.Bind(Class1.FooProperty, source);
Assert.Equal("initial", target.Foo);
source.OnNext("first");
Assert.Equal("first", target.Foo);
source.OnNext("second");
Assert.Equal("second", target.Foo);
sub.Dispose();
source.OnNext("third");
Assert.Equal("second", target.Foo);
}
[Fact]
public void Bind_Binds_Property_Value_NonGeneric()
{
var target = new Class1();
var source = new Subject<string>();
var sub = target.Bind((AvaloniaProperty)Class1.FooProperty, source);
Assert.Equal("initial", target.Foo);
source.OnNext("first");
Assert.Equal("first", target.Foo);
source.OnNext("second");
Assert.Equal("second", target.Foo);
sub.Dispose();
source.OnNext("third");
Assert.Equal("second", target.Foo);
}
[Fact]
public void Bind_NonGeneric_Uses_UnsetValue()
{
var target = new Class1();
var source = new Subject<object>();
var sub = target.Bind((AvaloniaProperty)Class1.BazProperty, source);
Assert.Equal(5, target.Baz);
source.OnNext(6);
Assert.Equal(6, target.Baz);
source.OnNext(AvaloniaProperty.UnsetValue);
Assert.Equal(-1, target.Baz);
}
[Fact]
public void Bind_Handles_Wrong_Type()
{
var target = new Class1();
var source = new Subject<object>();
var sub = target.Bind(Class1.FooProperty, source);
source.OnNext(45);
Assert.Equal(null, target.Foo);
}
[Fact]
public void Bind_Handles_Wrong_Value_Type()
{
var target = new Class1();
var source = new Subject<object>();
var sub = target.Bind(Class1.BazProperty, source);
source.OnNext("foo");
Assert.Equal(0, target.Baz);
}
[Fact]
public void ReadOnly_Property_Cannot_Be_Set()
{
var target = new Class1();
Assert.Throws<ArgumentException>(() =>
target.SetValue(Class1.BarProperty, "newvalue"));
}
[Fact]
public void ReadOnly_Property_Cannot_Be_Set_NonGeneric()
{
var target = new Class1();
Assert.Throws<ArgumentException>(() =>
target.SetValue((AvaloniaProperty)Class1.BarProperty, "newvalue"));
}
[Fact]
public void ReadOnly_Property_Cannot_Be_Bound()
{
var target = new Class1();
var source = new Subject<string>();
Assert.Throws<ArgumentException>(() =>
target.Bind(Class1.BarProperty, source));
}
[Fact]
public void ReadOnly_Property_Cannot_Be_Bound_NonGeneric()
{
var target = new Class1();
var source = new Subject<string>();
Assert.Throws<ArgumentException>(() =>
target.Bind(Class1.BarProperty, source));
}
[Fact]
public void GetValue_Gets_Value_On_AddOwnered_Property()
{
var target = new Class2();
Assert.Equal("initial2", target.GetValue(Class2.FooProperty));
}
[Fact]
public void GetValue_Gets_Value_On_AddOwnered_Property_Using_Original()
{
var target = new Class2();
Assert.Equal("initial2", target.GetValue(Class1.FooProperty));
}
[Fact]
public void GetValue_Gets_Value_On_AddOwnered_Property_Using_Original_NonGeneric()
{
var target = new Class2();
Assert.Equal("initial2", target.GetValue((AvaloniaProperty)Class1.FooProperty));
}
[Fact]
public void SetValue_Sets_Value_On_AddOwnered_Property_Using_Original()
{
var target = new Class2();
target.SetValue(Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target.Foo);
}
[Fact]
public void SetValue_Sets_Value_On_AddOwnered_Property_Using_Original_NonGeneric()
{
var target = new Class2();
target.SetValue((AvaloniaProperty)Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target.Foo);
}
[Fact]
public void UnsetValue_Is_Used_On_AddOwnered_Property()
{
var target = new Class2();
target.SetValue((AvaloniaProperty)Class1.FooProperty, AvaloniaProperty.UnsetValue);
Assert.Equal("unset", target.Foo);
}
[Fact]
public void Bind_Binds_AddOwnered_Property_Value()
{
var target = new Class2();
var source = new Subject<string>();
var sub = target.Bind(Class1.FooProperty, source);
Assert.Equal("initial2", target.Foo);
source.OnNext("first");
Assert.Equal("first", target.Foo);
source.OnNext("second");
Assert.Equal("second", target.Foo);
sub.Dispose();
source.OnNext("third");
Assert.Equal("second", target.Foo);
}
[Fact]
public void Bind_Binds_AddOwnered_Property_Value_NonGeneric()
{
var target = new Class2();
var source = new Subject<string>();
var sub = target.Bind((AvaloniaProperty)Class1.FooProperty, source);
Assert.Equal("initial2", target.Foo);
source.OnNext("first");
Assert.Equal("first", target.Foo);
source.OnNext("second");
Assert.Equal("second", target.Foo);
sub.Dispose();
source.OnNext("third");
Assert.Equal("second", target.Foo);
}
[Fact]
public void Property_Notifies_Initialized()
{
Class1 target;
bool raised = false;
Class1.FooProperty.Initialized.Subscribe(e =>
raised = e.Property == Class1.FooProperty &&
e.OldValue == AvaloniaProperty.UnsetValue &&
(string)e.NewValue == "initial" &&
e.Priority == BindingPriority.Unset);
target = new Class1();
Assert.True(raised);
}
[Fact]
public void BindingError_Does_Not_Cause_Target_Update()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.FooProperty, source);
source.OnNext("initial");
source.OnNext(new BindingNotification(new InvalidOperationException("Foo"), BindingErrorType.Error));
Assert.Equal("initial", target.GetValue(Class1.FooProperty));
}
[Fact]
public void BindingError_With_FallbackValue_Causes_Target_Update()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.FooProperty, source);
source.OnNext("initial");
source.OnNext(new BindingNotification(
new InvalidOperationException("Foo"),
BindingErrorType.Error,
"fallback"));
Assert.Equal("fallback", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Binding_To_Direct_Property_Logs_BindingError()
{
var target = new Class1();
var source = new Subject<object>();
var called = false;
LogCallback checkLogMessage = (level, area, src, mt, pv) =>
{
if (level == LogEventLevel.Error &&
area == LogArea.Binding &&
mt == "Error in binding to {Target}.{Property}: {Message}" &&
pv.Length == 3 &&
pv[0] is Class1 &&
object.ReferenceEquals(pv[1], Class1.FooProperty) &&
(string)pv[2] == "Binding Error Message")
{
called = true;
}
};
using (TestLogSink.Start(checkLogMessage))
{
target.Bind(Class1.FooProperty, source);
source.OnNext("baz");
source.OnNext(new BindingNotification(new InvalidOperationException("Binding Error Message"), BindingErrorType.Error));
}
Assert.True(called);
}
private class Class1 : AvaloniaObject
{
public static readonly DirectProperty<Class1, string> FooProperty =
AvaloniaProperty.RegisterDirect<Class1, string>(
"Foo",
o => o.Foo,
(o, v) => o.Foo = v,
unsetValue: "unset");
public static readonly DirectProperty<Class1, string> BarProperty =
AvaloniaProperty.RegisterDirect<Class1, string>("Bar", o => o.Bar);
public static readonly DirectProperty<Class1, int> BazProperty =
AvaloniaProperty.RegisterDirect<Class1, int>(
"Bar",
o => o.Baz,
(o,v) => o.Baz = v,
unsetValue: -1);
private string _foo = "initial";
private readonly string _bar = "bar";
private int _baz = 5;
public string Foo
{
get { return _foo; }
set { SetAndRaise(FooProperty, ref _foo, value); }
}
public string Bar
{
get { return _bar; }
}
public int Baz
{
get { return _baz; }
set { SetAndRaise(BazProperty, ref _baz, value); }
}
}
private class Class2 : AvaloniaObject
{
public static readonly DirectProperty<Class2, string> FooProperty =
Class1.FooProperty.AddOwner<Class2>(o => o.Foo, (o, v) => o.Foo = v);
private string _foo = "initial2";
static Class2()
{
}
public string Foo
{
get { return _foo; }
set { SetAndRaise(FooProperty, ref _foo, 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 Internal.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.IO
{
// A MemoryStream represents a Stream in memory (i.e, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
//
// There are two ways to create a MemoryStream. You can initialize one
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
private int _origin; // For user-provided arrays, start at this origin
private int _position; // read/write head.
private int _length; // Number of bytes within the memory stream
private int _capacity; // length of usable portion of buffer for stream
// Note that _capacity == _buffer.Length for non-user-provided byte[]'s
private bool _expandable; // User-provided buffers aren't expandable.
private bool _writable; // Can user write to this stream?
private bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
// <TODO>In V2, if we get support for arrays of more than 2 GB worth of elements,
// consider removing this constraint, or setting it to Int64.MaxValue.</TODO>
private const int MemStreamMaxLength = int.MaxValue;
public MemoryStream()
: this(0)
{
}
public MemoryStream(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity);
}
_buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>();
_capacity = capacity;
_expandable = true;
_writable = true;
_exposable = true;
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
public MemoryStream(byte[] buffer)
: this(buffer, true)
{
}
public MemoryStream(byte[] buffer, bool writable)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
_buffer = buffer;
_length = _capacity = buffer.Length;
_writable = writable;
_exposable = false;
_origin = 0;
_isOpen = true;
}
public MemoryStream(byte[] buffer, int index, int count)
: this(buffer, index, count, true, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable)
: this(buffer, index, count, writable, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
_writable = writable;
_exposable = publiclyVisible; // Can TryGetBuffer return the array?
_expandable = false;
_isOpen = true;
}
public override bool CanRead => _isOpen;
public override bool CanSeek => _isOpen;
public override bool CanWrite => _writable;
private void EnsureWriteable()
{
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
_isOpen = false;
_writable = false;
_expandable = false;
// Don't set buffer to null - allow TryGetBuffer & ToArray to work.
}
}
finally
{
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value)
{
// Check for overflow
if (value < 0)
{
throw new IOException(SR.IO_IO_StreamTooLong);
}
if (value > _capacity)
{
int newCapacity = value;
if (newCapacity < 256)
{
newCapacity = 256;
}
if (newCapacity < _capacity * 2)
{
newCapacity = _capacity * 2;
}
Capacity = newCapacity;
return true;
}
return false;
}
public override void Flush()
{
}
#pragma warning disable 1998 //async method with no await operators
public override async Task FlushAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Flush();
}
#pragma warning restore 1998
public virtual bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (!_exposable)
{
buffer = default(ArraySegment<byte>);
return false;
}
buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin));
return true;
}
public virtual byte[] GetBuffer()
{
if (!_exposable)
throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
return _buffer;
}
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
internal byte[] InternalGetBuffer()
{
return _buffer;
}
// PERF: True cursor position, we don't need _origin for direct access
internal int InternalGetPosition()
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _position;
}
// PERF: Takes out Int32 as fast as possible
internal int InternalReadInt32()
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
int pos = (_position += 4); // use temp to avoid race
if (pos > _length)
{
_position = _length;
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24);
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
internal int InternalEmulateRead(int count)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
int n = _length - _position;
if (n > count)
{
n = count;
}
if (n < 0)
{
n = 0;
}
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
public virtual int Capacity
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _capacity - _origin;
}
set
{
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
if (value < Length)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (!_expandable && (value != Capacity))
{
throw new NotSupportedException(SR.NotSupported_MemStreamNotExpandable);
}
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
if (_expandable && value != _capacity)
{
if (value > 0)
{
byte[] newBuffer = new byte[value];
if (_length > 0)
{
Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _length);
}
_buffer = newBuffer;
}
else
{
_buffer = null;
}
_capacity = value;
}
}
}
public override long Length
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _length - _origin;
}
}
public override long Position
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _position - _origin;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (value > MemStreamMaxLength)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
_position = _origin + (int)value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
int n = _length - _position;
if (n > count)
{
n = count;
}
if (n <= 0)
{
return 0;
}
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
int byteCount = n;
while (--byteCount >= 0)
buffer[offset + byteCount] = _buffer[_position + byteCount];
}
else
Buffer.BlockCopy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
public override int Read(Span<byte> destination)
{
if (GetType() != typeof(MemoryStream))
{
// MemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior
// to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload
// should use the behavior of Read(byte[],int,int) overload.
return base.Read(destination);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
int n = Math.Min(_length - _position, destination.Length);
if (n <= 0)
{
return 0;
}
// TODO: Read(byte[], int, int) has an n <= 8 optimization, presumably
// based on benchmarking. Determine if/where such a cut-off is here and
// add an equivalent optimization if necessary.
new Span<byte>(_buffer, _position, n).CopyTo(destination);
_position += n;
return n;
}
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadAsyncImpl(buffer, offset, count, cancellationToken);
}
#pragma warning disable 1998 //async method with no await operators
private async Task<int> ReadAsyncImpl(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Read(buffer, offset, count);
}
public override async ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
// ReadAsync(Memory<byte>,...) needs to delegate to an existing virtual to do the work, in case an existing derived type
// has changed or augmented the logic associated with reads. If the Memory wraps an array, we could delegate to
// ReadAsync(byte[], ...), but that would defeat part of the purpose, as ReadAsync(byte[], ...) often needs to allocate
// a Task<int> for the return value, so we want to delegate to one of the synchronous methods. We could always
// delegate to the Read(Span<byte>) method, and that's the most efficient solution when dealing with a concrete
// MemoryStream, but if we're dealing with a type derived from MemoryStream, Read(Span<byte>) will end up delegating
// to Read(byte[], ...), which requires it to get a byte[] from ArrayPool and copy the data. So, we special-case the
// very common case of the Memory<byte> wrapping an array: if it does, we delegate to Read(byte[], ...) with it,
// as that will be efficient in both cases, and we fall back to Read(Span<byte>) if the Memory<byte> wrapped something
// else; if this is a concrete MemoryStream, that'll be efficient, and only in the case where the Memory<byte> wrapped
// something other than an array and this is a MemoryStream-derived type that doesn't override Read(Span<byte>) will
// it then fall back to doing the ArrayPool/copy behavior.
return destination.TryGetArray(out ArraySegment<byte> destinationArray) ?
Read(destinationArray.Array, destinationArray.Offset, destinationArray.Count) :
Read(destination.Span);
}
#pragma warning restore 1998
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
public override int ReadByte()
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (_position >= _length)
{
return -1;
}
return _buffer[_position++];
}
public override void CopyTo(Stream destination, int bufferSize)
{
// Since we did not originally override this method, validate the arguments
// the same way Stream does for back-compat.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
base.CopyTo(destination, bufferSize);
return;
}
int originalPosition = _position;
// Seek to the end of the MemoryStream.
int remaining = InternalEmulateRead(_length - originalPosition);
// If we were already at or past the end, there's no copying to do so just quit.
if (remaining > 0)
{
// Call Write() on the other Stream, using our internal buffer and avoiding any
// intermediary allocations.
destination.Write(_buffer, originalPosition, remaining);
}
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// This implementation offers better performance compared to the base class version.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into ReadAsync) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
return base.CopyToAsync(destination, bufferSize, cancellationToken);
}
return CopyToAsyncImpl(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncImpl(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
int pos = _position;
int n = InternalEmulateRead(_length - _position);
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
if (memStrDest == null)
{
await destination.WriteAsync(_buffer, pos, n, cancellationToken).ConfigureAwait(false);
}
else
{
memStrDest.Write(_buffer, pos, n);
}
}
public override long Seek(long offset, SeekOrigin loc)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (offset > MemStreamMaxLength)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength);
}
switch (loc)
{
case SeekOrigin.Begin:
{
int tempPosition = unchecked(_origin + (int)offset);
if (offset < 0 || tempPosition < _origin)
{
throw new IOException(SR.IO_IO_SeekBeforeBegin);
}
_position = tempPosition;
break;
}
case SeekOrigin.Current:
{
int tempPosition = unchecked(_position + (int)offset);
if (unchecked(_position + offset) < _origin || tempPosition < _origin)
{
throw new IOException(SR.IO_IO_SeekBeforeBegin);
}
_position = tempPosition;
break;
}
case SeekOrigin.End:
{
int tempPosition = unchecked(_length + (int)offset);
if (unchecked(_length + offset) < _origin || tempPosition < _origin)
{
throw new IOException(SR.IO_IO_SeekBeforeBegin);
}
_position = tempPosition;
break;
}
default:
throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, Int32.MaxValue - origin
// Origin is 0 in all cases other than a MemoryStream created on
// top of an existing array and a specific starting offset was passed
// into the MemoryStream constructor. The upper bounds prevents any
// situations where a stream may be created on top of an array then
// the stream is made longer than the maximum possible length of the
// array (Int32.MaxValue).
//
public override void SetLength(long value)
{
if (value < 0 || value > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
EnsureWriteable();
// Origin wasn't publicly exposed above.
Debug.Assert(MemStreamMaxLength == int.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (int.MaxValue - _origin))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
{
Array.Clear(_buffer, _length, newLength - _length);
}
_length = newLength;
if (_position > newLength)
{
_position = newLength;
}
}
public virtual byte[] ToArray()
{
//BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy.");
int count = _length - _origin;
if (count == 0)
{
return Array.Empty<byte>();
}
byte[] copy = new byte[count];
Buffer.BlockCopy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
EnsureWriteable();
int i = _position + count;
// Check for overflow
if (i < 0)
{
throw new IOException(SR.IO_IO_StreamTooLong);
}
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, i - _length);
}
_length = i;
}
if ((count <= 8) && (buffer != _buffer))
{
int byteCount = count;
while (--byteCount >= 0)
{
_buffer[_position + byteCount] = buffer[offset + byteCount];
}
}
else
{
Buffer.BlockCopy(buffer, offset, _buffer, _position, count);
}
_position = i;
}
public override void Write(ReadOnlySpan<byte> source)
{
if (GetType() != typeof(MemoryStream))
{
// MemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior
// to this Write(Span<byte>) overload being introduced. In that case, this Write(Span<byte>) overload
// should use the behavior of Write(byte[],int,int) overload.
base.Write(source);
return;
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
EnsureWriteable();
// Check for overflow
int i = _position + source.Length;
if (i < 0)
{
throw new IOException(SR.IO_StreamTooLong);
}
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, i - _length);
}
_length = i;
}
source.CopyTo(new Span<byte>(_buffer, _position, source.Length));
_position = i;
}
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return WriteAsyncImpl(buffer, offset, count, cancellationToken);
}
#pragma warning disable 1998 //async method with no await operators
private async Task WriteAsyncImpl(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Write(buffer, offset, count);
}
public override async Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
// See corresponding comment in ReadAsync for why we don't just always use Write(ReadOnlySpan<byte>).
// Unlike ReadAsync, we could delegate to WriteAsync(byte[], ...) here, but we don't for consistency.
if (source.DangerousTryGetArray(out ArraySegment<byte> sourceArray))
{
Write(sourceArray.Array, sourceArray.Offset, sourceArray.Count);
}
else
{
Write(source.Span);
}
}
#pragma warning restore 1998
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
public override void WriteByte(byte value)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
EnsureWriteable();
if (_position >= _length)
{
int newLength = _position + 1;
bool mustZero = _position > _length;
if (newLength >= _capacity)
{
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, _position - _length);
}
_length = newLength;
}
_buffer[_position++] = value;
}
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
stream.Write(_buffer, _origin, _length - _origin);
}
}
}
| |
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Xunit;
#if NET461
using Microsoft.Owin.Testing;
#endif
namespace RimDev.Stuntman.Core.Tests
{
public class StuntmanOptionsTests
{
public class SignInUriProperty
{
[Fact]
public void BeginsWithDefaultRootPathWhenNotSpecified()
{
var sut = new StuntmanOptions();
Assert.StartsWith(Constants.StuntmanOptions.DefaultStuntmanRootPath, sut.SignInUri);
}
[Fact]
public void BeginsWithSpecifiedRootPath()
{
var sut = new StuntmanOptions("custom/root/path");
Assert.StartsWith("custom/root/path", sut.SignInUri);
}
[Fact]
public void AddsTrailingSlashToRootPath()
{
var sut = new StuntmanOptions("custom/root/path");
Assert.StartsWith("custom/root/path/", sut.SignInUri);
}
[Fact]
public void EndsWithCorrectSuffix()
{
var sut = new StuntmanOptions();
Assert.EndsWith(Constants.StuntmanOptions.SignInEndpoint, sut.SignInUri);
}
}
public class SignOutUriProperty
{
[Fact]
public void BeginsWithDefaultRootPathWhenNotSpecified()
{
var sut = new StuntmanOptions();
Assert.StartsWith(Constants.StuntmanOptions.DefaultStuntmanRootPath, sut.SignOutUri);
}
[Fact]
public void BeginsWithSpecifiedRootPath()
{
var sut = new StuntmanOptions("custom/root/path");
Assert.StartsWith("custom/root/path", sut.SignOutUri);
}
[Fact]
public void AddsTrailingSlashToRootPath()
{
var sut = new StuntmanOptions("custom/root/path");
Assert.StartsWith("custom/root/path/", sut.SignOutUri);
}
[Fact]
public void EndsWithCorrectSuffix()
{
var sut = new StuntmanOptions();
Assert.EndsWith(Constants.StuntmanOptions.SignOutEndpoint, sut.SignOutUri);
}
}
public class UserPickerAlignmentProperty
{
[Fact]
public void DefaultsToStuntmanAlignmentLeft()
{
var sut = new StuntmanOptions();
Assert.Equal(StuntmanAlignment.Left, sut.UserPickerAlignment);
}
}
public class AddUserMethod
{
[Fact]
public void ThrowsForNullUser()
{
Assert.Throws<ArgumentNullException>(
() => new StuntmanOptions().AddUser(null));
}
[Fact]
public void AddsUser()
{
var sut = new StuntmanOptions();
sut.AddUser(new StuntmanUser("user-1", "User 1"));
var user = sut.Users.Single();
Assert.Equal("user-1", user.Id);
Assert.Equal("User 1", user.Name);
}
[Fact]
public void ThrowsForDuplicateId()
{
var sut = new StuntmanOptions();
var user = new StuntmanUser("user-1", "User 1");
sut.AddUser(user);
var exception = Assert.Throws<Exception>(() =>
{
sut.AddUser(user);
});
Assert.Equal("user must have unique Id.", exception.Message);
}
[Fact]
public void SetsSourceToLocalSource()
{
var sut = new StuntmanOptions();
sut.AddUser(new StuntmanUser("user-1", "User 1"));
var user = sut.Users.Single();
Assert.Equal(Constants.StuntmanOptions.LocalSource, user.Source);
}
}
public class AddUsersMethod
{
[Fact]
public void ThrowsForNullUsers()
{
Assert.Throws<ArgumentNullException>(
() => new StuntmanOptions().AddUsers(null));
}
[Fact]
public void AddsUsers()
{
var sut = new StuntmanOptions();
var users = Enumerable.Range(1, 10)
.Select(i => new StuntmanUser(i.ToString(), $"user-{i}"))
.ToList();
var options = sut.AddUsers(users);
Assert.Equal(10, options.Users.Count);
}
}
public class AddUsersFromJsonMethod
{
#if NET461
[Fact]
public async Task AddsUsersFromFileSystem()
{
const string Id1 = "user-1";
const string Name1 = "Test Name 1";
const string Id2 = "user-2";
const string Name2 = "Test Name 2";
var json = string.Empty;
var stuntmanOptions = new StuntmanOptions()
.AddUser(new StuntmanUser(Id1, Name1))
.AddUser(new StuntmanUser(Id2, Name2));
using (var server = TestServer.Create(app =>
{
stuntmanOptions.EnableServer();
app.UseStuntman(stuntmanOptions);
}))
{
var response = await server.HttpClient.GetAsync(stuntmanOptions.ServerUri);
json = await response.Content.ReadAsStringAsync();
}
var options = new StuntmanOptions(
stuntmanOptionsRetriever:
new TestStuntmanOptionsRetriever(localFileStringToReturn: json))
.AddUsersFromJson("C:\\test.json");
Assert.Equal(2, options.Users.Count);
Assert.NotNull(options.Users.SingleOrDefault(x => x.Id == Id1));
Assert.NotNull(options.Users.SingleOrDefault(x => x.Name == Name1));
Assert.NotNull(options.Users.SingleOrDefault(x => x.Id == Id2));
Assert.NotNull(options.Users.SingleOrDefault(x => x.Name == Name2));
}
[Fact]
public async Task AddsUsersFromWebClientRequest()
{
const string Id1 = "user-1";
const string Name1 = "Test Name 1";
const string Id2 = "user-2";
const string Name2 = "Test Name 2";
var json = string.Empty;
var stuntmanOptions = new StuntmanOptions()
.AddUser(new StuntmanUser(Id1, Name1))
.AddUser(new StuntmanUser(Id2, Name2));
using (var server = TestServer.Create(app =>
{
stuntmanOptions.EnableServer();
app.UseStuntman(stuntmanOptions);
}))
{
var response = await server.HttpClient.GetAsync(stuntmanOptions.ServerUri);
json = await response.Content.ReadAsStringAsync();
}
var options = new StuntmanOptions(
stuntmanOptionsRetriever:
new TestStuntmanOptionsRetriever(webClientStringToReturn: json))
.AddUsersFromJson("https://example.com");
Assert.Equal(2, options.Users.Count);
Assert.NotNull(options.Users.SingleOrDefault(x => x.Id == Id1));
Assert.NotNull(options.Users.SingleOrDefault(x => x.Name == Name1));
Assert.NotNull(options.Users.SingleOrDefault(x => x.Id == Id2));
Assert.NotNull(options.Users.SingleOrDefault(x => x.Name == Name2));
}
[Fact]
public async Task AddsUserClaims()
{
const string ClaimType = "TestClaim";
const string ClaimValue = "TestClaimValue";
var json = string.Empty;
var stuntmanOptions = new StuntmanOptions()
.AddUser(new StuntmanUser("user-1", "Test Name 1")
.AddClaim(ClaimType, ClaimValue))
.AddUser(new StuntmanUser("user-2", "Test Name 2"));
using (var server = TestServer.Create(app =>
{
stuntmanOptions.EnableServer();
app.UseStuntman(stuntmanOptions);
}))
{
var response = await server.HttpClient.GetAsync(stuntmanOptions.ServerUri);
json = await response.Content.ReadAsStringAsync();
}
var options = new StuntmanOptions(
stuntmanOptionsRetriever:
new TestStuntmanOptionsRetriever(localFileStringToReturn: json))
.AddUsersFromJson("C:\\test.json");
var user1 = options.Users.SingleOrDefault(x => x.Claims.Any());
Assert.NotNull(user1);
var testClaim = user1.Claims.Single();
Assert.Equal(ClaimType, testClaim.Type);
Assert.Equal(ClaimValue, testClaim.Value);
}
[Fact]
public async Task AllowsOptionalConfigurationOfUsers()
{
const string TestClaim = "test-claim";
const string TestClaimValue = "test-claim-value";
var json = string.Empty;
var stuntmanOptions = new StuntmanOptions()
.AddUser(new StuntmanUser("user-1", "Test Name 1"))
.AddUser(new StuntmanUser("user-2", "Test Name 2"));
using (var server = TestServer.Create(app =>
{
stuntmanOptions.EnableServer();
app.UseStuntman(stuntmanOptions);
}))
{
var response = await server.HttpClient.GetAsync(stuntmanOptions.ServerUri);
json = await response.Content.ReadAsStringAsync();
}
var options = new StuntmanOptions(
stuntmanOptionsRetriever:
new TestStuntmanOptionsRetriever(localFileStringToReturn: json))
.AddUsersFromJson(
"C:\\test.json",
user => user.Claims.Add(new Claim(TestClaim, TestClaimValue)));
Assert.True(options.Users.Any());
Assert.True(options.Users.All(
x => x.Claims.Count(y => y.Type == TestClaim && y.Value == TestClaimValue) == 1));
}
#endif
[Fact]
public void ThrowsForNullPathOrUrl()
{
Assert.Throws<ArgumentNullException>(
() => new StuntmanOptions().AddUsersFromJson(null));
}
[Theory,
InlineData(""),
InlineData(" "),
InlineData("../file.json"),
InlineData("..\\file.json"),
]
public void ThrowsForInvalidUri(string pathOrUrl)
{
Assert.Throws<UriFormatException>(
() => new StuntmanOptions().AddUsersFromJson(pathOrUrl));
}
[Fact]
public void ThrowsForInvalidJson()
{
var json = @"{{""}}{{";
Assert.Throws<JsonReaderException>(
() => new StuntmanOptions(stuntmanOptionsRetriever: new TestStuntmanOptionsRetriever(json))
.AddUsersFromJson("C:\\test.json"));
}
}
public class AddConfigurationFromServer
{
[Fact]
public void ThrowsForNullServerBaseUrl()
{
Assert.Throws<ArgumentNullException>(
"serverBaseUrl",
() => new StuntmanOptions().AddConfigurationFromServer(null));
}
[Theory,
InlineData(""),
InlineData(" "),
InlineData("file.json")
]
public void ThrowsForInvalidUri(string serverBaseUrl)
{
Assert.Throws<UriFormatException>(
() => new StuntmanOptions().AddConfigurationFromServer(serverBaseUrl));
}
[Fact]
public void ThrowsForUnexpectedResponse()
{
var options = new StuntmanOptions(stuntmanOptionsRetriever: new TestStuntmanOptionsRetriever(
webClientStringToReturn: "some_error"));
Assert.Throws<JsonReaderException>(
() => options.AddConfigurationFromServer("https://example.com"));
}
[Fact]
public void AddsStuntmanServerResponseUsers()
{
const string Id1 = "user-1";
var stuntmanServerResponse = new StuntmanServerResponse
{
Users = new[]
{
new StuntmanUser(Id1, "User 1")
}
};
var json = JsonConvert.SerializeObject(stuntmanServerResponse);
var options = new StuntmanOptions(stuntmanOptionsRetriever: new TestStuntmanOptionsRetriever(
webClientStringToReturn: json));
options.AddConfigurationFromServer("https://example.com");
Assert.Equal(Id1, options.Users.Single().Id);
}
[Fact]
public void SetsSourceToserverBaseUrl()
{
const string ServerBaseUrl = "https://example.com";
var stuntmanServerResponse = new StuntmanServerResponse
{
Users = new[]
{
new StuntmanUser("user-1", "User 1")
}
};
var json = JsonConvert.SerializeObject(stuntmanServerResponse);
var options = new StuntmanOptions(stuntmanOptionsRetriever: new TestStuntmanOptionsRetriever(
webClientStringToReturn: json));
options.AddConfigurationFromServer(ServerBaseUrl);
Assert.Equal(ServerBaseUrl, options.Users.Single().Source);
}
}
public class TryAddConfigurationFromServer
{
[Fact]
public void ThrowsForNullServerBaseUrl()
{
Assert.Throws<ArgumentNullException>(
"serverBaseUrl",
() => new StuntmanOptions().TryAddConfigurationFromServer(null));
}
[Fact]
public void DoesNotThrowForUnexpectedResponse()
{
var options = new StuntmanOptions(stuntmanOptionsRetriever: new TestStuntmanOptionsRetriever(
webClientStringToReturn: "some_error"));
options.TryAddConfigurationFromServer("https://example.com");
}
[Fact]
public void ProcessesStuntmanServerResponse()
{
const string Id1 = "user-1";
var stuntmanServerResponse = new StuntmanServerResponse
{
Users = new[]
{
new StuntmanUser(Id1, "User 1")
}
};
var json = JsonConvert.SerializeObject(stuntmanServerResponse);
var options = new StuntmanOptions(stuntmanOptionsRetriever: new TestStuntmanOptionsRetriever(
webClientStringToReturn: json));
options.TryAddConfigurationFromServer("https://example.com");
Assert.Equal(Id1, options.Users.Single().Id);
}
[Fact]
public void SetsSourceToserverBaseUrl()
{
const string ServerBaseUrl = "https://example.com";
var stuntmanServerResponse = new StuntmanServerResponse
{
Users = new[]
{
new StuntmanUser("user-1", "User 1")
}
};
var json = JsonConvert.SerializeObject(stuntmanServerResponse);
var options = new StuntmanOptions(stuntmanOptionsRetriever: new TestStuntmanOptionsRetriever(
webClientStringToReturn: json));
options.TryAddConfigurationFromServer(ServerBaseUrl);
Assert.Equal(ServerBaseUrl, options.Users.Single().Source);
}
[Fact]
public void InvokesonExceptionWhenExceptionThrown()
{
var options = new StuntmanOptions(stuntmanOptionsRetriever: new TestStuntmanOptionsRetriever(
webClientStringToReturn: "error"));
Exception actualException = null;
options.TryAddConfigurationFromServer(
"https://example.com", (ex) => { actualException = ex; });
Assert.NotNull(actualException);
Assert.Equal(
"Unexpected character encountered while parsing value: "
+ "e. Path '', line 0, position 0.",
actualException.Message);
}
}
public class SetUserPickerAlignmentMethod
{
[Theory,
InlineData(StuntmanAlignment.Left),
InlineData(StuntmanAlignment.Center),
InlineData(StuntmanAlignment.Right)]
public void SetsUserPickerAlignment(StuntmanAlignment alignment)
{
var sut = new StuntmanOptions();
sut.SetUserPickerAlignment(alignment);
Assert.Equal(alignment, sut.UserPickerAlignment);
}
}
public class UserPickerMethod_IPrincipal
{
// Rely on tests in UserPickerTests
}
public class UserPickerMethod_IPrincipal_String
{
// Rely on tests in UserPickerTests
}
private class TestStuntmanOptionsRetriever : StuntmanOptionsRetriever
{
private readonly string _localFileStringToReturn;
private readonly string _webClientStringToReturn;
public TestStuntmanOptionsRetriever(
string localFileStringToReturn = null,
string webClientStringToReturn = null)
{
_localFileStringToReturn = localFileStringToReturn;
_webClientStringToReturn = webClientStringToReturn;
}
public override string GetStringFromLocalFile(Uri uri)
{
if (_localFileStringToReturn == null)
{
return base.GetStringFromLocalFile(uri);
}
return _localFileStringToReturn;
}
public override string GetStringUsingWebClient(Uri uri)
{
if (_webClientStringToReturn == null)
{
return base.GetStringUsingWebClient(uri);
}
return _webClientStringToReturn;
}
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace Avro
{
/// <summary>
/// Base class for all schema types
/// </summary>
public abstract class Schema
{
/// <summary>
/// Enum for schema types
/// </summary>
public enum Type
{
Null,
Boolean,
Int,
Long,
Float,
Double,
Bytes,
String,
Record,
Enumeration,
Array,
Map,
Union,
Fixed,
Error
}
/// <summary>
/// Schema type property
/// </summary>
public Type Tag { get; private set; }
/// <summary>
/// Additional JSON attributes apart from those defined in the AVRO spec
/// </summary>
internal PropertyMap Props { get; private set; }
/// <summary>
/// Constructor for schema class
/// </summary>
/// <param name="type"></param>
protected Schema(Type type, PropertyMap props)
{
this.Tag = type;
this.Props = props;
}
/// <summary>
/// The name of this schema. If this is a named schema such as an enum, it returns the fully qualified
/// name for the schema. For other schemas, it returns the type of the schema.
/// </summary>
public abstract string Name { get; }
/// <summary>
/// Static class to return new instance of schema object
/// </summary>
/// <param name="jtok">JSON object</param>
/// <param name="names">list of named schemas already read</param>
/// <param name="encspace">enclosing namespace of the schema</param>
/// <returns>new Schema object</returns>
internal static Schema ParseJson(JToken jtok, SchemaNames names, string encspace)
{
if (null == jtok) throw new ArgumentNullException("j", "j cannot be null.");
if (jtok.Type == JTokenType.String) // primitive schema with no 'type' property or primitive or named type of a record field
{
string value = (string)jtok;
PrimitiveSchema ps = PrimitiveSchema.NewInstance(value);
if (null != ps) return ps;
NamedSchema schema = null;
if (names.TryGetValue(value, null, encspace, out schema)) return schema;
throw new SchemaParseException("Undefined name: " + value);
}
if (jtok is JArray) // union schema with no 'type' property or union type for a record field
return UnionSchema.NewInstance(jtok as JArray, null, names, encspace);
if (jtok is JObject) // JSON object with open/close parenthesis, it must have a 'type' property
{
JObject jo = jtok as JObject;
JToken jtype = jo["type"];
if (null == jtype)
throw new SchemaParseException("Property type is required");
var props = Schema.GetProperties(jtok);
if (jtype.Type == JTokenType.String)
{
string type = (string)jtype;
if (type.Equals("array"))
return ArraySchema.NewInstance(jtok, props, names, encspace);
if (type.Equals("map"))
return MapSchema.NewInstance(jtok, props, names, encspace);
Schema schema = PrimitiveSchema.NewInstance((string)type, props);
if (null != schema) return schema;
return NamedSchema.NewInstance(jo, props, names, encspace);
}
else if (jtype.Type == JTokenType.Array)
return UnionSchema.NewInstance(jtype as JArray, props, names, encspace);
}
throw new AvroTypeException("Invalid JSON for schema: " + jtok);
}
/// <summary>
/// Parses a given JSON string to create a new schema object
/// </summary>
/// <param name="json">JSON string</param>
/// <returns>new Schema object</returns>
public static Schema Parse(string json)
{
if (string.IsNullOrEmpty(json)) throw new ArgumentNullException("json", "json cannot be null.");
return Parse(json.Trim(), new SchemaNames(), null); // standalone schema, so no enclosing namespace
}
/// <summary>
/// Parses a JSON string to create a new schema object
/// </summary>
/// <param name="json">JSON string</param>
/// <param name="names">list of named schemas already read</param>
/// <param name="encspace">enclosing namespace of the schema</param>
/// <returns>new Schema object</returns>
internal static Schema Parse(string json, SchemaNames names, string encspace)
{
Schema sc = PrimitiveSchema.NewInstance(json);
if (null != sc) return sc;
try
{
bool IsArray = json.StartsWith("[") && json.EndsWith("]");
JContainer j = IsArray ? (JContainer)JArray.Parse(json) : (JContainer)JObject.Parse(json);
return ParseJson(j, names, encspace);
}
catch (Newtonsoft.Json.JsonSerializationException ex)
{
throw new SchemaParseException("Could not parse. " + ex.Message + Environment.NewLine + json);
}
}
/// <summary>
/// Static function to parse custom properties (not defined in the Avro spec) from the given JSON object
/// </summary>
/// <param name="jtok">JSON object to parse</param>
/// <returns>Property map if custom properties were found, null if no custom properties found</returns>
internal static PropertyMap GetProperties(JToken jtok)
{
var props = new PropertyMap();
props.Parse(jtok);
if (props.Count > 0)
return props;
else
return null;
}
/// <summary>
/// Returns the canonical JSON representation of this schema.
/// </summary>
/// <returns>The canonical JSON representation of this schema.</returns>
public override string ToString()
{
System.IO.StringWriter sw = new System.IO.StringWriter();
Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);
if (this is PrimitiveSchema || this is UnionSchema)
{
writer.WriteStartObject();
writer.WritePropertyName("type");
}
WriteJson(writer, new SchemaNames(), null); // stand alone schema, so no enclosing name space
if (this is PrimitiveSchema || this is UnionSchema)
writer.WriteEndObject();
return sw.ToString();
}
/// <summary>
/// Writes opening { and 'type' property
/// </summary>
/// <param name="writer">JSON writer</param>
private void writeStartObject(JsonTextWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("type");
writer.WriteValue(GetTypeString(this.Tag));
}
/// <summary>
/// Returns symbol name for the given schema type
/// </summary>
/// <param name="type">schema type</param>
/// <returns>symbol name</returns>
public static string GetTypeString(Type type)
{
if (type != Type.Enumeration) return type.ToString().ToLower();
return "enum";
}
/// <summary>
/// Default implementation for writing schema properties in JSON format
/// </summary>
/// <param name="writer">JSON writer</param>
/// <param name="names">list of named schemas already written</param>
/// <param name="encspace">enclosing namespace of the schema</param>
protected internal virtual void WriteJsonFields(JsonTextWriter writer, SchemaNames names, string encspace)
{
}
/// <summary>
/// Writes schema object in JSON format
/// </summary>
/// <param name="writer">JSON writer</param>
/// <param name="names">list of named schemas already written</param>
/// <param name="encspace">enclosing namespace of the schema</param>
protected internal virtual void WriteJson(JsonTextWriter writer, SchemaNames names, string encspace)
{
writeStartObject(writer);
WriteJsonFields(writer, names, encspace);
if (null != this.Props) Props.WriteJson(writer);
writer.WriteEndObject();
}
/// <summary>
/// Returns the schema's custom property value given the property name
/// </summary>
/// <param name="key">custom property name</param>
/// <returns>custom property value</returns>
public string GetProperty(string key)
{
if (null == this.Props) return null;
string v;
return (this.Props.TryGetValue(key, out v)) ? v : null;
}
/// <summary>
/// Hash code function
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return Tag.GetHashCode() + getHashCode(Props);
}
/// <summary>
/// Returns true if and only if data written using writerSchema can be read using the current schema
/// according to the Avro resolution rules.
/// </summary>
/// <param name="writerSchema">The writer's schema to match against.</param>
/// <returns>True if and only if the current schema matches the writer's.</returns>
public virtual bool CanRead(Schema writerSchema) { return Tag == writerSchema.Tag; }
/// <summary>
/// Compares two objects, null is equal to null
/// </summary>
/// <param name="o1">first object</param>
/// <param name="o2">second object</param>
/// <returns>true if two objects are equal, false otherwise</returns>
protected static bool areEqual(object o1, object o2)
{
return o1 == null ? o2 == null : o1.Equals(o2);
}
/// <summary>
/// Hash code helper function
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
protected static int getHashCode(object obj)
{
return obj == null ? 0 : obj.GetHashCode();
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, all rights reserved
//
// File: GlyphsSerializer.cs
//
//------------------------------------------------------------------------------
using System;
using System.Windows.Threading;
using System.Diagnostics;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using MS.Internal;
using MS.Win32;
using Microsoft.Win32.SafeHandles;
using System.Windows;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Security.Permissions;
using MS.Internal.PresentationCore;
namespace System.Windows.Media
{
/// <summary>
///
/// </summary>
[FriendAccessAllowed] // used by System.Printing.dll
internal class GlyphsSerializer
{
#region public methods
/// <summary>
///
/// </summary>
/// <param name="glyphRun"></param>
public GlyphsSerializer(GlyphRun glyphRun)
{
if (glyphRun == null)
{
throw new ArgumentNullException("glyphRun");
}
_glyphTypeface = glyphRun.GlyphTypeface;
_milToEm = EmScaleFactor / glyphRun.FontRenderingEmSize;
_sideways = glyphRun.IsSideways;
_characters = glyphRun.Characters;
_caretStops = glyphRun.CaretStops;
// the first value in the cluster map can be non-zero, in which case it's applied as an offset to all
// subsequent entries in the cluster map
_clusters = glyphRun.ClusterMap;
if (_clusters != null)
_glyphClusterInitialOffset = _clusters[0];
_indices = glyphRun.GlyphIndices;
_advances = glyphRun.AdvanceWidths;
_offsets = glyphRun.GlyphOffsets;
// "100,50,,0;".Length is a capacity estimate for an individual glyph
_glyphStringBuider = new StringBuilder(10);
// string length * _glyphStringBuider.Capacity is an estimate for the whole string
_indicesStringBuider = new StringBuilder(
Math.Max(
(_characters == null ? 0 : _characters.Count),
_indices.Count
)
* _glyphStringBuider.Capacity
);
}
/// <summary>
/// Encode glyph run glyph information into Indices, UnicodeString and CaretStops string.
/// </summary>
public void ComputeContentStrings(out string characters, out string indices, out string caretStops)
{
if (_clusters != null)
{
// the algorithm works by finding (n:m) clusters and appending m glyphs for each cluster
int characterIndex;
int glyphClusterStart = 0;
int charClusterStart = 0;
bool forceNewCluster = true;
for (characterIndex = 0; characterIndex < _clusters.Count; ++characterIndex)
{
if (forceNewCluster)
{
glyphClusterStart = _clusters[characterIndex];
charClusterStart = characterIndex;
forceNewCluster = false;
continue;
}
if (_clusters[characterIndex] != glyphClusterStart)
{
// end of cluster, flush it
Debug.Assert(_clusters[characterIndex] > glyphClusterStart);
AddCluster(glyphClusterStart - _glyphClusterInitialOffset, _clusters[characterIndex] - _glyphClusterInitialOffset, charClusterStart, characterIndex);
// start a new cluster
glyphClusterStart = _clusters[characterIndex];
charClusterStart = characterIndex;
}
// otherwise, we are still within a cluster
}
// flush the last cluster
Debug.Assert(_indices.Count > glyphClusterStart - _glyphClusterInitialOffset);
AddCluster(glyphClusterStart - _glyphClusterInitialOffset, _indices.Count, charClusterStart, characterIndex);
}
else
{
// zero cluster map means 1:1 mapping
Debug.Assert(_characters == null || _characters.Count == 0 || _indices.Count == _characters.Count);
for (int i = 0; i < _indices.Count; ++i)
AddCluster(i, i + 1, i, i + 1);
}
// remove trailing semicolons
RemoveTrailingCharacters(_indicesStringBuider, GlyphSeparator);
indices = _indicesStringBuider.ToString();
if (_characters == null || _characters.Count == 0)
{
characters = string.Empty;
}
else
{
StringBuilder builder = new StringBuilder(_characters.Count);
foreach(char ch in _characters)
{
builder.Append(ch);
}
characters = builder.ToString();
}
caretStops = CreateCaretStopsString();
}
#endregion public methods
#region private methods
private void RemoveTrailingCharacters(StringBuilder sb, char trailingCharacter)
{
int length = sb.Length;
int trailingCharIndex = length - 1;
while (trailingCharIndex >= 0)
{
if (sb[trailingCharIndex] != trailingCharacter)
break;
--trailingCharIndex;
}
sb.Length = trailingCharIndex + 1;
}
private void AddGlyph(int glyph, int sourceCharacter)
{
Debug.Assert(_glyphStringBuider.Length == 0);
// glyph index
ushort fontIndex = _indices[glyph];
ushort glyphIndexFromCmap;
if (sourceCharacter == -1 ||
!_glyphTypeface.CharacterToGlyphMap.TryGetValue(sourceCharacter, out glyphIndexFromCmap) ||
fontIndex != glyphIndexFromCmap)
{
_glyphStringBuider.Append(fontIndex.ToString(CultureInfo.InvariantCulture));
}
_glyphStringBuider.Append(GlyphSubEntrySeparator);
// advance width
int normalizedAdvance = (int)Math.Round(_advances[glyph] * _milToEm);
double fontAdvance = _sideways ? _glyphTypeface.AdvanceHeights[fontIndex] : _glyphTypeface.AdvanceWidths[fontIndex];
if (normalizedAdvance != (int)Math.Round(fontAdvance * EmScaleFactor))
{
_glyphStringBuider.Append(normalizedAdvance.ToString(CultureInfo.InvariantCulture));
}
_glyphStringBuider.Append(GlyphSubEntrySeparator);
// u,v offset
if (_offsets != null)
{
// u offset
int offset = (int)Math.Round(_offsets[glyph].X * _milToEm);
if (offset != 0)
_glyphStringBuider.Append(offset.ToString(CultureInfo.InvariantCulture));
_glyphStringBuider.Append(GlyphSubEntrySeparator);
// v offset
offset = (int)Math.Round(_offsets[glyph].Y * _milToEm);
if (offset != 0)
_glyphStringBuider.Append(offset.ToString(CultureInfo.InvariantCulture));
_glyphStringBuider.Append(GlyphSubEntrySeparator);
}
// flags are not implemented yet
// remove trailing commas
RemoveTrailingCharacters(_glyphStringBuider, GlyphSubEntrySeparator);
_glyphStringBuider.Append(GlyphSeparator);
_indicesStringBuider.Append(_glyphStringBuider.ToString());
// reset for next glyph
_glyphStringBuider.Length = 0;
}
private void AddCluster(int glyphClusterStart, int glyphClusterEnd, int charClusterStart, int charClusterEnd)
{
int charactersInCluster = charClusterEnd - charClusterStart;
int glyphsInCluster = glyphClusterEnd - glyphClusterStart;
// no source character to deduce glyph properties from
int sourceCharacter = -1;
// the format is ... [(CharacterClusterSize[:GlyphClusterSize])] GlyphIndex ...
if (glyphsInCluster != 1)
{
_indicesStringBuider.AppendFormat(CultureInfo.InvariantCulture, "({0}:{1})", charactersInCluster, glyphsInCluster);
}
else
{
if (charactersInCluster != 1)
_indicesStringBuider.AppendFormat(CultureInfo.InvariantCulture, "({0})", charactersInCluster);
else
{
// 1:1 cluster, we can omit (n:m) specification and possibly deduce some
// glyph properties from character
if (_characters != null && _characters.Count != 0)
sourceCharacter = _characters[charClusterStart];
}
}
for (int glyph = glyphClusterStart; glyph < glyphClusterEnd; ++glyph)
{
AddGlyph(glyph, sourceCharacter);
}
}
private string CreateCaretStopsString()
{
if (_caretStops == null)
return String.Empty;
// Since the trailing 0xF (i.e. all true) entries in the caret stop specifications can be omitted,
// we can limit the caret stop list walk until the last nibble that contains 'false'.
int caretStopStringLength = 0;
int lastCaretStop = 0;
for (int i = _caretStops.Count - 1; i >= 0; --i)
{
if (!_caretStops[i])
{
caretStopStringLength = (i + 4) / 4;
// lastCaretStop to consider when building, the rest will correpond to 0xF entries
lastCaretStop = Math.Min(i | 3, _caretStops.Count - 1);
break;
}
}
// All values are set to true, so we don't have to include caret stop string at all.
if (caretStopStringLength == 0)
return String.Empty;
StringBuilder sb = new StringBuilder(caretStopStringLength);
byte mask = 0x8;
byte accumulatedValue = 0;
for (int i = 0; i <= lastCaretStop; ++i)
{
if (_caretStops[i])
accumulatedValue |= mask;
if (mask != 1)
mask >>= 1;
else
{
sb.AppendFormat("{0:x1}", accumulatedValue);
accumulatedValue = 0;
mask = 0x8;
}
}
if (mask != 0x8)
sb.AppendFormat("{0:x1}", accumulatedValue);
Debug.Assert(caretStopStringLength == sb.ToString().Length);
return sb.ToString();
}
#endregion private methods
#region private data
private GlyphTypeface _glyphTypeface;
private IList<char> _characters;
private double _milToEm;
private bool _sideways;
private int _glyphClusterInitialOffset;
private IList<ushort> _clusters;
private IList<ushort> _indices;
private IList<double> _advances;
private IList<Point> _offsets;
private IList<bool> _caretStops;
private StringBuilder _indicesStringBuider;
private StringBuilder _glyphStringBuider;
private const char GlyphSubEntrySeparator = ',';
private const char GlyphSeparator = ';';
private const double EmScaleFactor = 100.0;
#endregion region private data
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// The implementation of the environment of intervals
using System;
using System.Text;
using System.Diagnostics;
using Microsoft.Research.AbstractDomains.Expressions;
using Microsoft.Research.DataStructures;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.AbstractDomains.Numerical
{
[ContractVerification(true)]
sealed public class DisIntervalEnvironment<Variable, Expression>
: IntervalEnvironment_Base<DisIntervalEnvironment<Variable, Expression>, Variable, Expression, DisInterval, Rational>
{
#region Constructors
public DisIntervalEnvironment(ExpressionManager<Variable, Expression> expManager)
: base(expManager, new DisintervalsCheckIfHoldsVisitor(expManager.Decoder))
{
Contract.Requires(expManager != null);
}
private DisIntervalEnvironment(DisIntervalEnvironment<Variable, Expression> original)
: base(original)
{
Contract.Requires(original != null);
}
#endregion
#region TestTrue*
public override DisIntervalEnvironment<Variable, Expression> TestTrueGeqZero(Expression exp)
{
var newConstraints = IntervalInference.InferConstraints_GeqZero(exp, this.ExpressionManager.Decoder, this);
foreach (var pair in newConstraints)
{
this[pair.One] = pair.Two;
}
return this;
}
public override DisIntervalEnvironment<Variable, Expression> TestTrueLessThan(Expression exp1, Expression exp2)
{
return HelperForTestTrueLessThanSignedOrUnsigned(true, exp1, exp2);
}
public override DisIntervalEnvironment<Variable, Expression> TestTrueLessThan_Un(Expression exp1, Expression exp2)
{
return HelperForTestTrueLessThanSignedOrUnsigned(false, exp1, exp2);
}
private DisIntervalEnvironment<Variable, Expression> HelperForTestTrueLessThanSignedOrUnsigned(bool isSigned, Expression exp1, Expression exp2)
{
bool isBottom;
var newConstraints = IntervalInference.InferConstraints_LT(isSigned, exp1, exp2, this.ExpressionManager.Decoder, this, out isBottom);
if (isBottom)
{
return this.Bottom;
}
Assume(newConstraints);
return this;
}
public override DisIntervalEnvironment<Variable, Expression> TestTrueLessEqualThan(Expression exp1, Expression exp2)
{
return HelperForTestTrueLessEqualThanSignedOrUnsigned(true, exp1, exp2);
}
public override DisIntervalEnvironment<Variable, Expression> TestTrueLessEqualThan_Un(Expression exp1, Expression exp2)
{
return HelperForTestTrueLessEqualThanSignedOrUnsigned(false, exp1, exp2);
}
private DisIntervalEnvironment<Variable, Expression> HelperForTestTrueLessEqualThanSignedOrUnsigned(bool isSigned, Expression exp1, Expression exp2)
{
bool isBottom;
var newConstraints = IntervalInference.InferConstraints_Leq(isSigned, exp1, exp2, this.ExpressionManager.Decoder, this, out isBottom);
if (isBottom)
{
return this.Bottom;
}
Assume(newConstraints);
return this;
}
protected override DisIntervalEnvironment<Variable, Expression> TestNotEqualToZero(Expression guard)
{
var val = Eval(guard).Meet(DisInterval.NotZero);
var guardVar = this.ExpressionManager.Decoder.UnderlyingVariable(guard);
this.RefineWith(guardVar, val);
return this;
}
protected override DisIntervalEnvironment<Variable, Expression> TestNotEqualToZero(Variable v)
{
return TestTrueEqualToDisinterval(v, DisInterval.NotZero);
}
protected override DisIntervalEnvironment<Variable, Expression> TestEqualToZero(Variable v)
{
return TestTrueEqualToDisinterval(v, DisInterval.For(0));
}
private DisIntervalEnvironment<Variable, Expression> TestTrueEqualToDisinterval(Variable v, DisInterval dis)
{
Contract.Requires(dis != null);
Contract.Ensures(Contract.Result<DisIntervalEnvironment<Variable, Expression>>() != null);
DisInterval prevVal;
if (this.TryGetValue(v, out prevVal))
{
dis = prevVal.Meet(dis);
}
this[v] = dis;
return this;
}
public override DisIntervalEnvironment<Variable, Expression> TestNotEqual(Expression e1, Expression e2)
{
var v2 = this.Eval(e2);
if (v2.IsSingleton)
{
var notV2 = DisInterval.NotInThisInterval(v2);
var e1Var = this.ExpressionManager.Decoder.UnderlyingVariable(this.ExpressionManager.Decoder.Stripped(e1));
this.RefineWith(e1Var, notV2);
}
bool isBottomLT, isBottomGT;
var constraintsLT = IntervalInference.InferConstraints_LT(true, e1, e2, this.ExpressionManager.Decoder, this, out isBottomLT);
var constraintsGT = IntervalInference.InferConstraints_LT(true, e2, e1, this.ExpressionManager.Decoder, this, out isBottomGT);
if (isBottomLT)
{
// Bottom join Bottom = Bottom
if (isBottomGT)
{
return this.Bottom;
}
this.TestTrueListOfFacts(constraintsGT);
}
else if (isBottomGT)
{
this.TestTrueListOfFacts(constraintsLT);
}
else
{
var join = JoinConstraints(constraintsLT, constraintsGT);
this.TestTrueListOfFacts(join);
}
return this;
}
protected override void AssumeKLessThanRight(DisInterval k, Variable right)
{
DisInterval refined;
if (IntervalInference.TryRefine_KLessThanRight(true, k, right, Rational.For(1), this, out refined))
{
this[right] = refined;
}
}
protected override void AssumeLeftLessThanK(Variable left, DisInterval k)
{
DisInterval refined;
if (IntervalInference.TryRefine_LeftLessThanK(true, left, k, this, out refined))
{
this[left] = refined;
}
}
/// <summary>
/// Assume the constraints <code>newConstraints</code>.
/// It works with side effects
/// </summary>
private void Assume(List<Pair<Variable, DisInterval>> newConstraints)
{
Contract.Requires(newConstraints != null);
foreach (var pair in newConstraints)
{
Contract.Assume(pair.Two != null);
this.RefineWith(pair.One, pair.Two);
}
}
#endregion
#region Bounds
public override DisInterval BoundsFor(Expression exp)
{
return this.Eval(exp);
}
public override DisInterval BoundsFor(Variable v)
{
DisInterval d;
if (this.TryGetValue(v, out d))
{
return d;
}
return DisInterval.UnknownInterval;
}
protected override void AssumeInDisInterval_Internal(Variable x, DisInterval value)
{
if (value.IsTop)
{
return;
}
DisInterval prev, next;
if (this.TryGetValue(x, out prev))
{
next = prev.Meet(value);
}
else
{
next = value;
}
if (next.IsBottom)
{
this.State = AbstractState.Bottom;
}
else
{
this[x] = next;
}
}
#endregion
#region Arithmetics
public override bool IsGreaterEqualThanZero(Rational val)
{
return val >= 0;
}
public override bool IsGreaterThanZero(Rational val)
{
return val > 0;
}
public override bool IsLessThanZero(Rational val)
{
return val < 0;
}
public override bool IsLessEqualThanZero(Rational val)
{
return val <= 0;
}
public override bool IsLessThan(Rational val1, Rational val2)
{
return val1 < val2;
}
public override bool IsLessEqualThan(Rational val1, Rational val2)
{
return val1 <= val2;
}
public override bool IsZero(Rational val)
{
return val.IsZero;
}
public override bool IsNotZero(Rational val)
{
return val.IsNotZero;
}
public override bool IsPlusInfinity(Rational val)
{
return val.IsPlusInfinity;
}
public override bool IsMinusInfinity(Rational val)
{
return val.IsMinusInfinity;
}
public override bool AreEqual(DisInterval left, DisInterval right)
{
return left.IsNormal && right.IsNormal && left.LessEqual(right) && right.LessEqual(left);
}
public override Rational PlusInfinity
{
get
{
return Rational.PlusInfinity;
}
}
public override Rational MinusInfinty
{
get
{
return Rational.MinusInfinity;
}
}
public override bool TryAdd(Rational left, Rational right, out Rational result)
{
if (Rational.TryAdd(left, right, out result))
{
return true;
}
else
{
result = default(Rational);
return false;
}
}
public override FlatAbstractDomain<bool> IsNotZero(DisInterval intv)
{
Contract.Assume(intv != null); // F: just lazy
if (intv.IsSingleton && intv.LowerBound.IsZero)
{
return CheckOutcome.False;
}
if (intv.Meet(this.IntervalZero).IsBottom)
{
return CheckOutcome.True;
}
return CheckOutcome.Top;
}
public override bool IsMaxInt32(DisInterval intv)
{
return intv.IsSingleton && intv.LowerBound.IsInteger && ((Int32)(intv.LowerBound.NextInt32)) == Int32.MaxValue;
}
public override bool IsMinInt32(DisInterval intv)
{
return intv.IsSingleton && intv.LowerBound.IsInteger && ((Int32)(intv.LowerBound.NextInt32)) == Int32.MinValue;
}
public override DisInterval IntervalUnknown
{
get
{
return DisInterval.UnknownInterval;
}
}
public override DisInterval IntervalZero
{
get
{
return DisInterval.For(0);
}
}
public override DisInterval IntervalOne
{
get
{
return DisInterval.For(1);
}
}
public override DisInterval Interval_Positive
{
get { return DisInterval.For(Interval.PositiveInterval); }
}
public override DisInterval Interval_StrictlyPositive
{
get { return this.IntervalRightOpen(Rational.For(1)); }
}
public override DisInterval IntervalGreaterEqualThanMinusOne
{
get { return DisInterval.For(Interval.For(-1, Rational.PlusInfinity)); }
}
public override DisInterval IntervalSingleton(Rational val)
{
return DisInterval.For(val);
}
public override DisInterval IntervalRightOpen(Rational inf)
{
return DisInterval.For(inf, Rational.PlusInfinity);
}
public override DisInterval IntervalLeftOpen(Rational sup)
{
return DisInterval.For(Rational.MinusInfinity, sup);
}
public override DisInterval Interval_Add(DisInterval left, DisInterval right)
{
return left + right;
}
public override DisInterval Interval_Div(DisInterval left, DisInterval right)
{
return left / right;
}
public override DisInterval Interval_Sub(DisInterval left, DisInterval right)
{
return left - right;
}
public override DisInterval Interval_Mul(DisInterval left, DisInterval right)
{
return left * right;
}
public override DisInterval Interval_UnaryMinus(DisInterval left)
{
return -left;
}
public override DisInterval Interval_Not(DisInterval left)
{
if (!left.IsNormal)
{
return left;
}
// !(!0) is 0
if (left.IsNotZero)
{
return DisInterval.For(0);
}
// !(0) is !=0
if (left.IsZero)
{
return DisInterval.NotZero;
}
// !([0, +oo]) is [-oo, -1]
if (left.IsPositiveOrZero)
{
return DisInterval.Negative;
}
return left;
}
public override DisInterval Interval_Rem(DisInterval left, DisInterval right)
{
return left % right;
}
public override DisInterval Interval_BitwiseAnd(DisInterval left, DisInterval right)
{
return left & right;
}
public override DisInterval Interval_BitwiseXor(DisInterval left, DisInterval right)
{
return left ^ right;
}
public override DisInterval Interval_BitwiseOr(DisInterval left, DisInterval right)
{
return left | right;
}
public override DisInterval Interval_ShiftLeft(DisInterval left, DisInterval right)
{
return DisInterval.ShiftLeft(left, right);
}
public override DisInterval Interval_ShiftRight(DisInterval left, DisInterval right)
{
return DisInterval.ShiftRight(left, right);
}
protected override DisInterval ApplyConversion(ExpressionOperator conversionType, DisInterval val)
{
return val.Map(intv => Interval.ApplyConversion(conversionType, intv));
}
#endregion
#region For*
public override DisInterval For(byte v)
{
return DisInterval.For(v);
}
public override DisInterval For(double d)
{
return DisInterval.For(d);
}
public override DisInterval For(short v)
{
return DisInterval.For(v);
}
public override DisInterval For(int v)
{
return DisInterval.For(v);
}
public override DisInterval For(long v)
{
return DisInterval.For(v);
}
public override DisInterval For(sbyte s)
{
return DisInterval.For(s);
}
public override DisInterval For(ushort u)
{
return DisInterval.For(u);
}
public override DisInterval For(uint u)
{
return DisInterval.For(u);
}
public override DisInterval For(Rational r)
{
return DisInterval.For(r);
}
public override DisInterval For(Rational inf, Rational sup)
{
return DisInterval.For(inf, sup);
}
#endregion
#region Overridden
public override List<Pair<Variable, Int32>> IntConstants
{
get
{
if (this.IsBottom || this.IsTop)
{
return new List<Pair<Variable, Int32>>();
}
var result = new List<Pair<Variable, Int32>>();
foreach (var pair in this.Elements)
{
Contract.Assume(pair.Value != null);
if (pair.Value.IsInt32 && pair.Value.IsSingleton)
{
result.Add(pair.Key, (Int32)pair.Value.LowerBound);
}
}
return result;
}
}
protected override T To<T>(Rational n, IFactory<T> factory)
{
return factory.Constant(n);
}
protected override DisIntervalEnvironment<Variable, Expression> Factory()
{
return new DisIntervalEnvironment<Variable, Expression>(this.ExpressionManager);
}
protected override DisIntervalEnvironment<Variable, Expression> DuplicateMe()
{
return new DisIntervalEnvironment<Variable, Expression>(this);
}
protected override DisIntervalEnvironment<Variable, Expression> NewInstance(
ExpressionManager<Variable, Expression> expManager)
{
return new DisIntervalEnvironment<Variable, Expression>(this.ExpressionManager);
}
protected override DisInterval ConvertInterval(Interval intv)
{
return DisInterval.For(intv);
}
#endregion
#region Specialized CheckIfHolds Visitor
private class DisintervalsCheckIfHoldsVisitor
: IntervalsCheckIfHoldsVisitor
{
public DisintervalsCheckIfHoldsVisitor(IExpressionDecoder<Variable, Expression> decoder)
: base(decoder)
{
Contract.Requires(decoder != null);
}
public override FlatAbstractDomain<bool> VisitNotEqual(Expression left, Expression right, Expression original, FlatAbstractDomain<bool> data)
{
// Special case for the special semantics of NaN
if (left.Equals(right) && !this.Decoder.IsNaN(left) && !this.Decoder.IsNaN(right))
{
return CheckOutcome.False;
}
var direct = base.VisitNotEqual(left, right, original, data);
if (direct.IsNormal())
{
return direct;
}
var leftDis = Domain.Eval(left);
var rightDis = Domain.Eval(right);
if (leftDis.Meet(rightDis).IsBottom)
{
return CheckOutcome.True;
}
return CheckOutcome.Top;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class Read_char_int_int : PortsTest
{
//The number of random bytes to receive for read method testing
private const int numRndBytesToRead = 8;
//The number of random bytes to receive for large input buffer testing
private const int largeNumRndCharsToRead = 2048;
//When we test Read and do not care about actually reading anything we must still
//create an byte array to pass into the method the following is the size of the
//byte array used in this situation
private const int defaultCharArraySize = 1;
private const int defaultCharOffset = 0;
private const int defaultCharCount = 1;
//The maximum buffer size when an exception occurs
private const int maxBufferSizeForException = 255;
//The maximum buffer size when an exception is not expected
private const int maxBufferSize = 8;
public enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void Buffer_Null()
{
VerifyReadException(null, 0, 1, typeof(ArgumentNullException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEG1()
{
VerifyReadException(new char[defaultCharArraySize], -1, defaultCharCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEGRND()
{
Random rndGen = new Random(-55);
VerifyReadException(new char[defaultCharArraySize], rndGen.Next(int.MinValue, 0), defaultCharCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_MinInt()
{
VerifyReadException(new char[defaultCharArraySize], int.MinValue, defaultCharCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEG1()
{
VerifyReadException(new char[defaultCharArraySize], defaultCharOffset, -1, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEGRND()
{
Random rndGen = new Random(-55);
VerifyReadException(new char[defaultCharArraySize], defaultCharOffset, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_MinInt()
{
VerifyReadException(new char[defaultCharArraySize], defaultCharOffset, int.MinValue, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OffsetCount_EQ_Length_Plus_1()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(0, bufferLength);
int count = bufferLength + 1 - offset;
Type expectedException = typeof(ArgumentException);
VerifyReadException(new char[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OffsetCount_GT_Length()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(0, bufferLength);
int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyReadException(new char[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_GT_Length()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(bufferLength, int.MaxValue);
int count = defaultCharCount;
Type expectedException = typeof(ArgumentException);
VerifyReadException(new char[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_GT_Length()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = defaultCharOffset;
int count = rndGen.Next(bufferLength + 1, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyReadException(new char[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void OffsetCount_EQ_Length()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = rndGen.Next(0, bufferLength - 1);
int count = bufferLength - offset;
VerifyRead(new char[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Offset_EQ_Length_Minus_1()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = bufferLength - 1;
int count = 1;
VerifyRead(new char[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Count_EQ_Length()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = 0;
int count = bufferLength;
VerifyRead(new char[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_EQ_Zero()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = 0;
int count = 0;
com.Open();
Assert.Equal(0, com.Read(new char[bufferLength], offset, count));
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ASCIIEncoding()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyRead(new char[bufferLength], offset, count, new ASCIIEncoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF8Encoding()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyRead(new char[bufferLength], offset, count, new UTF8Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF32Encoding()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyRead(new char[bufferLength], offset, count, new UTF32Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ASCIIEncoding_1Char()
{
VerifyRead(new char[1], 0, 1, new ASCIIEncoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF8Encoding_1Char()
{
VerifyRead(new char[1], 0, 1, new UTF8Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF32Encoding_1Char()
{
VerifyRead(new char[1], 0, 1, new UTF32Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void LargeInputBuffer()
{
int bufferLength = largeNumRndCharsToRead;
int offset = 0;
int count = bufferLength;
VerifyRead(new char[bufferLength], offset, count, largeNumRndCharsToRead);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void BytesFollowedByCharsASCII()
{
VerifyBytesFollowedByChars(new ASCIIEncoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void BytesFollowedByCharsUTF8()
{
VerifyBytesFollowedByChars(new UTF8Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void BytesFollowedByCharsUTF32()
{
VerifyBytesFollowedByChars(new UTF32Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedData()
{
int bufferLength = 32 + 8;
int offset = 3;
int count = 32;
VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedData()
{
int bufferLength = 8;
int offset = 3;
int count = 3;
VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedAndNonBufferedData()
{
int bufferLength = 64 + 8;
int offset = 3;
int count = 64;
VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedAndNonBufferedData()
{
int bufferLength = 8;
int offset = 3;
int count = 3;
VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void GreedyRead()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.Surrogates);
byte[] byteXmitBuffer = new byte[1024];
char utf32Char = (char)8169;
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
int numCharsRead;
Debug.WriteLine(
"Verifying that Read(char[], int, int) will read everything from internal buffer and drivers buffer");
for (int i = 0; i < byteXmitBuffer.Length; i++)
{
byteXmitBuffer[i] = (byte)rndGen.Next(0, 256);
}
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
TCSupport.SetHighSpeed(com1, com2);
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
Assert.Equal(1, com1.BytesToRead);
com1.Encoding = Encoding.UTF32;
com2.Encoding = Encoding.UTF32;
com2.Write(utf32CharBytes, 1, 3);
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
int numBytes = Encoding.UTF32.GetByteCount(charXmitBuffer);
byte[] byteBuffer = Encoding.UTF32.GetBytes(charXmitBuffer);
var expectedChars = new char[1 + Encoding.UTF32.GetCharCount(byteBuffer)];
expectedChars[0] = utf32Char;
Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1);
var charRcvBuffer = new char[(int)(expectedChars.Length * 1.5)];
TCSupport.WaitForReadBufferToLoad(com1, 4 + numBytes);
if (expectedChars.Length != (numCharsRead = com1.Read(charRcvBuffer, 0, charRcvBuffer.Length)))
{
Fail("Err_6481sfadw Expected read to read {0} chars actually read {1}", expectedChars.Length,
numCharsRead);
}
Assert.Equal(expectedChars, charRcvBuffer.Take(expectedChars.Length).ToArray());
Assert.Equal(0, com1.BytesToRead);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_DataReceivedBeforeTimeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None);
char[] charRcvBuffer = new char[charXmitBuffer.Length];
ASyncRead asyncRead = new ASyncRead(com1, charRcvBuffer, 0, charRcvBuffer.Length);
var asyncReadTask = new Task(asyncRead.Read);
Debug.WriteLine(
"Verifying that Read(char[], int, int) will read characters that have been received after the call to Read was made");
com1.Encoding = Encoding.UTF8;
com2.Encoding = Encoding.UTF8;
com1.ReadTimeout = 20000; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
asyncReadTask.Start();
asyncRead.ReadStartedEvent.WaitOne();
// The WaitOne only tells us that the thread has started to execute code in the method
Thread.Sleep(2000); // We need to wait to guarantee that we are executing code in SerialPort
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
asyncRead.ReadCompletedEvent.WaitOne();
Assert.Null(asyncRead.Exception);
if (asyncRead.Result < 1)
{
Fail("Err_0158ahei Expected Read to read at least one character {0}", asyncRead.Result);
}
else
{
int receivedLength = asyncRead.Result;
while (receivedLength < charRcvBuffer.Length)
{
receivedLength += com1.Read(charRcvBuffer, receivedLength, charRcvBuffer.Length - receivedLength);
}
Assert.Equal(charXmitBuffer.Length, receivedLength);
Assert.Equal(charXmitBuffer, charRcvBuffer);
}
TCSupport.WaitForTaskCompletion(asyncReadTask);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_ResizeBuffer()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(1023, TCSupport.CharacterOptions.ASCII);
int readResult;
Debug.WriteLine("Verifying that Read(char[], int, int) will compact data in the buffer");
com1.Encoding = Encoding.ASCII;
com2.Encoding = Encoding.ASCII;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
//[] Fill the buffer up then read in all but one of the chars
var expectedChars = new char[charXmitBuffer.Length - 1];
var charRcvBuffer = new char[charXmitBuffer.Length - 1];
Array.Copy(charXmitBuffer, 0, expectedChars, 0, charXmitBuffer.Length - 1);
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
TCSupport.WaitForPredicate(() => com1.BytesToRead == charXmitBuffer.Length, 2000,
"Err_29829haie Expected to received {0} bytes actual={1}", charXmitBuffer.Length, com1.BytesToRead);
if (charXmitBuffer.Length - 1 != (readResult = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1)))
{
Fail("Err_55084aheid Expected to read {0} chars actual {1}", charXmitBuffer.Length - 1,
readResult);
}
TCSupport.VerifyArray(expectedChars, charRcvBuffer);
//[] Write 16 more cahrs and read in 16 chars
expectedChars = new char[16];
charRcvBuffer = new char[16];
expectedChars[0] = charXmitBuffer[charXmitBuffer.Length - 1];
Array.Copy(charXmitBuffer, 0, expectedChars, 1, 15);
com2.Write(charXmitBuffer, 0, 16);
TCSupport.WaitForPredicate(() => com1.BytesToRead == 17, 2000,
"Err_0516848aied Expected to received {0} bytes actual={1}", 17, com1.BytesToRead);
if (16 != (readResult = com1.Read(charRcvBuffer, 0, 16)))
{
Fail("Err_650848ahide Expected to read {0} chars actual {1}", 16, readResult);
}
Assert.Equal(expectedChars, charRcvBuffer);
//[] Write more chars and read in all of the chars
expectedChars = new char[charXmitBuffer.Length + 1];
charRcvBuffer = new char[charXmitBuffer.Length + 1];
expectedChars[0] = charXmitBuffer[15];
Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length);
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
TCSupport.WaitForPredicate(() => com1.BytesToRead == charXmitBuffer.Length + 1, 2000,
"Err_41515684 Expected to received {0} bytes actual={1}", charXmitBuffer.Length + 2, com1.BytesToRead);
if (charXmitBuffer.Length + 1 != (readResult = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length + 1)))
{
Fail("Err_460574ajied Expected to read {0} chars actual {1}", charXmitBuffer.Length + 1, readResult);
}
Assert.Equal(expectedChars, charRcvBuffer);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_Timeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None);
byte[] byteXmitBuffer = new UTF32Encoding().GetBytes(charXmitBuffer);
char[] charRcvBuffer = new char[charXmitBuffer.Length];
int result;
Debug.WriteLine(
"Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown");
com1.Encoding = new UTF32Encoding();
com2.Encoding = new UTF32Encoding();
com1.ReadTimeout = 500; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
//Write the first 3 bytes of a character
com2.Write(byteXmitBuffer, 0, 3);
try
{
com1.Read(charXmitBuffer, 0, charXmitBuffer.Length);
Fail("Err_29299aize Expected ReadTo to throw TimeoutException");
}
catch (TimeoutException)
{
} //Expected
Assert.Equal(3, com1.BytesToRead);
com2.Write(byteXmitBuffer, 3, byteXmitBuffer.Length - 3);
// retValue &= TCSupport.WaitForPredicate(delegate() {return com1.BytesToRead == byteXmitBuffer.Length; },
// 5000, "Err_91818aheid Expected BytesToRead={0} actual={1}", byteXmitBuffer.Length, com1.BytesToRead);
TCSupport.WaitForExpected(() => com1.BytesToRead, byteXmitBuffer.Length,
5000, "Err_91818aheid BytesToRead");
result = com1.Read(charRcvBuffer, 0, charRcvBuffer.Length);
Assert.Equal(charXmitBuffer.Length, result);
Assert.Equal(charXmitBuffer, charRcvBuffer);
VerifyBytesReadOnCom1FromCom2(com1, com2, byteXmitBuffer, charXmitBuffer, charRcvBuffer, 0,
charRcvBuffer.Length);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_Partial()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char utf32Char = (char)0x254b; //Box drawing char
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
char[] charRcvBuffer = new char[3];
int result;
Debug.WriteLine("Verifying that Read(char[], int, int) works when reading partial characters");
com1.Encoding = new UTF32Encoding();
com2.Encoding = new UTF32Encoding();
com1.ReadTimeout = 500;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
//Write the first 3 bytes of a character
com2.Write(utf32CharBytes, 0, 4);
com2.Write(utf32CharBytes, 0, 3);
TCSupport.WaitForExpected(() => com1.BytesToRead, 7,
5000, "Err_018158ajid BytesToRead");
result = com1.Read(charRcvBuffer, 0, charRcvBuffer.Length);
Assert.Equal(1, result);
com2.Write(utf32CharBytes, 3, 1);
result = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1);
Assert.Equal(1, result);
Assert.Equal(utf32Char, charRcvBuffer[0]);
Assert.Equal(utf32Char, charRcvBuffer[1]);
VerifyBytesReadOnCom1FromCom2(com1, com2, utf32CharBytes, new[] { utf32Char }, charRcvBuffer, 0,
charRcvBuffer.Length);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_SurrogateBoundary()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = new char[32];
int result;
Debug.WriteLine("Verifying that Read(char[], int, int) works with reading surrogate characters");
TCSupport.GetRandomChars(charXmitBuffer, 0, charXmitBuffer.Length - 2, TCSupport.CharacterOptions.Surrogates);
charXmitBuffer[charXmitBuffer.Length - 2] = TCSupport.GenerateRandomHighSurrogate();
charXmitBuffer[charXmitBuffer.Length - 1] = TCSupport.GenerateRandomLowSurrogate();
com1.Encoding = Encoding.Unicode;
com2.Encoding = Encoding.Unicode;
com1.ReadTimeout = 500;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
//[] First lets try with buffer size that is larger then what we are asking for
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
TCSupport.WaitForExpected(() => com1.BytesToRead, charXmitBuffer.Length * 2,
5000, "Err_018158ajid BytesToRead");
var charRcvBuffer = new char[charXmitBuffer.Length];
result = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1);
Assert.Equal(charXmitBuffer.Length - 2, result);
char[] actualChars = new char[charXmitBuffer.Length];
Array.Copy(charRcvBuffer, 0, actualChars, 0, result);
result = com1.Read(actualChars, actualChars.Length - 2, 2);
Assert.Equal(2, result);
Assert.Equal(charXmitBuffer, actualChars);
//[] Next lets try with buffer size that is the same size as what we are asking for
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
TCSupport.WaitForExpected(() => com1.BytesToRead, charXmitBuffer.Length * 2,
5000, "Err_018158ajid BytesToRead");
charRcvBuffer = new char[charXmitBuffer.Length - 1];
result = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1);
Assert.Equal(charXmitBuffer.Length - 2, result);
actualChars = new char[charXmitBuffer.Length];
Array.Copy(charRcvBuffer, 0, actualChars, 0, result);
result = com1.Read(actualChars, actualChars.Length - 2, 2);
Assert.Equal(2, result);
Assert.Equal(charXmitBuffer, actualChars);
}
}
#endregion
#region Verification for Test Cases
private void VerifyReadException(char[] buffer, int offset, int count, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int bufferLength = null == buffer ? 0 : buffer.Length;
Debug.WriteLine("Verifying read method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count);
com.Open();
Assert.Throws(expectedException, () => com.Read(buffer, offset, count));
}
}
private void VerifyRead(char[] buffer, int offset, int count)
{
VerifyRead(buffer, offset, count, new ASCIIEncoding(), numRndBytesToRead, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(char[] buffer, int offset, int count, int numberOfBytesToRead)
{
VerifyRead(buffer, offset, count, new ASCIIEncoding(), numberOfBytesToRead, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(char[] buffer, int offset, int count, int numberOfBytesToRead, ReadDataFromEnum readDataFrom)
{
VerifyRead(buffer, offset, count, new ASCIIEncoding(), numberOfBytesToRead, readDataFrom);
}
private void VerifyRead(char[] buffer, int offset, int count, Encoding encoding)
{
VerifyRead(buffer, offset, count, encoding, numRndBytesToRead, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(char[] buffer, int offset, int count, Encoding encoding, int numberOfBytesToRead,
ReadDataFromEnum readDataFrom)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
char[] charsToWrite;
char[] expectedChars = new char[numberOfBytesToRead];
byte[] bytesToWrite = new byte[numberOfBytesToRead];
if (1 < count)
{
charsToWrite = TCSupport.GetRandomChars(numberOfBytesToRead, TCSupport.CharacterOptions.Surrogates);
}
else
{
charsToWrite = TCSupport.GetRandomChars(numberOfBytesToRead, TCSupport.CharacterOptions.None);
}
//Genrate some random chars in the buffer
for (int i = 0; i < buffer.Length; i++)
{
char randChar = (char)rndGen.Next(0, ushort.MaxValue);
buffer[i] = randChar;
}
TCSupport.SetHighSpeed(com1, com2);
Debug.WriteLine(
"Verifying read method buffer.Length={0}, offset={1}, count={2}, endocing={3} with {4} random chars",
buffer.Length, offset, count, encoding.EncodingName, bytesToWrite.Length);
com1.ReadTimeout = 500;
com1.Encoding = encoding;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
bytesToWrite = com1.Encoding.GetBytes(charsToWrite, 0, charsToWrite.Length);
expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
switch (readDataFrom)
{
case ReadDataFromEnum.NonBuffered:
VerifyReadNonBuffered(com1, com2, bytesToWrite, buffer, offset, count);
break;
case ReadDataFromEnum.Buffered:
VerifyReadBuffered(com1, com2, bytesToWrite, buffer, offset, count);
break;
case ReadDataFromEnum.BufferedAndNonBuffered:
VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite, buffer, offset, count);
break;
default:
throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null);
}
}
}
private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] rcvBuffer, int offset, int count)
{
char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars, rcvBuffer, offset, count);
}
private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] rcvBuffer, int offset, int count)
{
char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
BufferData(com1, com2, bytesToWrite);
PerformReadOnCom1FromCom2(com1, com2, expectedChars, rcvBuffer, offset, count);
}
private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] rcvBuffer, int offset, int count)
{
char[] expectedChars = new char[com1.Encoding.GetCharCount(bytesToWrite, 0, bytesToWrite.Length) * 2];
char[] encodedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
Array.Copy(encodedChars, 0, expectedChars, 0, bytesToWrite.Length);
Array.Copy(encodedChars, 0, expectedChars, encodedChars.Length, encodedChars.Length);
BufferData(com1, com2, bytesToWrite);
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars, rcvBuffer, offset, count);
}
private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
char c = TCSupport.GenerateRandomCharNonSurrogate();
byte[] bytesForSingleChar = com1.Encoding.GetBytes(new char[] { c }, 0, 1);
com2.Write(bytesForSingleChar, 0, bytesForSingleChar.Length); // Write one byte at the begining because we are going to read this to buffer the rest of the data
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer
Assert.Equal(bytesToWrite.Length, com1.BytesToRead);
}
private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, char[] rcvBuffer, int offset, int count)
{
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 500;
//This is pretty lame but we will have to live with if for now becuase we can not
//gaurentee the number of bytes Write will add
Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250);
PerformReadOnCom1FromCom2(com1, com2, expectedChars, rcvBuffer, offset, count);
}
private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars, char[] rcvBuffer, int offset, int count)
{
char[] buffer = new char[expectedChars.Length];
char[] oldRcvBuffer = (char[])rcvBuffer.Clone();
int numBytesWritten = com1.Encoding.GetByteCount(expectedChars);
int totalBytesRead = 0;
int totalCharsRead = 0;
while (true)
{
int charsRead;
try
{
charsRead = com1.Read(rcvBuffer, offset, count);
}
catch (TimeoutException)
{
break;
}
// While there are more characters to be read
int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, offset, charsRead);
totalBytesRead += bytesRead;
if (expectedChars.Length < totalCharsRead + charsRead)
{
//If we have read in more characters than we expect
//1<DEBUG>
Debug.WriteLine("count={0}, charsRead={1} expectedChars.Length={2}, totalCharsRead={3}", count, charsRead, expectedChars.Length, totalCharsRead);
Debug.WriteLine("rcvBuffer");
TCSupport.PrintChars(rcvBuffer);
Debug.WriteLine("\nexpectedChars");
TCSupport.PrintChars(expectedChars);
//1</DEBUG>
Fail("ERROR!!!: We have received more characters then were sent");
}
if (count != charsRead &&
(count < charsRead ||
((expectedChars.Length - totalCharsRead) != charsRead &&
!TCSupport.IsSurrogate(expectedChars[totalCharsRead + charsRead]))))
{
//If we have not read all of the characters that we should have
//1<DEBUG>
Debug.WriteLine("count={0}, charsRead={1} expectedChars.Length={2}, totalCharsRead={3}", count, charsRead, expectedChars.Length, totalCharsRead);
Debug.WriteLine("rcvBuffer");
TCSupport.PrintChars(rcvBuffer);
Debug.WriteLine("\nexpectedChars");
TCSupport.PrintChars(expectedChars);
//1</DEBUG>
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
}
VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, charsRead);
Array.Copy(rcvBuffer, offset, buffer, totalCharsRead, charsRead);
totalCharsRead += charsRead;
Assert.Equal(numBytesWritten - totalBytesRead, com1.BytesToRead);
oldRcvBuffer = (char[])rcvBuffer.Clone();
}
VerifyBuffer(rcvBuffer, oldRcvBuffer, 0, rcvBuffer.Length);
//Compare the chars that were written with the ones we expected to read
for (int i = 0; i < expectedChars.Length; i++)
{
if (expectedChars[i] != buffer[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)buffer[i], i);
}
}
Assert.Equal(0, com1.BytesToRead);
}
private void VerifyBytesFollowedByChars(Encoding encoding)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] xmitCharBuffer = TCSupport.GetRandomChars(numRndBytesToRead, TCSupport.CharacterOptions.Surrogates);
char[] rcvCharBuffer = new char[xmitCharBuffer.Length];
byte[] xmitByteBuffer = new byte[numRndBytesToRead];
byte[] rcvByteBuffer = new byte[xmitByteBuffer.Length];
Random rndGen = new Random(-55);
int numRead;
Debug.WriteLine("Verifying read method does not alter stream of bytes after chars have been read with {0}",
encoding.GetType());
for (int i = 0; i < xmitByteBuffer.Length; i++)
{
xmitByteBuffer[i] = (byte)rndGen.Next(0, 256);
}
com1.Encoding = encoding;
com2.Encoding = encoding;
com1.ReadTimeout = 500;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(xmitCharBuffer, 0, xmitCharBuffer.Length);
com2.Write(xmitByteBuffer, 0, xmitByteBuffer.Length);
Thread.Sleep(
(int)
(((xmitByteBuffer.Length + com2.Encoding.GetByteCount(xmitCharBuffer) * 10.0) / com1.BaudRate) * 1000) +
500);
Thread.Sleep(500);
if (xmitCharBuffer.Length != (numRead = com1.Read(rcvCharBuffer, 0, rcvCharBuffer.Length)))
{
Fail("ERROR!!!: Expected to read {0} chars actually read {1}", xmitCharBuffer.Length, numRead);
}
if (encoding.EncodingName == Encoding.UTF7.EncodingName)
{
//If UTF7Encoding is being used we we might leave a - in the stream
if (com1.BytesToRead == xmitByteBuffer.Length + 1)
{
int byteRead;
if ('-' != (char)(byteRead = com1.ReadByte()))
{
Fail("Err_29282naie Expected '-' to be left in the stream with UTF7Encoding and read {0}", byteRead);
}
}
}
if (xmitByteBuffer.Length != (numRead = com1.Read(rcvByteBuffer, 0, rcvByteBuffer.Length)))
{
Fail("ERROR!!!: Expected to read {0} bytes actually read {1}", xmitByteBuffer.Length, numRead);
}
for (int i = 0; i < xmitByteBuffer.Length; i++)
{
if (xmitByteBuffer[i] != rcvByteBuffer[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)xmitByteBuffer[i], (int)rcvByteBuffer[i], i);
}
}
Assert.Equal(0, com1.BytesToRead);
/*DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG
if(!retValue) {
for(int i=0; i<xmitCharBuffer.Length; ++i) {
Debug.WriteLine("(char){0}, ", (int)xmitCharBuffer[i]);
}
for(int i=0; i<xmitCharBuffer.Length; ++i) {
Debug.WriteLine("{0}, ", (int)xmitByteBuffer[i]);
}
}*/
}
}
private void VerifyBuffer(char[] actualBuffer, char[] expectedBuffer, int offset, int count)
{
//Verify all character before the offset
for (int i = 0; i < offset; i++)
{
if (actualBuffer[i] != expectedBuffer[i])
{
Fail("ERROR!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]);
}
}
//Verify all character after the offset + count
for (int i = offset + count; i < actualBuffer.Length; i++)
{
if (actualBuffer[i] != expectedBuffer[i])
{
Fail("ERROR!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]);
}
}
}
private class ASyncRead
{
private readonly SerialPort _com;
private readonly char[] _buffer;
private readonly int _offset;
private readonly int _count;
private int _result;
private readonly AutoResetEvent _readCompletedEvent;
private readonly AutoResetEvent _readStartedEvent;
private Exception _exception;
public ASyncRead(SerialPort com, char[] buffer, int offset, int count)
{
_com = com;
_buffer = buffer;
_offset = offset;
_count = count;
_result = -1;
_readCompletedEvent = new AutoResetEvent(false);
_readStartedEvent = new AutoResetEvent(false);
_exception = null;
}
public void Read()
{
try
{
_readStartedEvent.Set();
_result = _com.Read(_buffer, _offset, _count);
}
catch (Exception e)
{
_exception = e;
}
finally
{
_readCompletedEvent.Set();
}
}
public AutoResetEvent ReadStartedEvent => _readStartedEvent;
public AutoResetEvent ReadCompletedEvent => _readCompletedEvent;
public int Result => _result;
public Exception Exception => _exception;
}
#endregion
}
}
| |
/*
'===============================================================================
' Generated From - CSharp_dOOdads_BusinessEntity.vbgen
'
' ** IMPORTANT **
' How to Generate your stored procedures:
'
' SQL = SQL_StoredProcs.vbgen
' ACCESS = Access_StoredProcs.vbgen
' ORACLE = Oracle_StoredProcs.vbgen
' FIREBIRD = FirebirdStoredProcs.vbgen
' POSTGRESQL = PostgreSQL_StoredProcs.vbgen
'
' The supporting base class OleDbEntity is in the Architecture directory in "dOOdads".
'
' This object is 'abstract' which means you need to inherit from it to be able
' to instantiate it. This is very easilly done. You can override properties and
' methods in your derived class, this allows you to regenerate this class at any
' time and not worry about overwriting custom code.
'
' NEVER EDIT THIS FILE.
'
' public class YourObject : _YourObject
' {
'
' }
'
'===============================================================================
*/
// Generated by MyGeneration Version # (1.1.3.5)
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Collections.Specialized;
using MyGeneration.dOOdads;
namespace MyGeneration.dOOdads.Tests.Access
{
public abstract class _AggregateTest : OleDbEntity
{
public _AggregateTest()
{
this.QuerySource = "AggregateTest";
this.MappingName = "AggregateTest";
}
//=================================================================
// public Overrides void AddNew()
//=================================================================
//
//=================================================================
public override void AddNew()
{
base.AddNew();
}
public override string GetAutoKeyColumn()
{
return "ID";
}
public override void FlushData()
{
this._whereClause = null;
this._aggregateClause = null;
base.FlushData();
}
//=================================================================
// public Function LoadAll() As Boolean
//=================================================================
// Loads all of the records in the database, and sets the currentRow to the first row
//=================================================================
public bool LoadAll()
{
ListDictionary parameters = null;
return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_AggregateTestLoadAll]", parameters);
}
//=================================================================
// public Overridable Function LoadByPrimaryKey() As Boolean
//=================================================================
// Loads a single row of via the primary key
//=================================================================
public virtual bool LoadByPrimaryKey(int ID)
{
ListDictionary parameters = new ListDictionary();
parameters.Add(Parameters.ID, ID);
return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_AggregateTestLoadByPrimaryKey]", parameters);
}
#region Parameters
protected class Parameters
{
public static OleDbParameter ID
{
get
{
return new OleDbParameter("@ID", OleDbType.Numeric, 0);
}
}
public static OleDbParameter DepartmentID
{
get
{
return new OleDbParameter("@DepartmentID", OleDbType.Numeric, 0);
}
}
public static OleDbParameter FirstName
{
get
{
return new OleDbParameter("@FirstName", OleDbType.VarWChar, 25);
}
}
public static OleDbParameter LastName
{
get
{
return new OleDbParameter("@LastName", OleDbType.VarWChar, 15);
}
}
public static OleDbParameter Age
{
get
{
return new OleDbParameter("@Age", OleDbType.Numeric, 0);
}
}
public static OleDbParameter HireDate
{
get
{
return new OleDbParameter("@HireDate", OleDbType.Date, 0);
}
}
public static OleDbParameter Salary
{
get
{
return new OleDbParameter("@Salary", OleDbType.Double, 0);
}
}
public static OleDbParameter IsActive
{
get
{
return new OleDbParameter("@IsActive", OleDbType.Boolean, 2);
}
}
}
#endregion
#region ColumnNames
public class ColumnNames
{
public const string ID = "ID";
public const string DepartmentID = "DepartmentID";
public const string FirstName = "FirstName";
public const string LastName = "LastName";
public const string Age = "Age";
public const string HireDate = "HireDate";
public const string Salary = "Salary";
public const string IsActive = "IsActive";
static public string ToPropertyName(string columnName)
{
if(ht == null)
{
ht = new Hashtable();
ht[ID] = _AggregateTest.PropertyNames.ID;
ht[DepartmentID] = _AggregateTest.PropertyNames.DepartmentID;
ht[FirstName] = _AggregateTest.PropertyNames.FirstName;
ht[LastName] = _AggregateTest.PropertyNames.LastName;
ht[Age] = _AggregateTest.PropertyNames.Age;
ht[HireDate] = _AggregateTest.PropertyNames.HireDate;
ht[Salary] = _AggregateTest.PropertyNames.Salary;
ht[IsActive] = _AggregateTest.PropertyNames.IsActive;
}
return (string)ht[columnName];
}
static private Hashtable ht = null;
}
#endregion
#region PropertyNames
public class PropertyNames
{
public const string ID = "ID";
public const string DepartmentID = "DepartmentID";
public const string FirstName = "FirstName";
public const string LastName = "LastName";
public const string Age = "Age";
public const string HireDate = "HireDate";
public const string Salary = "Salary";
public const string IsActive = "IsActive";
static public string ToColumnName(string propertyName)
{
if(ht == null)
{
ht = new Hashtable();
ht[ID] = _AggregateTest.ColumnNames.ID;
ht[DepartmentID] = _AggregateTest.ColumnNames.DepartmentID;
ht[FirstName] = _AggregateTest.ColumnNames.FirstName;
ht[LastName] = _AggregateTest.ColumnNames.LastName;
ht[Age] = _AggregateTest.ColumnNames.Age;
ht[HireDate] = _AggregateTest.ColumnNames.HireDate;
ht[Salary] = _AggregateTest.ColumnNames.Salary;
ht[IsActive] = _AggregateTest.ColumnNames.IsActive;
}
return (string)ht[propertyName];
}
static private Hashtable ht = null;
}
#endregion
#region StringPropertyNames
public class StringPropertyNames
{
public const string ID = "s_ID";
public const string DepartmentID = "s_DepartmentID";
public const string FirstName = "s_FirstName";
public const string LastName = "s_LastName";
public const string Age = "s_Age";
public const string HireDate = "s_HireDate";
public const string Salary = "s_Salary";
public const string IsActive = "s_IsActive";
}
#endregion
#region Properties
public virtual int ID
{
get
{
return base.Getint(ColumnNames.ID);
}
set
{
base.Setint(ColumnNames.ID, value);
}
}
public virtual int DepartmentID
{
get
{
return base.Getint(ColumnNames.DepartmentID);
}
set
{
base.Setint(ColumnNames.DepartmentID, value);
}
}
public virtual string FirstName
{
get
{
return base.Getstring(ColumnNames.FirstName);
}
set
{
base.Setstring(ColumnNames.FirstName, value);
}
}
public virtual string LastName
{
get
{
return base.Getstring(ColumnNames.LastName);
}
set
{
base.Setstring(ColumnNames.LastName, value);
}
}
public virtual int Age
{
get
{
return base.Getint(ColumnNames.Age);
}
set
{
base.Setint(ColumnNames.Age, value);
}
}
public virtual DateTime HireDate
{
get
{
return base.GetDateTime(ColumnNames.HireDate);
}
set
{
base.SetDateTime(ColumnNames.HireDate, value);
}
}
public virtual double Salary
{
get
{
return base.Getdouble(ColumnNames.Salary);
}
set
{
base.Setdouble(ColumnNames.Salary, value);
}
}
public virtual bool IsActive
{
get
{
return base.Getbool(ColumnNames.IsActive);
}
set
{
base.Setbool(ColumnNames.IsActive, value);
}
}
#endregion
#region String Properties
public virtual string s_ID
{
get
{
return this.IsColumnNull(ColumnNames.ID) ? string.Empty : base.GetintAsString(ColumnNames.ID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.ID);
else
this.ID = base.SetintAsString(ColumnNames.ID, value);
}
}
public virtual string s_DepartmentID
{
get
{
return this.IsColumnNull(ColumnNames.DepartmentID) ? string.Empty : base.GetintAsString(ColumnNames.DepartmentID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.DepartmentID);
else
this.DepartmentID = base.SetintAsString(ColumnNames.DepartmentID, value);
}
}
public virtual string s_FirstName
{
get
{
return this.IsColumnNull(ColumnNames.FirstName) ? string.Empty : base.GetstringAsString(ColumnNames.FirstName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.FirstName);
else
this.FirstName = base.SetstringAsString(ColumnNames.FirstName, value);
}
}
public virtual string s_LastName
{
get
{
return this.IsColumnNull(ColumnNames.LastName) ? string.Empty : base.GetstringAsString(ColumnNames.LastName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.LastName);
else
this.LastName = base.SetstringAsString(ColumnNames.LastName, value);
}
}
public virtual string s_Age
{
get
{
return this.IsColumnNull(ColumnNames.Age) ? string.Empty : base.GetintAsString(ColumnNames.Age);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Age);
else
this.Age = base.SetintAsString(ColumnNames.Age, value);
}
}
public virtual string s_HireDate
{
get
{
return this.IsColumnNull(ColumnNames.HireDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.HireDate);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.HireDate);
else
this.HireDate = base.SetDateTimeAsString(ColumnNames.HireDate, value);
}
}
public virtual string s_Salary
{
get
{
return this.IsColumnNull(ColumnNames.Salary) ? string.Empty : base.GetdoubleAsString(ColumnNames.Salary);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Salary);
else
this.Salary = base.SetdoubleAsString(ColumnNames.Salary, value);
}
}
public virtual string s_IsActive
{
get
{
return this.IsColumnNull(ColumnNames.IsActive) ? string.Empty : base.GetboolAsString(ColumnNames.IsActive);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.IsActive);
else
this.IsActive = base.SetboolAsString(ColumnNames.IsActive, value);
}
}
#endregion
#region Where Clause
public class WhereClause
{
public WhereClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffWhereParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffWhereParameter(this);
}
return _tearOff;
}
}
#region WhereParameter TearOff's
public class TearOffWhereParameter
{
public TearOffWhereParameter(WhereClause clause)
{
this._clause = clause;
}
public WhereParameter ID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.ID, Parameters.ID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter DepartmentID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.DepartmentID, Parameters.DepartmentID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter FirstName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.FirstName, Parameters.FirstName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter LastName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.LastName, Parameters.LastName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Age
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Age, Parameters.Age);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter HireDate
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.HireDate, Parameters.HireDate);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Salary
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Salary, Parameters.Salary);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter IsActive
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.IsActive, Parameters.IsActive);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
private WhereClause _clause;
}
#endregion
public WhereParameter ID
{
get
{
if(_ID_W == null)
{
_ID_W = TearOff.ID;
}
return _ID_W;
}
}
public WhereParameter DepartmentID
{
get
{
if(_DepartmentID_W == null)
{
_DepartmentID_W = TearOff.DepartmentID;
}
return _DepartmentID_W;
}
}
public WhereParameter FirstName
{
get
{
if(_FirstName_W == null)
{
_FirstName_W = TearOff.FirstName;
}
return _FirstName_W;
}
}
public WhereParameter LastName
{
get
{
if(_LastName_W == null)
{
_LastName_W = TearOff.LastName;
}
return _LastName_W;
}
}
public WhereParameter Age
{
get
{
if(_Age_W == null)
{
_Age_W = TearOff.Age;
}
return _Age_W;
}
}
public WhereParameter HireDate
{
get
{
if(_HireDate_W == null)
{
_HireDate_W = TearOff.HireDate;
}
return _HireDate_W;
}
}
public WhereParameter Salary
{
get
{
if(_Salary_W == null)
{
_Salary_W = TearOff.Salary;
}
return _Salary_W;
}
}
public WhereParameter IsActive
{
get
{
if(_IsActive_W == null)
{
_IsActive_W = TearOff.IsActive;
}
return _IsActive_W;
}
}
private WhereParameter _ID_W = null;
private WhereParameter _DepartmentID_W = null;
private WhereParameter _FirstName_W = null;
private WhereParameter _LastName_W = null;
private WhereParameter _Age_W = null;
private WhereParameter _HireDate_W = null;
private WhereParameter _Salary_W = null;
private WhereParameter _IsActive_W = null;
public void WhereClauseReset()
{
_ID_W = null;
_DepartmentID_W = null;
_FirstName_W = null;
_LastName_W = null;
_Age_W = null;
_HireDate_W = null;
_Salary_W = null;
_IsActive_W = null;
this._entity.Query.FlushWhereParameters();
}
private BusinessEntity _entity;
private TearOffWhereParameter _tearOff;
}
public WhereClause Where
{
get
{
if(_whereClause == null)
{
_whereClause = new WhereClause(this);
}
return _whereClause;
}
}
private WhereClause _whereClause = null;
#endregion
#region Aggregate Clause
public class AggregateClause
{
public AggregateClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffAggregateParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffAggregateParameter(this);
}
return _tearOff;
}
}
#region AggregateParameter TearOff's
public class TearOffAggregateParameter
{
public TearOffAggregateParameter(AggregateClause clause)
{
this._clause = clause;
}
public AggregateParameter ID
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.ID, Parameters.ID);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter DepartmentID
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.DepartmentID, Parameters.DepartmentID);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter FirstName
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.FirstName, Parameters.FirstName);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter LastName
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.LastName, Parameters.LastName);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter Age
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.Age, Parameters.Age);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter HireDate
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.HireDate, Parameters.HireDate);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter Salary
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.Salary, Parameters.Salary);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter IsActive
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.IsActive, Parameters.IsActive);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
private AggregateClause _clause;
}
#endregion
public AggregateParameter ID
{
get
{
if(_ID_W == null)
{
_ID_W = TearOff.ID;
}
return _ID_W;
}
}
public AggregateParameter DepartmentID
{
get
{
if(_DepartmentID_W == null)
{
_DepartmentID_W = TearOff.DepartmentID;
}
return _DepartmentID_W;
}
}
public AggregateParameter FirstName
{
get
{
if(_FirstName_W == null)
{
_FirstName_W = TearOff.FirstName;
}
return _FirstName_W;
}
}
public AggregateParameter LastName
{
get
{
if(_LastName_W == null)
{
_LastName_W = TearOff.LastName;
}
return _LastName_W;
}
}
public AggregateParameter Age
{
get
{
if(_Age_W == null)
{
_Age_W = TearOff.Age;
}
return _Age_W;
}
}
public AggregateParameter HireDate
{
get
{
if(_HireDate_W == null)
{
_HireDate_W = TearOff.HireDate;
}
return _HireDate_W;
}
}
public AggregateParameter Salary
{
get
{
if(_Salary_W == null)
{
_Salary_W = TearOff.Salary;
}
return _Salary_W;
}
}
public AggregateParameter IsActive
{
get
{
if(_IsActive_W == null)
{
_IsActive_W = TearOff.IsActive;
}
return _IsActive_W;
}
}
private AggregateParameter _ID_W = null;
private AggregateParameter _DepartmentID_W = null;
private AggregateParameter _FirstName_W = null;
private AggregateParameter _LastName_W = null;
private AggregateParameter _Age_W = null;
private AggregateParameter _HireDate_W = null;
private AggregateParameter _Salary_W = null;
private AggregateParameter _IsActive_W = null;
public void AggregateClauseReset()
{
_ID_W = null;
_DepartmentID_W = null;
_FirstName_W = null;
_LastName_W = null;
_Age_W = null;
_HireDate_W = null;
_Salary_W = null;
_IsActive_W = null;
this._entity.Query.FlushAggregateParameters();
}
private BusinessEntity _entity;
private TearOffAggregateParameter _tearOff;
}
public AggregateClause Aggregate
{
get
{
if(_aggregateClause == null)
{
_aggregateClause = new AggregateClause(this);
}
return _aggregateClause;
}
}
private AggregateClause _aggregateClause = null;
#endregion
protected override IDbCommand GetInsertCommand()
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_AggregateTestInsert]";
CreateParameters(cmd);
return cmd;
}
protected override IDbCommand GetUpdateCommand()
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_AggregateTestUpdate]";
CreateParameters(cmd);
return cmd;
}
protected override IDbCommand GetDeleteCommand()
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_AggregateTestDelete]";
OleDbParameter p;
p = cmd.Parameters.Add(Parameters.ID);
p.SourceColumn = ColumnNames.ID;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
private IDbCommand CreateParameters(OleDbCommand cmd)
{
OleDbParameter p;
p = cmd.Parameters.Add(Parameters.ID);
p.SourceColumn = ColumnNames.ID;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.DepartmentID);
p.SourceColumn = ColumnNames.DepartmentID;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.FirstName);
p.SourceColumn = ColumnNames.FirstName;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.LastName);
p.SourceColumn = ColumnNames.LastName;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.Age);
p.SourceColumn = ColumnNames.Age;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.HireDate);
p.SourceColumn = ColumnNames.HireDate;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.Salary);
p.SourceColumn = ColumnNames.Salary;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.IsActive);
p.SourceColumn = ColumnNames.IsActive;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="TreeWalker.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: TreeWalker class, allows client to walk custom views of
// UIAutomation tree.
//
// History:
// 02/05/2004 : BrendanM Created
//
//---------------------------------------------------------------------------
using System;
using System.Windows.Automation.Provider;
using MS.Internal.Automation;
namespace System.Windows.Automation
{
/// <summary>
/// TreeWalker - used to walk over a view of the UIAutomation tree
/// </summary>
#if (INTERNAL_COMPILE)
internal sealed class TreeWalker
#else
public sealed class TreeWalker
#endif
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Create a tree walker that can be used to walk a specified
/// view of the UIAutomation tree.
/// </summary>
/// <param name="condition">Condition defining the view - nodes that do not satisfy this condition are skipped over</param>
public TreeWalker(Condition condition)
{
Misc.ValidateArgumentNonNull(condition, "condition");
_condition = condition;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Constants / Readonly Fields
//
//------------------------------------------------------
#region Public Constants and Readonly Fields
/// <summary>
/// Predefined TreeWalker for walking the Raw view of the UIAutomation tree
/// </summary>
public static readonly TreeWalker RawViewWalker = new TreeWalker(Automation.RawViewCondition);
/// <summary>
/// Predefined TreeWalker for walking the Control view of the UIAutomation tree
/// </summary>
public static readonly TreeWalker ControlViewWalker = new TreeWalker(Automation.ControlViewCondition);
/// <summary>
/// Predefined TreeWalker for walking the Content view of the UIAutomation tree
/// </summary>
public static readonly TreeWalker ContentViewWalker = new TreeWalker(Automation.ContentViewCondition);
#endregion Public Constants and Readonly Fields
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Get the parent of the specified element, in the current view
/// </summary>
/// <param name="element">element to get the parent of</param>
/// <returns>The parent of the specified element; can be null if
/// specified element was the root element</returns>
/// <remarks>The view used is determined by the condition passed to
/// the constructor - elements that do not satisfy that condition
/// are skipped over</remarks>
public AutomationElement GetParent(AutomationElement element)
{
Misc.ValidateArgumentNonNull(element, "element");
return element.Navigate(NavigateDirection.Parent, _condition, null);
}
/// <summary>
/// Get the first child of the specified element, in the current view
/// </summary>
/// <param name="element">element to get the first child of</param>
/// <returns>The frst child of the specified element - or null if
/// the specified element has no children</returns>
/// <remarks>The view used is determined by the condition passed to
/// the constructor - elements that do not satisfy that condition
/// are skipped over</remarks>
public AutomationElement GetFirstChild(AutomationElement element)
{
Misc.ValidateArgumentNonNull(element, "element");
return element.Navigate(NavigateDirection.FirstChild, _condition, null);
}
/// <summary>
/// Get the last child of the specified element, in the current view
/// </summary>
/// <param name="element">element to get the last child of</param>
/// <returns>The last child of the specified element - or null if
/// the specified element has no children</returns>
/// <remarks>The view used is determined by the condition passed to
/// the constructor - elements that do not satisfy that condition
/// are skipped over</remarks>
public AutomationElement GetLastChild(AutomationElement element)
{
Misc.ValidateArgumentNonNull(element, "element");
return element.Navigate(NavigateDirection.LastChild, _condition, null);
}
/// <summary>
/// Get the next sibling of the specified element, in the current view
/// </summary>
/// <param name="element">element to get the next sibling of</param>
/// <returns>The next sibling of the specified element - or null if the
/// specified element has no next sibling</returns>
/// <remarks>The view used is determined by the condition passed to
/// the constructor - elements that do not satisfy that condition
/// are skipped over</remarks>
public AutomationElement GetNextSibling(AutomationElement element)
{
Misc.ValidateArgumentNonNull(element, "element");
return element.Navigate(NavigateDirection.NextSibling, _condition, null);
}
/// <summary>
/// Get the previous sibling of the specified element, in the current view
/// </summary>
/// <param name="element">element to get the previous sibling of</param>
/// <returns>The previous sibling of the specified element - or null if the
/// specified element has no previous sibling</returns>
/// <remarks>The view used is determined by the condition passed to
/// the constructor - elements that do not satisfy that condition
/// are skipped over</remarks>
public AutomationElement GetPreviousSibling(AutomationElement element)
{
Misc.ValidateArgumentNonNull(element, "element");
return element.Navigate(NavigateDirection.PreviousSibling, _condition, null);
}
/// <summary>
/// Return the element or the nearest ancestor which is present in
/// the view of the tree used by this treewalker
/// </summary>
/// <param name="element">element to normalize</param>
/// <returns>The element or the nearest ancestor which satisfies the
/// condition used by this TreeWalker</returns>
/// <remarks>
/// This method starts at the specified element and walks up the
/// tree until it finds an element that satisfies the TreeWalker's
/// condition.
///
/// If the passed-in element itself satsifies the condition, it is
/// returned as-is.
///
/// If the process of walking up the tree hits the root node, then
/// the root node is returned, regardless of whether it satisfies
/// the condition or not.
/// </remarks>
public AutomationElement Normalize(AutomationElement element)
{
Misc.ValidateArgumentNonNull(element, "element");
return element.Normalize(_condition, null);
}
/// <summary>
/// Get the parent of the specified element, in the current view,
/// prefetching properties
/// </summary>
/// <param name="element">element to get the parent of</param>
/// <param name="request">CacheRequest specifying information to be prefetched</param>
/// <returns>The parent of the specified element; can be null if
/// specified element was the root element</returns>
/// <remarks>The view used is determined by the condition passed to
/// the constructor - elements that do not satisfy that condition
/// are skipped over</remarks>
public AutomationElement GetParent(AutomationElement element, CacheRequest request)
{
Misc.ValidateArgumentNonNull(element, "element");
Misc.ValidateArgumentNonNull(request, "request");
return element.Navigate(NavigateDirection.Parent, _condition, request);
}
/// <summary>
/// Get the first child of the specified element, in the current view,
/// prefetching properties
/// </summary>
/// <param name="element">element to get the first child of</param>
/// <param name="request">CacheRequest specifying information to be prefetched</param>
/// <returns>The frst child of the specified element - or null if
/// the specified element has no children</returns>
/// <remarks>The view used is determined by the condition passed to
/// the constructor - elements that do not satisfy that condition
/// are skipped over</remarks>
public AutomationElement GetFirstChild(AutomationElement element, CacheRequest request)
{
Misc.ValidateArgumentNonNull(element, "element");
Misc.ValidateArgumentNonNull(request, "request");
return element.Navigate(NavigateDirection.FirstChild, _condition, request);
}
/// <summary>
/// Get the last child of the specified element, in the current view,
/// prefetching properties
/// </summary>
/// <param name="element">element to get the last child of</param>
/// <param name="request">CacheRequest specifying information to be prefetched</param>
/// <returns>The last child of the specified element - or null if
/// the specified element has no children</returns>
/// <remarks>The view used is determined by the condition passed to
/// the constructor - elements that do not satisfy that condition
/// are skipped over</remarks>
public AutomationElement GetLastChild(AutomationElement element, CacheRequest request)
{
Misc.ValidateArgumentNonNull(element, "element");
Misc.ValidateArgumentNonNull(request, "request");
return element.Navigate(NavigateDirection.LastChild, _condition, request);
}
/// <summary>
/// Get the next sibling of the specified element, in the current view,
/// prefetching properties
/// </summary>
/// <param name="element">element to get the next sibling of</param>
/// <param name="request">CacheRequest specifying information to be prefetched</param>
/// <returns>The next sibling of the specified element - or null if the
/// specified element has no next sibling</returns>
/// <remarks>The view used is determined by the condition passed to
/// the constructor - elements that do not satisfy that condition
/// are skipped over</remarks>
public AutomationElement GetNextSibling(AutomationElement element, CacheRequest request)
{
Misc.ValidateArgumentNonNull(element, "element");
Misc.ValidateArgumentNonNull(request, "request");
return element.Navigate(NavigateDirection.NextSibling, _condition, request);
}
/// <summary>
/// Get the previous sibling of the specified element, in the current view,
/// prefetching properties
/// </summary>
/// <param name="element">element to get the previous sibling of</param>
/// <param name="request">CacheRequest specifying information to be prefetched</param>
/// <returns>The previous sibling of the specified element - or null if the
/// specified element has no previous sibling</returns>
/// <remarks>The view used is determined by the condition passed to
/// the constructor - elements that do not satisfy that condition
/// are skipped over</remarks>
public AutomationElement GetPreviousSibling(AutomationElement element, CacheRequest request)
{
Misc.ValidateArgumentNonNull(element, "element");
Misc.ValidateArgumentNonNull(request, "request");
return element.Navigate(NavigateDirection.PreviousSibling, _condition, request);
}
/// <summary>
/// Return the element or the nearest ancestor which is present in
/// the view of the tree used by this treewalker, prefetching properties
/// for the returned node
/// </summary>
/// <param name="element">element to normalize</param>
/// <param name="request">CacheRequest specifying information to be prefetched</param>
/// <returns>The element or the nearest ancestor which satisfies the
/// condition used by this TreeWalker</returns>
/// <remarks>
/// This method starts at the specified element and walks up the
/// tree until it finds an element that satisfies the TreeWalker's
/// condition.
///
/// If the passed-in element itself satsifies the condition, it is
/// returned as-is.
///
/// If the process of walking up the tree hits the root node, then
/// the root node is returned, regardless of whether it satisfies
/// the condition or not.
/// </remarks>
public AutomationElement Normalize(AutomationElement element, CacheRequest request)
{
Misc.ValidateArgumentNonNull(element, "element");
Misc.ValidateArgumentNonNull(request, "request");
return element.Normalize(_condition, request);
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// Returns the condition used by this TreeWalker. The TreeWalker
/// skips over nodes that do not satisfy the condition.
/// </summary>
public Condition Condition
{
get
{
return _condition;
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private Condition _condition;
#endregion Private Fields
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.Generic;
using System.ServiceModel.Description;
using System.Net.Security;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.ComponentModel;
using System.Xml;
public class WindowsStreamSecurityBindingElement : StreamUpgradeBindingElement,
ITransportTokenAssertionProvider,
IPolicyExportExtension
{
ProtectionLevel protectionLevel;
public WindowsStreamSecurityBindingElement()
: base()
{
this.protectionLevel = ConnectionOrientedTransportDefaults.ProtectionLevel;
}
protected WindowsStreamSecurityBindingElement(WindowsStreamSecurityBindingElement elementToBeCloned)
: base(elementToBeCloned)
{
this.protectionLevel = elementToBeCloned.protectionLevel;
}
[DefaultValue(ConnectionOrientedTransportDefaults.ProtectionLevel)]
public ProtectionLevel ProtectionLevel
{
get
{
return this.protectionLevel;
}
set
{
ProtectionLevelHelper.Validate(value);
this.protectionLevel = value;
}
}
public override BindingElement Clone()
{
return new WindowsStreamSecurityBindingElement(this);
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
#pragma warning suppress 56506 // [....], BindingContext.BindingParameters cannot be null
context.BindingParameters.Add(this);
return context.BuildInnerChannelFactory<TChannel>();
}
public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
#pragma warning suppress 56506 // [....], BindingContext.BindingParameters cannot be null
context.BindingParameters.Add(this);
return context.CanBuildInnerChannelFactory<TChannel>();
}
public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
#pragma warning suppress 56506 // [....], BindingContext.BindingParameters cannot be null
context.BindingParameters.Add(this);
return context.BuildInnerChannelListener<TChannel>();
}
public override bool CanBuildChannelListener<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
#pragma warning suppress 56506 // [....], BindingContext.BindingParameters cannot be null
context.BindingParameters.Add(this);
return context.CanBuildInnerChannelListener<TChannel>();
}
public override StreamUpgradeProvider BuildClientStreamUpgradeProvider(BindingContext context)
{
return new WindowsStreamSecurityUpgradeProvider(this, context, true);
}
public override StreamUpgradeProvider BuildServerStreamUpgradeProvider(BindingContext context)
{
return new WindowsStreamSecurityUpgradeProvider(this, context, false);
}
public override T GetProperty<T>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)new SecurityCapabilities(true, true, true, protectionLevel, protectionLevel);
}
else if (typeof(T) == typeof(IdentityVerifier))
{
return (T)(object)IdentityVerifier.CreateDefault();
}
else
{
return context.GetInnerProperty<T>();
}
}
internal static void ImportPolicy(MetadataImporter importer, PolicyConversionContext policyContext)
{
XmlElement assertion = PolicyConversionContext.FindAssertion(policyContext.GetBindingAssertions(),
TransportPolicyConstants.WindowsTransportSecurityName, TransportPolicyConstants.DotNetFramingNamespace, true);
if (assertion != null)
{
WindowsStreamSecurityBindingElement windowsBindingElement
= new WindowsStreamSecurityBindingElement();
XmlReader reader = new XmlNodeReader(assertion);
reader.ReadStartElement();
string protectionLevelString = null;
if (reader.IsStartElement(
TransportPolicyConstants.ProtectionLevelName,
TransportPolicyConstants.DotNetFramingNamespace) && !reader.IsEmptyElement)
{
protectionLevelString = reader.ReadElementContentAsString();
}
if (string.IsNullOrEmpty(protectionLevelString))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(
SR.GetString(SR.ExpectedElementMissing, TransportPolicyConstants.ProtectionLevelName, TransportPolicyConstants.DotNetFramingNamespace)));
}
windowsBindingElement.ProtectionLevel = (ProtectionLevel)Enum.Parse(typeof(ProtectionLevel), protectionLevelString);
policyContext.BindingElements.Add(windowsBindingElement);
}
}
#region ITransportTokenAssertionProvider Members
public XmlElement GetTransportTokenAssertion()
{
XmlDocument document = new XmlDocument();
XmlElement assertion =
document.CreateElement(TransportPolicyConstants.DotNetFramingPrefix,
TransportPolicyConstants.WindowsTransportSecurityName,
TransportPolicyConstants.DotNetFramingNamespace);
XmlElement protectionLevelElement = document.CreateElement(TransportPolicyConstants.DotNetFramingPrefix,
TransportPolicyConstants.ProtectionLevelName, TransportPolicyConstants.DotNetFramingNamespace);
protectionLevelElement.AppendChild(document.CreateTextNode(this.ProtectionLevel.ToString()));
assertion.AppendChild(protectionLevelElement);
return assertion;
}
#endregion
void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
{
if (exporter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter");
}
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
SecurityBindingElement.ExportPolicyForTransportTokenAssertionProviders(exporter, context);
}
internal override bool IsMatch(BindingElement b)
{
if (b == null)
{
return false;
}
WindowsStreamSecurityBindingElement security = b as WindowsStreamSecurityBindingElement;
if (security == null)
{
return false;
}
if (this.protectionLevel != security.protectionLevel)
{
return false;
}
return true;
}
}
}
| |
// CodeContracts
//
// 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.
//-----------------------------------------------------------------------------
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//-----------------------------------------------------------------------------
using System;
using System.IO;
using System.Text;
namespace Microsoft.Cci.Pdb
{
internal class BitAccess
{
internal BitAccess(byte[] buffer)
{
this.buffer = buffer;
offset = 0;
}
internal BitAccess(int capacity)
{
this.buffer = new byte[capacity];
}
internal byte[] Buffer
{
get { return buffer; }
}
private byte[] buffer;
internal void FillBuffer(Stream stream, int capacity)
{
MinCapacity(capacity);
stream.Read(buffer, 0, capacity);
offset = 0;
}
internal void Append(Stream stream, int count)
{
int newCapacity = offset + count;
if (buffer.Length < newCapacity)
{
byte[] newBuffer = new byte[newCapacity];
Array.Copy(buffer, newBuffer, buffer.Length);
buffer = newBuffer;
}
stream.Read(buffer, offset, count);
offset += count;
}
internal int Position
{
get { return offset; }
set { offset = value; }
}
private int offset;
//internal void WriteBuffer(Stream stream, int count) {
// stream.Write(buffer, 0, count);
//}
internal void MinCapacity(int capacity)
{
if (buffer.Length < capacity)
{
buffer = new byte[capacity];
}
offset = 0;
}
internal void Align(int alignment)
{
while ((offset % alignment) != 0)
{
offset++;
}
}
//internal void WriteInt32(int value) {
// buffer[offset + 0] = (byte)value;
// buffer[offset + 1] = (byte)(value >> 8);
// buffer[offset + 2] = (byte)(value >> 16);
// buffer[offset + 3] = (byte)(value >> 24);
// offset += 4;
//}
//internal void WriteInt32(int[] values) {
// for (int i = 0; i < values.Length; i++) {
// WriteInt32(values[i]);
// }
//}
//internal void WriteBytes(byte[] bytes) {
// for (int i = 0; i < bytes.Length; i++) {
// buffer[offset++] = bytes[i];
// }
//}
internal void ReadInt16(out short value)
{
value = (short)((buffer[offset + 0] & 0xFF) |
(buffer[offset + 1] << 8));
offset += 2;
}
internal void ReadInt8(out sbyte value)
{
value = (sbyte)buffer[offset];
offset += 1;
}
internal void ReadInt32(out int value)
{
value = (int)((buffer[offset + 0] & 0xFF) |
(buffer[offset + 1] << 8) |
(buffer[offset + 2] << 16) |
(buffer[offset + 3] << 24));
offset += 4;
}
internal void ReadInt64(out long value)
{
value = (long)(((ulong)buffer[offset + 0] & 0xFF) |
((ulong)buffer[offset + 1] << 8) |
((ulong)buffer[offset + 2] << 16) |
((ulong)buffer[offset + 3] << 24) |
((ulong)buffer[offset + 4] << 32) |
((ulong)buffer[offset + 5] << 40) |
((ulong)buffer[offset + 6] << 48) |
((ulong)buffer[offset + 7] << 56));
offset += 8;
}
internal void ReadUInt16(out ushort value)
{
value = (ushort)((buffer[offset + 0] & 0xFF) |
(buffer[offset + 1] << 8));
offset += 2;
}
internal void ReadUInt8(out byte value)
{
value = (byte)((buffer[offset + 0] & 0xFF));
offset += 1;
}
internal void ReadUInt32(out uint value)
{
value = (uint)((buffer[offset + 0] & 0xFF) |
(buffer[offset + 1] << 8) |
(buffer[offset + 2] << 16) |
(buffer[offset + 3] << 24));
offset += 4;
}
internal void ReadUInt64(out ulong value)
{
value = (ulong)(((ulong)buffer[offset + 0] & 0xFF) |
((ulong)buffer[offset + 1] << 8) |
((ulong)buffer[offset + 2] << 16) |
((ulong)buffer[offset + 3] << 24) |
((ulong)buffer[offset + 4] << 32) |
((ulong)buffer[offset + 5] << 40) |
((ulong)buffer[offset + 6] << 48) |
((ulong)buffer[offset + 7] << 56));
offset += 8;
}
internal void ReadInt32(int[] values)
{
for (int i = 0; i < values.Length; i++)
{
ReadInt32(out values[i]);
}
}
internal void ReadUInt32(uint[] values)
{
for (int i = 0; i < values.Length; i++)
{
ReadUInt32(out values[i]);
}
}
internal void ReadBytes(byte[] bytes)
{
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = buffer[offset++];
}
}
internal float ReadFloat()
{
float result = BitConverter.ToSingle(buffer, offset);
offset += 4;
return result;
}
internal double ReadDouble()
{
double result = BitConverter.ToDouble(buffer, offset);
offset += 8;
return result;
}
internal decimal ReadDecimal()
{
int[] bits = new int[4];
this.ReadInt32(bits);
return new decimal(bits[2], bits[3], bits[1], bits[0] < 0, (byte)((bits[0] & 0x00FF0000) >> 16));
}
internal void ReadBString(out string value)
{
ushort len;
this.ReadUInt16(out len);
value = Encoding.UTF8.GetString(buffer, offset, len);
offset += len;
}
internal string ReadBString(int len)
{
var result = Encoding.UTF8.GetString(buffer, offset, len);
offset += len;
return result;
}
internal void ReadCString(out string value)
{
int len = 0;
while (offset + len < buffer.Length && buffer[offset + len] != 0)
{
len++;
}
value = Encoding.UTF8.GetString(buffer, offset, len);
offset += len + 1;
}
internal void SkipCString(out string value)
{
int len = 0;
while (offset + len < buffer.Length && buffer[offset + len] != 0)
{
len++;
}
offset += len + 1;
value = null;
}
internal void ReadGuid(out Guid guid)
{
uint a;
ushort b;
ushort c;
byte d;
byte e;
byte f;
byte g;
byte h;
byte i;
byte j;
byte k;
ReadUInt32(out a);
ReadUInt16(out b);
ReadUInt16(out c);
ReadUInt8(out d);
ReadUInt8(out e);
ReadUInt8(out f);
ReadUInt8(out g);
ReadUInt8(out h);
ReadUInt8(out i);
ReadUInt8(out j);
ReadUInt8(out k);
guid = new Guid(a, b, c, d, e, f, g, h, i, j, k);
}
internal string ReadString()
{
int len = 0;
while (offset + len < buffer.Length && buffer[offset + len] != 0)
{
len += 2;
}
string result = Encoding.Unicode.GetString(buffer, offset, len);
offset += len + 2;
return result;
}
}
}
| |
//
// CryptoConvertTest.cs - NUnit Test Cases for CryptoConvert
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2004 Novell (http://www.novell.com)
//
using NUnit.Framework;
using System;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace MonoTests.Mono.Security.Cryptography {
[TestFixture]
public class CryptoConvertTest : Assertion {
// because most crypto stuff works with byte[] buffers
static public void AssertEquals (string msg, byte[] array1, byte[] array2)
{
if ((array1 == null) && (array2 == null))
return;
if (array1 == null)
Fail (msg + " -> First array is NULL");
if (array2 == null)
Fail (msg + " -> Second array is NULL");
bool a = (array1.Length == array2.Length);
if (a) {
for (int i = 0; i < array1.Length; i++) {
if (array1 [i] != array2 [i]) {
a = false;
break;
}
}
}
msg += " -> Expected " + BitConverter.ToString (array1, 0);
msg += " is different than " + BitConverter.ToString (array2, 0);
Assert (msg, a);
}
// strongname generated using "sn -k unit.snk"
static byte[] strongName = {
0x07, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32,
0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x7F, 0x7C, 0xEA, 0x4A,
0x28, 0x33, 0xD8, 0x3C, 0x86, 0x90, 0x86, 0x91, 0x11, 0xBB, 0x30, 0x0D,
0x3D, 0x69, 0x04, 0x4C, 0x48, 0xF5, 0x4F, 0xE7, 0x64, 0xA5, 0x82, 0x72,
0x5A, 0x92, 0xC4, 0x3D, 0xC5, 0x90, 0x93, 0x41, 0xC9, 0x1D, 0x34, 0x16,
0x72, 0x2B, 0x85, 0xC1, 0xF3, 0x99, 0x62, 0x07, 0x32, 0x98, 0xB7, 0xE4,
0xFA, 0x75, 0x81, 0x8D, 0x08, 0xB9, 0xFD, 0xDB, 0x00, 0x25, 0x30, 0xC4,
0x89, 0x13, 0xB6, 0x43, 0xE8, 0xCC, 0xBE, 0x03, 0x2E, 0x1A, 0x6A, 0x4D,
0x36, 0xB1, 0xEB, 0x49, 0x26, 0x6C, 0xAB, 0xC4, 0x29, 0xD7, 0x8F, 0x25,
0x11, 0xA4, 0x7C, 0x81, 0x61, 0x97, 0xCB, 0x44, 0x2D, 0x80, 0x49, 0x93,
0x48, 0xA7, 0xC9, 0xAB, 0xDB, 0xCF, 0xA3, 0x34, 0xCB, 0x6B, 0x86, 0xE0,
0x4D, 0x27, 0xFC, 0xA7, 0x4F, 0x36, 0xCA, 0x13, 0x42, 0xD3, 0x83, 0xC4,
0x06, 0x6E, 0x12, 0xE0, 0xA1, 0x3D, 0x9F, 0xA9, 0xEC, 0xD1, 0xC6, 0x08,
0x1B, 0x3D, 0xF5, 0xDB, 0x4C, 0xD4, 0xF0, 0x2C, 0xAA, 0xFC, 0xBA, 0x18,
0x6F, 0x48, 0x7E, 0xB9, 0x47, 0x68, 0x2E, 0xF6, 0x1E, 0x67, 0x1C, 0x7E,
0x0A, 0xCE, 0x10, 0x07, 0xC0, 0x0C, 0xAD, 0x5E, 0xC1, 0x53, 0x70, 0xD5,
0xE7, 0x25, 0xCA, 0x37, 0x5E, 0x49, 0x59, 0xD0, 0x67, 0x2A, 0xBE, 0x92,
0x36, 0x86, 0x8A, 0xBF, 0x3E, 0x17, 0x04, 0xFB, 0x1F, 0x46, 0xC8, 0x10,
0x5C, 0x93, 0x02, 0x43, 0x14, 0x96, 0x6A, 0xD9, 0x87, 0x17, 0x62, 0x7D,
0x3A, 0x45, 0xBE, 0x35, 0xDE, 0x75, 0x0B, 0x2A, 0xCE, 0x7D, 0xF3, 0x19,
0x85, 0x4B, 0x0D, 0x6F, 0x8D, 0x15, 0xA3, 0x60, 0x61, 0x28, 0x55, 0x46,
0xCE, 0x78, 0x31, 0x04, 0x18, 0x3C, 0x56, 0x4A, 0x3F, 0xA4, 0xC9, 0xB1,
0x41, 0xED, 0x22, 0x80, 0xA1, 0xB3, 0xE2, 0xC7, 0x1B, 0x62, 0x85, 0xE4,
0x81, 0x39, 0xCB, 0x1F, 0x95, 0xCC, 0x61, 0x61, 0xDF, 0xDE, 0xF3, 0x05,
0x68, 0xB9, 0x7D, 0x4F, 0xFF, 0xF3, 0xC0, 0x0A, 0x25, 0x62, 0xD9, 0x8A,
0x8A, 0x9E, 0x99, 0x0B, 0xFB, 0x85, 0x27, 0x8D, 0xF6, 0xD4, 0xE1, 0xB9,
0xDE, 0xB4, 0x16, 0xBD, 0xDF, 0x6A, 0x25, 0x9C, 0xAC, 0xCD, 0x91, 0xF7,
0xCB, 0xC1, 0x81, 0x22, 0x0D, 0xF4, 0x7E, 0xEC, 0x0C, 0x84, 0x13, 0x5A,
0x74, 0x59, 0x3F, 0x3E, 0x61, 0x00, 0xD6, 0xB5, 0x4A, 0xA1, 0x04, 0xB5,
0xA7, 0x1C, 0x29, 0xD0, 0xE1, 0x11, 0x19, 0xD7, 0x80, 0x5C, 0xEE, 0x08,
0x15, 0xEB, 0xC9, 0xA8, 0x98, 0xF5, 0xA0, 0xF0, 0x92, 0x2A, 0xB0, 0xD3,
0xC7, 0x8C, 0x8D, 0xBB, 0x88, 0x96, 0x4F, 0x18, 0xF0, 0x8A, 0xF9, 0x31,
0x9E, 0x44, 0x94, 0x75, 0x6F, 0x78, 0x04, 0x10, 0xEC, 0xF3, 0xB0, 0xCE,
0xA0, 0xBE, 0x7B, 0x25, 0xE1, 0xF7, 0x8A, 0xA8, 0xD4, 0x63, 0xC2, 0x65,
0x47, 0xCC, 0x5C, 0xED, 0x7D, 0x8B, 0x07, 0x4D, 0x76, 0x29, 0x53, 0xAC,
0x27, 0x8F, 0x5D, 0x78, 0x56, 0xFA, 0x99, 0x45, 0xA2, 0xCC, 0x65, 0xC4,
0x54, 0x13, 0x9F, 0x38, 0x41, 0x7A, 0x61, 0x0E, 0x0D, 0x34, 0xBC, 0x11,
0xAF, 0xE2, 0xF1, 0x8B, 0xFA, 0x2B, 0x54, 0x6C, 0xA3, 0x6C, 0x09, 0x1F,
0x0B, 0x43, 0x9B, 0x07, 0x95, 0x83, 0x3F, 0x97, 0x99, 0x89, 0xF5, 0x51,
0x41, 0xF6, 0x8E, 0x5D, 0xEF, 0x6D, 0x24, 0x71, 0x41, 0x7A, 0xAF, 0xBE,
0x81, 0x71, 0xAB, 0x76, 0x2F, 0x1A, 0x5A, 0xBA, 0xF3, 0xA6, 0x65, 0x7A,
0x80, 0x50, 0xCE, 0x23, 0xC3, 0xC7, 0x53, 0xB0, 0x7C, 0x97, 0x77, 0x27,
0x70, 0x98, 0xAE, 0xB5, 0x24, 0x66, 0xE1, 0x60, 0x39, 0x41, 0xDA, 0x54,
0x01, 0x64, 0xFB, 0x10, 0x33, 0xCE, 0x8B, 0xBE, 0x27, 0xD4, 0x21, 0x57,
0xCC, 0x0F, 0x1A, 0xC1, 0x3D, 0xF3, 0xCC, 0x39, 0xF0, 0x2F, 0xAE, 0xF1,
0xC0, 0xCD, 0x3B, 0x23, 0x87, 0x49, 0x7E, 0x40, 0x32, 0x6A, 0xD3, 0x96,
0x4A, 0xE5, 0x5E, 0x6E, 0x26, 0xFD, 0x8A, 0xCF, 0x7E, 0xFC, 0x37, 0xDE,
0x39, 0x0C, 0x53, 0x81, 0x75, 0x08, 0xAF, 0x6B, 0x39, 0x6C, 0xFB, 0xC9,
0x79, 0xC0, 0x9B, 0x5F, 0x34, 0x86, 0xB2, 0xDE, 0xC4, 0x19, 0x84, 0x5F,
0x0E, 0xED, 0x9B, 0xB8, 0xD3, 0x17, 0xDA, 0x78 };
static string strongNameString = "<RSAKeyValue><Modulus>4BJuBsSD00ITyjZPp/wnTeCGa8s0o8/bq8mnSJNJgC1Ey5dhgXykESWP1ynEq2wmSeuxNk1qGi4DvszoQ7YTicQwJQDb/bkIjYF1+uS3mDIHYpnzwYUrchY0HclBk5DFPcSSWnKCpWTnT/VITARpPQ0wuxGRhpCGPNgzKErqfH8=</Modulus><Exponent>AQAB</Exponent><P>+wQXPr+KhjaSvipn0FlJXjfKJefVcFPBXq0MwAcQzgp+HGce9i5oR7l+SG8YuvyqLPDUTNv1PRsIxtHsqZ89oQ==</P><Q>5IViG8fis6GAIu1BscmkP0pWPBgEMXjORlUoYWCjFY1vDUuFGfN9zioLdd41vkU6fWIXh9lqlhRDApNcEMhGHw==</Q><DP>Pj9ZdFoThAzsfvQNIoHBy/eRzaycJWrfvRa03rnh1PaNJ4X7C5meiorZYiUKwPP/T325aAXz3t9hYcyVH8s5gQ==</DP><DQ>qIr34SV7vqDOsPPsEAR4b3WURJ4x+YrwGE+WiLuNjMfTsCqS8KD1mKjJ6xUI7lyA1xkR4dApHKe1BKFKtdYAYQ==</DQ><InverseQ>UfWJmZc/g5UHm0MLHwlso2xUK/qL8eKvEbw0DQ5hekE4nxNUxGXMokWZ+lZ4XY8nrFMpdk0Hi33tXMxHZcJj1A==</InverseQ><D>eNoX07ib7Q5fhBnE3rKGNF+bwHnJ+2w5a68IdYFTDDneN/x+z4r9Jm5e5UqW02oyQH5JhyM7zcDxri/wOczzPcEaD8xXIdQnvovOMxD7ZAFU2kE5YOFmJLWumHAnd5d8sFPHwyPOUIB6ZabzuloaL3arcYG+r3pBcSRt712O9kE=</D></RSAKeyValue>";
// strongname public key extracted using "sn -p unit.snk unit.pub"
static byte[] strongNamePublicKey = {
0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00,
0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31,
0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x7F, 0x7C, 0xEA, 0x4A,
0x28, 0x33, 0xD8, 0x3C, 0x86, 0x90, 0x86, 0x91, 0x11, 0xBB, 0x30, 0x0D,
0x3D, 0x69, 0x04, 0x4C, 0x48, 0xF5, 0x4F, 0xE7, 0x64, 0xA5, 0x82, 0x72,
0x5A, 0x92, 0xC4, 0x3D, 0xC5, 0x90, 0x93, 0x41, 0xC9, 0x1D, 0x34, 0x16,
0x72, 0x2B, 0x85, 0xC1, 0xF3, 0x99, 0x62, 0x07, 0x32, 0x98, 0xB7, 0xE4,
0xFA, 0x75, 0x81, 0x8D, 0x08, 0xB9, 0xFD, 0xDB, 0x00, 0x25, 0x30, 0xC4,
0x89, 0x13, 0xB6, 0x43, 0xE8, 0xCC, 0xBE, 0x03, 0x2E, 0x1A, 0x6A, 0x4D,
0x36, 0xB1, 0xEB, 0x49, 0x26, 0x6C, 0xAB, 0xC4, 0x29, 0xD7, 0x8F, 0x25,
0x11, 0xA4, 0x7C, 0x81, 0x61, 0x97, 0xCB, 0x44, 0x2D, 0x80, 0x49, 0x93,
0x48, 0xA7, 0xC9, 0xAB, 0xDB, 0xCF, 0xA3, 0x34, 0xCB, 0x6B, 0x86, 0xE0,
0x4D, 0x27, 0xFC, 0xA7, 0x4F, 0x36, 0xCA, 0x13, 0x42, 0xD3, 0x83, 0xC4,
0x06, 0x6E, 0x12, 0xE0 };
static string strongNamePublicKeyString = "<RSAKeyValue><Modulus>4BJuBsSD00ITyjZPp/wnTeCGa8s0o8/bq8mnSJNJgC1Ey5dhgXykESWP1ynEq2wmSeuxNk1qGi4DvszoQ7YTicQwJQDb/bkIjYF1+uS3mDIHYpnzwYUrchY0HclBk5DFPcSSWnKCpWTnT/VITARpPQ0wuxGRhpCGPNgzKErqfH8=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
static byte[] strongNameNUnit = {
0x07, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32,
0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xCF, 0x4A, 0x0B, 0xBF,
0x35, 0x4B, 0x6D, 0x8D, 0x0C, 0x39, 0xE7, 0xBC, 0x40, 0xDD, 0x0B, 0xE1,
0x6A, 0x32, 0xBA, 0x9D, 0x76, 0x3E, 0x8D, 0x04, 0xFD, 0x95, 0x91, 0xB9,
0x2D, 0x72, 0x69, 0xDD, 0x09, 0xC2, 0xC6, 0x5E, 0xC7, 0x56, 0x3C, 0xE3,
0x93, 0xAC, 0xA7, 0x19, 0x13, 0xBE, 0xA1, 0x3D, 0xD6, 0xA2, 0x0D, 0x67,
0x6E, 0xD7, 0xDD, 0xC7, 0x26, 0xF8, 0x46, 0xFC, 0xE6, 0x68, 0x00, 0xBB,
0x03, 0x49, 0x03, 0x61, 0x9A, 0x1B, 0xAA, 0x52, 0x0F, 0x5F, 0x75, 0x89,
0x46, 0xCF, 0x2B, 0x4A, 0xF6, 0xBA, 0x7C, 0x31, 0x0D, 0x02, 0xD0, 0x92,
0xA5, 0xCF, 0x51, 0xBE, 0x6D, 0x52, 0xE8, 0x86, 0x33, 0xF5, 0x02, 0x47,
0x4B, 0x4F, 0x46, 0x1D, 0x85, 0x0B, 0x63, 0x21, 0x9C, 0x09, 0xA3, 0x37,
0x3A, 0x23, 0xD7, 0x31, 0x56, 0xEE, 0x03, 0xD6, 0xC7, 0xB3, 0x8C, 0x36,
0xD1, 0x21, 0x1F, 0xAC, 0xCD, 0xA7, 0x7F, 0x90, 0x33, 0x0B, 0x49, 0x62,
0xA6, 0xAD, 0xD1, 0xF5, 0x65, 0xC2, 0x78, 0x94, 0x0F, 0xB5, 0xC4, 0x4C,
0x3A, 0xC3, 0x06, 0xD1, 0x6B, 0x7C, 0x87, 0x2B, 0x57, 0xE2, 0xBB, 0x5D,
0x10, 0x85, 0x6E, 0xD7, 0xFC, 0x2D, 0x5F, 0xF4, 0x8A, 0xEA, 0xA7, 0xD7,
0x39, 0x84, 0x22, 0x12, 0xCF, 0x6E, 0x13, 0xC6, 0x45, 0x3B, 0xDB, 0xFD,
0xCE, 0xBD, 0x2B, 0x5A, 0x18, 0x29, 0xDE, 0xD9, 0x0B, 0x69, 0xAC, 0x30,
0x7B, 0x19, 0x2C, 0x35, 0x38, 0xFE, 0x5A, 0x73, 0x72, 0x32, 0xA5, 0x47,
0x48, 0xEA, 0xD7, 0x05, 0x83, 0x93, 0x5A, 0xAC, 0x59, 0xDC, 0x08, 0xE2,
0x44, 0x67, 0xAA, 0x0E, 0xB1, 0xA0, 0x73, 0xAC, 0xFB, 0x62, 0x2C, 0x31,
0x15, 0xE7, 0x83, 0xB5, 0x3F, 0xCF, 0xA4, 0x4C, 0x23, 0x57, 0x3B, 0x61,
0x59, 0x23, 0x50, 0x0E, 0xE7, 0xAE, 0x8E, 0x69, 0x78, 0x41, 0x3F, 0xCA,
0x95, 0xAC, 0x41, 0x59, 0x71, 0x25, 0xDA, 0x58, 0x91, 0x04, 0x8B, 0xBA,
0xF9, 0x5B, 0xF1, 0x33, 0xD4, 0x4F, 0x43, 0x99, 0x10, 0x6A, 0x2A, 0x4D,
0x78, 0xE7, 0x21, 0xE9, 0x47, 0x65, 0x81, 0xE9, 0x74, 0xB2, 0x6F, 0xE5,
0xFA, 0xB9, 0xEC, 0x37, 0x5B, 0x1D, 0x21, 0x31, 0x92, 0x5C, 0xCF, 0xFF,
0xBC, 0x34, 0xA5, 0x44, 0x48, 0xF7, 0xE3, 0xF1, 0x28, 0xE1, 0xC6, 0x39,
0x8F, 0x00, 0xC9, 0x70, 0x4B, 0x06, 0x0B, 0x0C, 0x66, 0x1E, 0xCF, 0x54,
0xEA, 0xE2, 0xA8, 0xFC, 0xE4, 0xBA, 0x1C, 0xA0, 0xA9, 0x71, 0x16, 0x51,
0x97, 0xA8, 0xBC, 0x4A, 0x95, 0x42, 0x71, 0x9F, 0x01, 0x5B, 0xEC, 0x07,
0x69, 0x7E, 0xB1, 0xB6, 0x92, 0x3D, 0x55, 0xE1, 0x48, 0xA6, 0x8F, 0x47,
0x5A, 0xBF, 0x47, 0x00, 0xF8, 0x1E, 0x2F, 0xE4, 0x62, 0x9F, 0xDD, 0x2F,
0x33, 0x2F, 0x9B, 0xF1, 0x5C, 0x93, 0x3E, 0x83, 0x65, 0xEA, 0x12, 0x4E,
0x9E, 0xDA, 0x6F, 0x6A, 0x51, 0x03, 0x8C, 0x2F, 0x47, 0xEB, 0x5C, 0x5B,
0x40, 0xC2, 0xE8, 0x4D, 0xC5, 0xA3, 0xC4, 0x8D, 0x30, 0x9A, 0xD4, 0x8E,
0x7D, 0x4D, 0xA6, 0x89, 0x81, 0x72, 0x82, 0x47, 0x5F, 0xAA, 0x4B, 0xBB,
0xD5, 0x8C, 0x75, 0x78, 0x21, 0x0F, 0x4B, 0xAA, 0x2E, 0x12, 0xF9, 0xF5,
0x81, 0x88, 0x72, 0x22, 0xD7, 0x77, 0xB4, 0x5F, 0x85, 0x12, 0xE5, 0xC7,
0x31, 0x2F, 0x4E, 0x3C, 0x63, 0xE9, 0x47, 0x79, 0x3C, 0x21, 0x5B, 0xDD,
0xED, 0x1C, 0x6A, 0xFD, 0x87, 0x01, 0xD2, 0x34, 0x0C, 0xEC };
[Test]
public void FromCapiKeyBlob ()
{
// keypair
RSA rsa = CryptoConvert.FromCapiKeyBlob (strongName, 0);
AssertEquals ("KeyPair", strongNameString, rsa.ToXmlString (true));
AssertEquals ("PublicKey-1", strongNamePublicKeyString, rsa.ToXmlString (false));
// public key (direct)
rsa = CryptoConvert.FromCapiKeyBlob (strongNamePublicKey, 12);
AssertEquals ("PublicKey-2", strongNamePublicKeyString, rsa.ToXmlString (false));
// public key (indirect - inside header)
rsa = CryptoConvert.FromCapiKeyBlob (strongNamePublicKey, 0);
AssertEquals ("PublicKey-3", strongNamePublicKeyString, rsa.ToXmlString (false));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void FromCapiKeyBlob_Null ()
{
RSA rsa = CryptoConvert.FromCapiKeyBlob (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromCapiKeyBlob_InvalidOffset ()
{
RSA rsa = CryptoConvert.FromCapiKeyBlob (new byte [0], 0);
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void FromCapiKeyBlob_UnknownBlob ()
{
byte[] blob = new byte [160];
RSA rsa = CryptoConvert.FromCapiKeyBlob (blob, 12);
}
[Test]
public void FromCapiPrivateKeyBlob ()
{
RSA rsa = CryptoConvert.FromCapiPrivateKeyBlob (strongName, 0);
AssertEquals ("KeyPair", strongNameString, rsa.ToXmlString (true));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void FromCapiPrivateKeyBlob_Null ()
{
RSA rsa = CryptoConvert.FromCapiPrivateKeyBlob (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromCapiPrivateKeyBlob_InvalidOffset ()
{
RSA rsa = CryptoConvert.FromCapiPrivateKeyBlob (new byte [0], 0);
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void FromCapiPrivateKeyBlob_Invalid ()
{
RSA rsa = CryptoConvert.FromCapiPrivateKeyBlob (strongNamePublicKey, 12);
}
[Test]
public void FromCapiPublicKeyBlob ()
{
RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (strongNamePublicKey, 12);
AssertEquals ("PublicKey", strongNamePublicKeyString, rsa.ToXmlString (false));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void FromCapiPublicKeyBlob_Null ()
{
RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromCapiPublicKeyBlob_InvalidOffset ()
{
RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (new byte [0], 0);
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void FromCapiPublicKeyBlob_Invalid ()
{
RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (strongName, 0);
}
[Test]
public void ToCapiKeyBlob_AsymmetricAlgorithm ()
{
AsymmetricAlgorithm rsa = RSA.Create ();
rsa.FromXmlString (strongNameString);
byte[] keypair = CryptoConvert.ToCapiKeyBlob (rsa, true);
AssertEquals ("RSA-KeyPair", strongName, keypair);
byte[] publicKey = CryptoConvert.ToCapiKeyBlob (rsa, false);
AssertEquals ("RSA-PublicKey", BitConverter.ToString (strongNamePublicKey, 12), BitConverter.ToString (publicKey));
// TODO dsa (not implemented yet)
AsymmetricAlgorithm dsa = DSA.Create ();
AssertNull ("DSA-KeyPair", CryptoConvert.ToCapiKeyBlob (dsa, true));
AssertNull ("DSA-PublicKey", CryptoConvert.ToCapiKeyBlob (dsa, false));
}
[Test]
public void ToCapiKeyBlob_RSA ()
{
RSA rsa = RSA.Create ();
rsa.FromXmlString (strongNameString);
byte[] keypair = CryptoConvert.ToCapiKeyBlob (rsa, true);
AssertEquals ("KeyPair", strongName, keypair);
byte[] publicKey = CryptoConvert.ToCapiKeyBlob (rsa, false);
AssertEquals ("PublicKey", BitConverter.ToString (strongNamePublicKey, 12), BitConverter.ToString (publicKey));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void ToCapiKeyBlob_AsymmetricNull ()
{
AsymmetricAlgorithm aa = null;
CryptoConvert.ToCapiKeyBlob (aa, false);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void ToCapiKeyBlob_RSANull ()
{
RSA rsa = null;
CryptoConvert.ToCapiKeyBlob (rsa, false);
}
[Test]
public void ToCapiPrivateKeyBlob ()
{
RSA rsa = RSA.Create ();
rsa.FromXmlString (strongNameString);
byte[] keypair = CryptoConvert.ToCapiPrivateKeyBlob (rsa);
AssertEquals ("KeyPair", strongName, keypair);
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void ToCapiPrivateKeyBlob_PublicKeyOnly ()
{
RSA rsa = RSA.Create ();
rsa.FromXmlString (strongNamePublicKeyString);
byte[] publicKey = CryptoConvert.ToCapiPrivateKeyBlob (rsa);
}
[Test]
public void ToCapiPublicKeyBlob ()
{
RSA rsa = RSA.Create ();
// full keypair
rsa.FromXmlString (strongNameString);
byte[] publicKey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
AssertEquals ("PublicKey-1", BitConverter.ToString (strongNamePublicKey, 12), BitConverter.ToString (publicKey));
// public key only
rsa.FromXmlString (strongNamePublicKeyString);
publicKey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
AssertEquals ("PublicKey-2", BitConverter.ToString (strongNamePublicKey, 12), BitConverter.ToString (publicKey));
}
[Test]
public void FromHex ()
{
AssertNull ("FromHex(null)", CryptoConvert.FromHex (null));
string result = BitConverter.ToString (CryptoConvert.FromHex ("0123456789aBcDeF"));
AssertEquals ("0123456789abcdef", "01-23-45-67-89-AB-CD-EF", result);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromHex_NonHexChars ()
{
CryptoConvert.FromHex ("abcdefgh");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromHex_NonMultipleOf2 ()
{
CryptoConvert.FromHex ("abc");
}
[Test]
public void ToHex ()
{
AssertNull ("FromHex(null)", CryptoConvert.FromHex (null));
byte[] data = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
AssertEquals ("0123456789abcdef", "0123456789ABCDEF", CryptoConvert.ToHex (data));
}
[Test]
public void NUnitKey_Broken ()
{
// for some strange reason nunit.snk hasn't the same
// size as other strongname. I wonder how it was
// generated ?
RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameNUnit, 0);
// note the bad D parameters !!!
// this only works because CRT is being used
AssertEquals ("KeyPair", "<RSAKeyValue><Modulus>rB8h0TaMs8fWA+5WMdcjOjejCZwhYwuFHUZPS0cC9TOG6FJtvlHPpZLQAg0xfLr2SivPRol1Xw9SqhuaYQNJA7sAaOb8Rvgmx93XbmcNotY9ob4TGaesk+M8VsdexsIJ3WlyLbmRlf0EjT52nboyauEL3UC85zkMjW1LNb8LSs8=</Modulus><Exponent>AQAB</Exponent><P>2d4pGForvc792ztFxhNuzxIihDnXp+qK9F8t/NduhRBdu+JXK4d8a9EGwzpMxLUPlHjCZfXRraZiSQszkH+nzQ==</P><Q>yj9BeGmOrucOUCNZYTtXI0ykzz+1g+cVMSxi+6xzoLEOqmdE4gjcWaxak4MF1+pIR6UycnNa/jg1LBl7MKxpCw==</Q><DP>cMkAjznG4Sjx4/dIRKU0vP/PXJIxIR1bN+y5+uVvsnTpgWVH6SHneE0qahCZQ0/UM/Fb+bqLBJFY2iVxWUGslQ==</DP><DQ>gz6TXPGbLzMv3Z9i5C8e+ABHv1pHj6ZI4VU9kraxfmkH7FsBn3FClUq8qJdRFnGpoBy65Pyo4upUzx5mDAsGSw==</DQ><InverseQ>x+UShV+0d9cicoiB9fkSLqpLDyF4dYzVu0uqX0eCcoGJpk19jtSaMI3Eo8VN6MJAW1zrRy+MA1Fqb9qeThLqZQ==</InverseQ><D>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</D></RSAKeyValue>", rsa.ToXmlString (true));
AssertEquals ("PublicKey", "<RSAKeyValue><Modulus>rB8h0TaMs8fWA+5WMdcjOjejCZwhYwuFHUZPS0cC9TOG6FJtvlHPpZLQAg0xfLr2SivPRol1Xw9SqhuaYQNJA7sAaOb8Rvgmx93XbmcNotY9ob4TGaesk+M8VsdexsIJ3WlyLbmRlf0EjT52nboyauEL3UC85zkMjW1LNb8LSs8=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>", rsa.ToXmlString (false));
}
}
}
| |
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
using Http2;
using Http2.Hpack;
using static Http2Tests.TestHeaders;
namespace Http2Tests
{
public class GenericStreamTests
{
private ILoggerProvider loggerProvider;
public GenericStreamTests(ITestOutputHelper outHelper)
{
loggerProvider = new XUnitOutputLoggerProvider(outHelper);
}
public static class StreamCreator
{
public struct Result
{
public Encoder hEncoder;
public Connection conn;
public IStream stream;
}
/// <summary>
/// Creates a bidirectionally open stream,
/// where the headers in both directions have already been sent but
/// no data.
/// </summary>
public static async Task<Result> CreateConnectionAndStream(
bool isServer,
ILoggerProvider loggerProvider,
IBufferedPipe iPipe, IBufferedPipe oPipe,
Settings? localSettings = null,
Settings? remoteSettings = null,
HuffmanStrategy huffmanStrategy = HuffmanStrategy.Never)
{
var result = new Result();
if (isServer)
{
var r1 = await ServerStreamTests.StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider,
iPipe, oPipe,
localSettings, remoteSettings,
huffmanStrategy);
// Headers have been received but not sent
await r1.stream.WriteHeadersAsync(DefaultStatusHeaders, false);
await oPipe.ReadAndDiscardHeaders(1u, false);
result.conn = r1.conn;
result.hEncoder = r1.hEncoder;
result.stream = r1.stream;
}
else
{
var r1 = await ClientStreamTests.StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider,
iPipe, oPipe,
localSettings, remoteSettings,
huffmanStrategy);
// Headers have been sent but not yet received
await iPipe.WriteHeaders(r1.hEncoder, 1u, false, DefaultStatusHeaders, true);
result.conn = r1.conn;
result.hEncoder = r1.hEncoder;
result.stream = r1.stream;
}
return result;
}
}
[Theory]
[InlineData(true, new int[]{0})]
[InlineData(true, new int[]{1})]
[InlineData(true, new int[]{100})]
[InlineData(true, new int[]{99, 784})]
[InlineData(true, new int[]{12874, 16384, 16383})]
[InlineData(false, new int[]{0})]
[InlineData(false, new int[]{1})]
[InlineData(false, new int[]{100})]
[InlineData(false, new int[]{99, 784})]
[InlineData(false, new int[]{12874, 16384, 16383})]
public async Task DataShouldBeCorrectlySent(
bool isServer, int[] dataLength)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe);
var totalToSend = dataLength.Aggregate(0, (sum, n) => sum+n);
var writeTask = Task.Run(async () =>
{
byte nr = 0;
for (var i = 0; i < dataLength.Length; i++)
{
var toSend = dataLength[i];
var isEndOfStream = i == (dataLength.Length - 1);
var buffer = new byte[toSend];
for (var j = 0; j < toSend; j++)
{
buffer[j] = nr;
nr++;
if (nr > 122) nr = 0;
}
await r.stream.WriteAsync(
new ArraySegment<byte>(buffer), isEndOfStream);
}
});
var data = new byte[totalToSend];
var offset = 0;
for (var i = 0; i < dataLength.Length; i++)
{
var fh = await outPipe.ReadFrameHeaderWithTimeout();
Assert.Equal(FrameType.Data, fh.Type);
Assert.Equal(1u, fh.StreamId);
var expectEOS = i == dataLength.Length - 1;
var gotEOS = (fh.Flags & (byte)DataFrameFlags.EndOfStream) != 0;
Assert.Equal(expectEOS, gotEOS);
Assert.Equal(dataLength[i], fh.Length);
var part = new byte[fh.Length];
await outPipe.ReadAllWithTimeout(new ArraySegment<byte>(part));
Array.Copy(part, 0, data, offset, fh.Length);
offset += fh.Length;
}
var doneTask = await Task.WhenAny(writeTask, Task.Delay(250));
Assert.True(writeTask == doneTask, "Expected write task to finish");
// Check if the correct data was received
var expected = 0;
for (var j = 0; j < totalToSend; j++)
{
Assert.Equal(expected, data[j]);
expected++;
if (expected > 122) expected = 0;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task EmptyDataFramesShouldNotWakeupPendingReads(
bool isServer)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe);
// Send a 0byte data frame
await inPipe.WriteData(1u, 0);
// Try to read - this should not unblock
var readTask = res.stream.ReadAsync(
new ArraySegment<byte>(new byte[1])).AsTask();
var doneTask = await Task.WhenAny(readTask, Task.Delay(100));
Assert.True(
doneTask != readTask,
"Expected read timeout but read finished");
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task EmptyDataFramesShouldBeValidSeperatorsBeforeTrailers(
bool isServer)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe);
// Send a 0byte data frame
await inPipe.WriteData(1u, 0);
// Send trailers
await inPipe.WriteHeaders(res.hEncoder, 1u, true,
DefaultTrailingHeaders);
// Check for no stream error
await inPipe.WritePing(new byte[8], false);
await outPipe.ReadAndDiscardPong();
}
[Theory]
[InlineData(true, new int[]{0})]
[InlineData(true, new int[]{1})]
[InlineData(true, new int[]{100})]
[InlineData(true, new int[]{99, 784})]
[InlineData(true, new int[]{12874, 16384, 16383})]
[InlineData(false, new int[]{0})]
[InlineData(false, new int[]{1})]
[InlineData(false, new int[]{100})]
[InlineData(false, new int[]{99, 784})]
[InlineData(false, new int[]{12874, 16384, 16383})]
public async Task DataFromDataFramesShouldBeReceived(
bool isServer, int[] dataLength)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe);
var readTask = res.stream.ReadAllToArrayWithTimeout();
var totalToSend = dataLength.Aggregate(0, (sum, n) => sum+n);
byte nr = 0;
for (var i = 0; i < dataLength.Length; i++)
{
var toSend = dataLength[i];
var isEndOfStream = i == (dataLength.Length - 1);
var flags = isEndOfStream ? DataFrameFlags.EndOfStream : 0;
var fh = new FrameHeader
{
Type = FrameType.Data,
StreamId = 1,
Flags = (byte)flags,
Length = toSend,
};
await inPipe.WriteFrameHeaderWithTimeout(fh);
var fdata = new byte[toSend];
for (var j = 0; j < toSend; j++)
{
fdata[j] = nr;
nr++;
if (nr > 122) nr = 0;
}
await inPipe.WriteWithTimeout(new ArraySegment<byte>(fdata));
// Wait for a short amount of time between DATA frames
if (!isEndOfStream) await Task.Delay(10);
}
var doneTask = await Task.WhenAny(
readTask, Task.Delay(ReadableStreamTestExtensions.ReadTimeout));
Assert.True(doneTask == readTask, "Expected read task to complete within timeout");
byte[] receivedData = await readTask;
Assert.NotNull(receivedData);
Assert.Equal(totalToSend, receivedData.Length);
var expected = 0;
for (var j = 0; j < totalToSend; j++)
{
Assert.Equal(expected, receivedData[j]);
expected++;
if (expected > 122) expected = 0;
}
}
[Theory]
[InlineData(true, 20, 0, 0)]
[InlineData(true, 20, 1, 0)]
[InlineData(true, 20, 0, 1024)]
[InlineData(true, 20, 1, 1024)]
[InlineData(true, 20, 255, 0)]
[InlineData(true, 20, 255, 1024)]
[InlineData(true, 5, 255, 64*1024 - 1)]
[InlineData(false, 20, 0, 0)]
[InlineData(false, 20, 1, 0)]
[InlineData(false, 20, 0, 1024)]
[InlineData(false, 20, 1, 1024)]
[InlineData(false, 20, 255, 0)]
[InlineData(false, 20, 255, 1024)]
[InlineData(false, 5, 255, 64*1024 - 1)]
public async Task DataFramesWithPaddingShouldBeCorrectlyReceived(
bool isServer, int nrFrames, byte numPadding, int bytesToSend)
{
var inPipe = new BufferedPipe(10*1024);
var outPipe = new BufferedPipe(10*1024);
var receiveOk = true;
var settings = Settings.Default;
settings.MaxFrameSize = 100 * 1024;
settings.InitialWindowSize = int.MaxValue;
var r = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe,
localSettings: settings);
for (var nrSends = 0; nrSends < nrFrames; nrSends++)
{
var buf = new byte[1 + bytesToSend + numPadding];
buf[0] = numPadding;
byte nr = 0;
for (var i = 0; i < bytesToSend; i++)
{
buf[1+i] = nr;
nr++;
if (nr > 123) nr = 0;
}
var fh = new FrameHeader
{
Type = FrameType.Data,
StreamId = 1,
Flags = (byte)DataFrameFlags.Padded,
Length = buf.Length,
};
await inPipe.WriteFrameHeaderWithTimeout(fh);
await inPipe.WriteWithTimeout(new ArraySegment<byte>(buf));
}
for (var nrSends = 0; nrSends < nrFrames; nrSends++)
{
var buf1 = new byte[bytesToSend];
await r.stream.ReadAllWithTimeout(new ArraySegment<byte>(buf1));
var expected = 0;
for (var j = 0; j < bytesToSend; j++)
{
if (buf1[j] != expected) {
receiveOk = false;
}
expected++;
if (expected > 123) expected = 0;
}
}
Assert.True(receiveOk, "Expected to receive correct data");
}
[Theory]
[InlineData(null, false)]
[InlineData(0, false)]
[InlineData(1, false)]
[InlineData(255, false)]
[InlineData(null, true)]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(255, true)]
public async Task ReceivingHeadersWithPaddingAndPriorityShouldBeSupported(
int? numPadding, bool hasPrio)
{
const int nrStreams = 10;
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
int nrAcceptedStreams = 0;
var handlerDone = new SemaphoreSlim(0);
uint streamId = 1;
var headersOk = false;
var streamIdOk = false;
var streamStateOk = false;
Func<IStream, bool> listener = (s) =>
{
Interlocked.Increment(ref nrAcceptedStreams);
Task.Run(async () =>
{
var rcvdHeaders = await s.ReadHeadersAsync();
headersOk = DefaultGetHeaders.SequenceEqual(rcvdHeaders);
streamIdOk = s.Id == streamId;
streamStateOk = s.State == StreamState.Open;
handlerDone.Release();
});
return true;
};
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
true, inPipe, outPipe, loggerProvider, listener);
var hEncoder = new Encoder();
var outBuf = new byte[Settings.Default.MaxFrameSize];
for (var i = 0; i < nrStreams; i++)
{
headersOk = false;
streamIdOk = false;
streamStateOk = false;
var headerOffset = 0;
if (numPadding != null)
{
outBuf[0] = (byte)numPadding;
headerOffset += 1;
}
if (hasPrio)
{
// TODO: Initialize the priority data in this test properly
// if priority data checking gets inserted later on
headerOffset += 5;
}
var result = hEncoder.EncodeInto(
new ArraySegment<byte>(outBuf, headerOffset, outBuf.Length-headerOffset),
DefaultGetHeaders);
var totalLength = headerOffset + result.UsedBytes;
if (numPadding != null) totalLength += numPadding.Value;
var flags = (byte)HeadersFrameFlags.EndOfHeaders;
if (numPadding != null) flags |= (byte)HeadersFrameFlags.Padded;
if (hasPrio) flags |= (byte)HeadersFrameFlags.Priority;
var fh = new FrameHeader
{
Type = FrameType.Headers,
Length = totalLength,
Flags = (byte)flags,
StreamId = streamId,
};
await inPipe.WriteFrameHeader(fh);
await inPipe.WriteAsync(new ArraySegment<byte>(outBuf, 0, totalLength));
var requestDone = await handlerDone.WaitAsync(ReadableStreamTestExtensions.ReadTimeout);
Assert.True(requestDone, "Expected handler to complete within timeout");
Assert.True(headersOk);
Assert.True(streamIdOk);
Assert.True(streamStateOk);
streamId += 2;
}
Assert.Equal(nrStreams, nrAcceptedStreams);
}
// TODO: Add checks for the cases where HPACK encoding is invalid
[Theory]
[InlineData(true, 0, null)]
[InlineData(true, 1, (byte)1)]
[InlineData(true, 255, (byte)255)]
[InlineData(false, 0, null)]
[InlineData(false, 1, (byte)1)]
[InlineData(false, 255, (byte)255)]
public async Task PaddingViolationsOnStreamsShouldLeadToGoAway(
bool onKnownStream, int frameLength, byte? padData)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await ServerStreamTests.StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider, inPipe, outPipe);
var fh = new FrameHeader
{
Type = FrameType.Data,
StreamId = onKnownStream ? 1u : 2u,
Flags = (byte)DataFrameFlags.Padded,
Length = frameLength,
};
await inPipe.WriteFrameHeader(fh);
if (frameLength > 0)
{
var data = new byte[frameLength];
data[0] = padData.Value;
await inPipe.WriteAsync(new ArraySegment<byte>(data));
}
await outPipe.AssertGoAwayReception(ErrorCode.ProtocolError, 1u);
}
// TODO: Check if HEADER frames with invalid padding lead to GOAWAY
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ReceivingTrailersShouldUnblockDataReceptionAndPresentThem(
bool isServer)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe);
var readDataTask = res.stream.ReadAllToArrayWithTimeout();
var fh = new FrameHeader
{
Type = FrameType.Data,
Length = 4,
StreamId = 1,
Flags = (byte)0,
};
await inPipe.WriteFrameHeader(fh);
await inPipe.WriteAsync(
new ArraySegment<byte>(
System.Text.Encoding.ASCII.GetBytes("ABCD")));
var trailers = new HeaderField[] {
new HeaderField { Name = "trai", Value = "ler" },
};
await inPipe.WriteHeaders(res.hEncoder, 1, true, trailers);
var bytes = await readDataTask;
Assert.Equal(4, bytes.Length);
Assert.Equal("ABCD", System.Text.Encoding.ASCII.GetString(bytes));
Assert.Equal(StreamState.HalfClosedRemote, res.stream.State);
var rcvdTrailers = await res.stream.ReadTrailersAsync();
Assert.Equal(trailers, rcvdTrailers);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task TrailersShouldBeCorrectlySent(bool isServer)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe);
await r.stream.WriteAsync(new ArraySegment<byte>(new byte[0]));
await outPipe.ReadAndDiscardData(1u, false, 0);
// Send trailers
await r.stream.WriteTrailersAsync(DefaultTrailingHeaders);
// Check the received trailers
var fh = await outPipe.ReadFrameHeaderWithTimeout();
Assert.Equal(FrameType.Headers, fh.Type);
Assert.Equal(1u, fh.StreamId);
var expectedFlags =
HeadersFrameFlags.EndOfHeaders | HeadersFrameFlags.EndOfStream;
Assert.Equal((byte)expectedFlags, fh.Flags);
Assert.InRange(fh.Length, 1, 1024);
var headerData = new byte[fh.Length];
await outPipe.ReadAllWithTimeout(new ArraySegment<byte>(headerData));
Assert.Equal(EncodedDefaultTrailingHeaders, headerData);
}
// TODO: Add a test with trailing CONTINUATION frames
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task RespondingTrailersWithoutDataShouldThrowAnException(
bool isServer)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe);
var ex = await Assert.ThrowsAsync<Exception>(async () =>
await r.stream.WriteTrailersAsync(DefaultTrailingHeaders));
Assert.Equal("Attempted to write trailers without data", ex.Message);
}
[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public async Task ReceivingHeaders2TimesShouldTriggerAStreamReset(
bool isServer, bool headersAreEndOfStream)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
// Establish open streams, which means headers are sent in both
// directions
var res = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe);
// Write a second header
await inPipe.WriteHeaders(
res.hEncoder, 1, headersAreEndOfStream, DefaultGetHeaders);
await outPipe.AssertResetStreamReception(1, ErrorCode.ProtocolError);
Assert.Equal(StreamState.Reset, res.stream.State);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CancellingAStreamShouldSendAResetFrame(
bool isServer)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe);
r.stream.Cancel();
await outPipe.AssertResetStreamReception(1, ErrorCode.Cancel);
Assert.Equal(StreamState.Reset, r.stream.State);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task OutgoingDataShouldRespectMaxFrameSize(
bool isServer)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var r = await StreamCreator.CreateConnectionAndStream(
isServer, loggerProvider, inPipe, outPipe);
var dataSize = Settings.Default.MaxFrameSize + 10;
var writeTask = Task.Run(async () =>
{
var data = new byte[dataSize];
await r.stream.WriteAsync(new ArraySegment<byte>(data), true);
});
// Expect to receive the data in fragments
await outPipe.ReadAndDiscardData(1u, false, (int)Settings.Default.MaxFrameSize);
await outPipe.ReadAndDiscardData(1u, true, 10);
var doneTask = await Task.WhenAny(writeTask, Task.Delay(250));
Assert.True(writeTask == doneTask, "Expected write task to finish");
}
[Theory]
[InlineData(true, 1u)]
[InlineData(true, 3u)]
[InlineData(true, 5u)]
public async Task ADataFrameOnAnUnknownStreamIdShouldTriggerAStreamReset(
bool isServer, uint streamId)
{
// TODO: Add test cases for clients
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
Func<IStream, bool> listener = (s) => true;
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
isServer, inPipe, outPipe, loggerProvider, listener);
// Establish a high stream ID, which means all below are invalid
var hEncoder = new Encoder();
var createdStreamId = 111u;
if (!isServer)
throw new Exception("For clients the stream must be created from connection");
await inPipe.WriteHeaders(
hEncoder, createdStreamId, false, DefaultGetHeaders);
await inPipe.WriteData(streamId, 0);
await outPipe.AssertResetStreamReception(streamId, ErrorCode.StreamClosed);
}
[Theory]
[InlineData(true, 1u)]
[InlineData(true, 2u)]
[InlineData(true, 3u)]
[InlineData(true, 4u)]
[InlineData(false, 1u)]
[InlineData(false, 2u)]
[InlineData(false, 3u)]
[InlineData(false, 4u)]
public async Task ADataFrameOnAnIdleStreamIdShouldTriggerAGoAway(
bool isServer, uint streamId)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
Func<IStream, bool> listener = (s) => true;
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
isServer, inPipe, outPipe, loggerProvider, listener);
await inPipe.WriteData(streamId, 0);
await outPipe.AssertGoAwayReception(ErrorCode.StreamClosed, 0u);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task HeadersOnStreamId0ShouldTriggerAGoAway(
bool isServer)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
Func<IStream, bool> listener = (s) => true;
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
isServer, inPipe, outPipe, loggerProvider, listener);
var hEncoder = new Encoder();
await inPipe.WriteHeaders(hEncoder, 0, false, DefaultGetHeaders);
await outPipe.AssertGoAwayReception(ErrorCode.ProtocolError, 0);
await outPipe.AssertStreamEnd();
}
[Theory]
[InlineData(true, 2)]
[InlineData(true, 4)]
[InlineData(false, 1)]
[InlineData(false, 3)]
public async Task HeadersOnStreamIdWhichCanNotBeRemoteInitiatedShouldTriggerAStreamReset(
bool isServer, uint streamId)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
Func<IStream, bool> listener = (s) => true;
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
isServer, inPipe, outPipe, loggerProvider, listener);
var hEncoder = new Encoder();
await inPipe.WriteHeaders(hEncoder, streamId, false, DefaultGetHeaders);
await outPipe.AssertResetStreamReception(streamId, ErrorCode.StreamClosed);
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate.Helpers;
using SDKTemplate.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Media.Core;
using Windows.Media.Protection;
using Windows.Media.Streaming.Adaptive;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
using Windows.Web.Http.Filters;
using Windows.Web.Http.Headers;
namespace SDKTemplate
{
/// See the README.md for discussion of this scenario.
///
/// Note: We register but do not unregister event handlers in this scenario, see the EventHandler
/// scenario for patterns that can be used to clean up.
public sealed partial class Scenario3_RequestModification : Page
{
public Scenario3_RequestModification()
{
this.InitializeComponent();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
ctsForAppHttpClientForKeys.Cancel(); // Cancel any HTTP requests the app was making.
adaptiveMS = null;
var mp = mediaPlayerElement.MediaPlayer;
if (mp != null)
{
mp.DisposeSource();
mediaPlayerElement.SetMediaPlayer(null);
mp.Dispose();
}
// We will clean up HDCP explicitly, this ensures the OutputProtectionManager
// does not have to continue to impose our policy until the Garbage Collector
// cleans the object.
hdcpSession?.Dispose();
hdcpSession = null;
}
AdaptiveContentModel adaptiveContentModel;
AddAuthorizationHeaderFilter httpClientFilter;
HdcpSession hdcpSession;
AdaptiveMediaSource adaptiveMS;
private void Page_OnLoaded(object sender, RoutedEventArgs e)
{
// We enforce HDCP in this scenario that uses encryption but not PlayReady.
hdcpSession = new HdcpSession();
// The protection level may change if screens are plugged or unplugged from the system or
// if explicitly set in the radio buttons in the UI.
hdcpSession.ProtectionChanged += (HdcpSession session, object args) =>
{
// After a change, impose a maximum bitrate based on the actual protection level.
HdcpProtection? protection = session.GetEffectiveProtection();
SetMaxBitrateForProtectionLevel(protection, adaptiveMS);
};
// Choose a default content, and tell the user that some content IDs
// require an authorization mode. Filter out the PlayReady content
// because this scenario does not support PlayReady.
SelectedContent.ItemsSource = MainPage.ContentManagementSystemStub.Where(model => !model.PlayReady);
SelectedContent.SelectedItem = MainPage.FindContentById(13);
// Initialize tokenMethod based on the default selected radio button.
var defaultRadioButton = AzureAuthorizationMethodPanel.Children.OfType<RadioButton>().First(button => button.IsChecked.Value);
Enum.TryParse((string)defaultRadioButton.Tag, out tokenMethod);
Log("Content Id 13 and 14 require that you choose an authorization method.");
}
private async void Load_Click(object sender, RoutedEventArgs e)
{
adaptiveContentModel = (AdaptiveContentModel)SelectedContent.SelectedItem;
if (tokenMethod == AzureKeyAcquisitionMethod.AuthorizationHeader)
{
// Use an IHttpFilter to identify key request URIs and insert an Authorization header with the Bearer token.
var baseProtocolFilter = new HttpBaseProtocolFilter();
httpClientFilter = new AddAuthorizationHeaderFilter(baseProtocolFilter);
httpClientFilter.AuthorizationHeader = new HttpCredentialsHeaderValue("Bearer", adaptiveContentModel.AesToken);
var httpClient = new HttpClient(httpClientFilter);
// Here is where you can add any required custom CDN headers.
httpClient.DefaultRequestHeaders.Append("X-HeaderKey", "HeaderValue");
// NOTE: It is not recommended to set Authorization headers needed for key request on the
// default headers of the HttpClient, as these will also be used on non-HTTPS calls
// for media segments and manifests -- and thus will be easily visible.
await LoadSourceFromUriAsync(adaptiveContentModel.ManifestUri, httpClient);
}
else
{
await LoadSourceFromUriAsync(adaptiveContentModel.ManifestUri);
}
// On small screens, hide the description text to make room for the video.
DescriptionText.Visibility = (ActualHeight < 650) ? Visibility.Collapsed : Visibility.Visible;
}
private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
{
mediaPlayerElement.MediaPlayer?.DisposeSource();
AdaptiveMediaSourceCreationResult result = null;
if (httpClient != null)
{
result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
}
else
{
result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
}
if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
{
adaptiveMS = result.MediaSource;
// Register for events before setting the IMediaPlaybackSource
RegisterForAdaptiveMediaSourceEvents(adaptiveMS);
// Now that we have bitrates, attempt to cap them based on HdcpProtection.
HdcpProtection? protection = hdcpSession.GetEffectiveProtection();
SetMaxBitrateForProtectionLevel(protection, adaptiveMS);
MediaSource source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMS);
// Note that in this sample with very few event handlers, we are creating neither
// a MediaPlayer nor a MediaPlaybackItem. The MediaPlayer will be created implicitly
// by the mpElement, which will also manage its lifetime.
mediaPlayerElement.Source = source;
// You can now access mpElement.MediaPlayer, but it is too late to register
// to handle its MediaOpened event.
}
else
{
Log($"Error creating the AdaptiveMediaSource: {result.Status}");
}
}
#region AdaptiveMediaSource Event Handlers
private void RegisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource aMS)
{
aMS.DownloadRequested += DownloadRequested;
aMS.DownloadFailed += DownloadFailed;
}
private async void DownloadRequested(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadRequestedEventArgs args)
{
if (args.ResourceType == AdaptiveMediaSourceResourceType.Key)
{
switch (tokenMethod)
{
case AzureKeyAcquisitionMethod.None:
break;
case AzureKeyAcquisitionMethod.AuthorizationHeader:
// By updating the IHttpFilter KeyHost property here, we ensure it's up to date
// before the network request is made. It is the IHttpFilter that will insert
// the Authorization header.
if (httpClientFilter != null)
{
httpClientFilter.KeyHost = args.ResourceUri.Host;
}
break;
case AzureKeyAcquisitionMethod.UrlQueryParameter:
ModifyKeyRequestUri(args);
break;
case AzureKeyAcquisitionMethod.ApplicationDownloaded:
await AppDownloadedKeyRequest(args);
break;
default:
break;
}
}
}
private void ModifyKeyRequestUri(AdaptiveMediaSourceDownloadRequestedEventArgs args)
{
if (adaptiveContentModel == null)
{
return;
}
// This pattern can be used to modify Uris, for example:
// To a redirect traffic to a secondary endpoint
// To change an segment request into a byte-range Uri into another resource
// Add the Bearer token to the Uri and modify the args.Result.ResourceUri
string armoredAuthToken = System.Net.WebUtility.UrlEncode("Bearer=" + adaptiveContentModel.AesToken);
string uriWithTokenParameter = $"{args.ResourceUri.AbsoluteUri}&token={armoredAuthToken}";
args.Result.ResourceUri = new Uri(uriWithTokenParameter);
}
private async Task AppDownloadedKeyRequest(AdaptiveMediaSourceDownloadRequestedEventArgs args)
{
if (adaptiveContentModel == null)
{
return;
}
// For AzureKeyAcquisitionMethod.ApplicationDownloaded we do the following:
// Call .GetDeferral() to allow asynchronous work to be performed
// Get the requested network resource using app code
// Set .Result.InputStream or .Result.Buffer with the response data
// Complete the deferral to indicate that we are done.
// With this pattern, the app has complete control over any downloaded content.
// Obtain a deferral so we can perform asynchronous operations.
var deferral = args.GetDeferral();
try
{
var appHttpClientForKeys = new HttpClient();
appHttpClientForKeys.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", adaptiveContentModel.AesToken);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, args.ResourceUri);
HttpResponseMessage response = await appHttpClientForKeys.SendRequestAsync(
request, HttpCompletionOption.ResponseHeadersRead).AsTask(ctsForAppHttpClientForKeys.Token);
if (response.IsSuccessStatusCode)
{
args.Result.InputStream = await response.Content.ReadAsInputStreamAsync();
// Alternatively, we could use:
// args.Result.Buffer = await response.Content.ReadAsBufferAsync();
}
else
{
// The app code failed. Report this by setting the args.Result.ExtendedStatus.
// This will ensure that the AdaptiveMediaSource does not attempt to download the resource
// itself, and instead treats the download as having failed.
switch (response.StatusCode)
{
case HttpStatusCode.Unauthorized:
// HTTP_E_STATUS_DENIED
args.Result.ExtendedStatus = 0x80190191;
break;
case HttpStatusCode.NotFound:
// HTTP_E_STATUS_NOT_FOUND
args.Result.ExtendedStatus = 0x80190194;
break;
default:
// HTTP_E_STATUS_UNEXPECTED
args.Result.ExtendedStatus = 0x80190001;
break;
}
Log($"Key Download Failed: {response.StatusCode} {args.ResourceUri}");
}
}
catch (TaskCanceledException)
{
Log($"Request canceled: {args.ResourceUri}");
}
catch (Exception e)
{
Log($"Key Download Failed: {e.Message} {args.ResourceUri}");
}
finally
{
// Complete the deferral when done.
deferral.Complete();
}
}
private void DownloadFailed(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadFailedEventArgs args)
{
Log($"DownloadFailed: {args.HttpResponseMessage}, {args.ResourceType}, {args.ResourceUri}");
}
#endregion
#region AzureKeyAcquisitionMethod
enum AzureKeyAcquisitionMethod
{
None,
AuthorizationHeader,
UrlQueryParameter,
ApplicationDownloaded,
}
private AzureKeyAcquisitionMethod tokenMethod;
private CancellationTokenSource ctsForAppHttpClientForKeys = new CancellationTokenSource();
private void AzureMethodSelected_Click(object sender, RoutedEventArgs e)
{
AzureKeyAcquisitionMethod selectedMethod;
string selected = (sender as RadioButton).Tag.ToString();
if (Enum.TryParse(selected, out selectedMethod))
{
tokenMethod = selectedMethod;
}
}
#endregion
#region HdcpDesiredMinimumProtection
/// <summary>
/// Handles the radio button selections from the UI and imposes that minimum desired protection
/// </summary>
private async void HdcpDesiredMinimumProtection_Click(object sender, RoutedEventArgs e)
{
HdcpProtection desiredMinimumProtection = HdcpProtection.Off;
string selected = (sender as RadioButton).Tag.ToString();
if (Enum.TryParse(selected, out desiredMinimumProtection))
{
var result = await hdcpSession.SetDesiredMinProtectionAsync(desiredMinimumProtection);
HdcpProtection? actualProtection = hdcpSession.GetEffectiveProtection();
if (result != HdcpSetProtectionResult.Success)
{
Log($"ERROR: Unable to set HdcpProtection.{desiredMinimumProtection}, Error: {result}, Actual HDCP: {actualProtection}");
}
else
{
Log($"HDCP Requested Minimum: {desiredMinimumProtection}, Actual: {actualProtection}");
}
}
}
/// <summary>
/// Enforces a fictitious content publisher's rules for bandwidth maximums based on HDCP protection levels.
/// </summary>
/// <param name="protection">Protection level to use when imposing bandwidth restriction.</param>
/// <param name="ams">AdaptiveMediaSource on which to impose restrictions</param>
private void SetMaxBitrateForProtectionLevel(HdcpProtection? protection, AdaptiveMediaSource ams)
{
EffectiveHdcpProtectionText.Text = protection.ToString();
if (ams != null && ams.AvailableBitrates.Count > 1)
{
// Get a sorted list of available bitrates.
var bitrates = new List<uint>(ams.AvailableBitrates);
bitrates.Sort();
// Apply maximum bitrate policy based on a fictitious content publisher's rules.
switch (protection)
{
case HdcpProtection.OnWithTypeEnforcement:
// Allow full bitrate.
ams.DesiredMaxBitrate = bitrates[bitrates.Count - 1];
DesiredMaxBitrateText.Text = "full bitrate allowed";
break;
case HdcpProtection.On:
// When there is no HDCP Type 1, make the highest bitrate unavailable.
ams.DesiredMaxBitrate = bitrates[bitrates.Count - 2];
DesiredMaxBitrateText.Text = "highest bitrate is unavailable";
break;
case HdcpProtection.Off:
case null:
default:
// When there is no HDCP at all (Off), or the system is still trying to determine what
// HDCP protection level to apply (null), then make only the lowest bitrate available.
ams.DesiredMaxBitrate = bitrates[0];
DesiredMaxBitrateText.Text = "lowest bitrate only";
break;
}
Log($"Imposed DesiredMaxBitrate={ams.DesiredMaxBitrate} for HdcpProtection.{protection}");
}
}
#endregion
#region Utilities
private void Log(string message)
{
LoggerControl.Log(message);
}
#endregion
}
#region IHttpFilter to add an authorization header
public class AddAuthorizationHeaderFilter : IHttpFilter
{
public AddAuthorizationHeaderFilter(IHttpFilter innerFilter)
{
if (innerFilter == null)
{
throw new ArgumentException("innerFilter cannot be null.");
}
this.innerFilter = innerFilter;
}
internal HttpCredentialsHeaderValue AuthorizationHeader;
private IHttpFilter innerFilter;
// NOTE: In production, an app might need logic for several failover key-delivery hosts.
public string KeyHost { get; set; }
public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
{
bool isKeyRequest = String.Equals(request.RequestUri.Host, KeyHost, StringComparison.OrdinalIgnoreCase);
if (isKeyRequest && AuthorizationHeader != null)
{
request.Headers.Authorization = AuthorizationHeader;
}
return innerFilter.SendRequestAsync(request);
}
public void Dispose()
{
}
}
#endregion
}
| |
// CodeContracts
//
// 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.Contracts;
namespace System.Reflection.Emit
{
public class TypeBuilder
{
public string FullName
{
get;
}
public Type ReflectedType
{
get;
}
public System.Reflection.Assembly Assembly
{
get;
}
public PackingSize PackingSize
{
get;
}
public Type UnderlyingSystemType
{
get;
}
public int Size
{
get;
}
public Type DeclaringType
{
get;
}
public RuntimeTypeHandle TypeHandle
{
get;
}
public TypeToken TypeToken
{
get;
}
public Type BaseType
{
get;
}
public string Name
{
get;
}
public Guid GUID
{
get;
}
public string Namespace
{
get;
}
public string AssemblyQualifiedName
{
get;
}
public System.Reflection.Module Module
{
get;
}
public void SetCustomAttribute (CustomAttributeBuilder customBuilder) {
Contract.Requires(customBuilder != null);
}
public void SetCustomAttribute (System.Reflection.ConstructorInfo con, Byte[] binaryAttribute) {
Contract.Requires(con != null);
Contract.Requires(binaryAttribute != null);
}
public bool IsDefined (Type attributeType, bool inherit) {
return default(bool);
}
public Object[] GetCustomAttributes (Type attributeType, bool inherit) {
Contract.Requires(attributeType != null);
return default(Object[]);
}
public Object[] GetCustomAttributes (bool inherit) {
return default(Object[]);
}
public bool IsSubclassOf (Type c) {
return default(bool);
}
public Type GetElementType () {
return default(Type);
}
public bool IsAssignableFrom (Type c) {
return default(bool);
}
public System.Reflection.MemberInfo[] GetMembers (System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.MemberInfo[]);
}
public System.Reflection.EventInfo[] GetEvents (System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.EventInfo[]);
}
public System.Reflection.InterfaceMapping GetInterfaceMap (Type interfaceType) {
return default(System.Reflection.InterfaceMapping);
}
public System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.MemberInfo[]);
}
public Type GetNestedType (string name, System.Reflection.BindingFlags bindingAttr) {
return default(Type);
}
public Type[] GetNestedTypes (System.Reflection.BindingFlags bindingAttr) {
return default(Type[]);
}
public System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.PropertyInfo[]);
}
public System.Reflection.EventInfo[] GetEvents () {
return default(System.Reflection.EventInfo[]);
}
public System.Reflection.EventInfo GetEvent (string name, System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.EventInfo);
}
public Type[] GetInterfaces () {
return default(Type[]);
}
public Type GetInterface (string name, bool ignoreCase) {
return default(Type);
}
public System.Reflection.FieldInfo[] GetFields (System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.FieldInfo[]);
}
public System.Reflection.FieldInfo GetField (string name, System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.FieldInfo);
}
public System.Reflection.MethodInfo[] GetMethods (System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.MethodInfo[]);
}
public System.Reflection.ConstructorInfo[] GetConstructors (System.Reflection.BindingFlags bindingAttr) {
return default(System.Reflection.ConstructorInfo[]);
}
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, Object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, String[] namedParameters) {
return default(object);
}
public void AddDeclarativeSecurity (System.Security.Permissions.SecurityAction action, System.Security.PermissionSet pset) {
}
public TypeBuilder DefineNestedType (string name, System.Reflection.TypeAttributes attr, Type parent, PackingSize packSize) {
return default(TypeBuilder);
}
public TypeBuilder DefineNestedType (string name, System.Reflection.TypeAttributes attr, Type parent, int typeSize) {
return default(TypeBuilder);
}
public TypeBuilder DefineNestedType (string name, System.Reflection.TypeAttributes attr) {
return default(TypeBuilder);
}
public TypeBuilder DefineNestedType (string name, System.Reflection.TypeAttributes attr, Type parent) {
return default(TypeBuilder);
}
public TypeBuilder DefineNestedType (string name, System.Reflection.TypeAttributes attr, Type parent, Type[] interfaces) {
return default(TypeBuilder);
}
public TypeBuilder DefineNestedType (string name) {
return default(TypeBuilder);
}
public FieldBuilder DefineUninitializedData (string name, int size, System.Reflection.FieldAttributes attributes) {
return default(FieldBuilder);
}
public FieldBuilder DefineInitializedData (string name, Byte[] data, System.Reflection.FieldAttributes attributes) {
return default(FieldBuilder);
}
public FieldBuilder DefineField (string fieldName, Type type, System.Reflection.FieldAttributes attributes) {
return default(FieldBuilder);
}
public void DefineMethodOverride (System.Reflection.MethodInfo methodInfoBody, System.Reflection.MethodInfo methodInfoDeclaration) {
}
public Type CreateType () {
return default(Type);
}
public ConstructorBuilder DefineDefaultConstructor (System.Reflection.MethodAttributes attributes) {
return default(ConstructorBuilder);
}
public ConstructorBuilder DefineConstructor (System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type[] parameterTypes) {
return default(ConstructorBuilder);
}
public ConstructorBuilder DefineTypeInitializer () {
return default(ConstructorBuilder);
}
public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) {
return default(MethodBuilder);
}
public MethodBuilder DefinePInvokeMethod (string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) {
return default(MethodBuilder);
}
public EventBuilder DefineEvent (string name, System.Reflection.EventAttributes attributes, Type eventtype) {
return default(EventBuilder);
}
public PropertyBuilder DefineProperty (string name, System.Reflection.PropertyAttributes attributes, Type returnType, Type[] parameterTypes) {
return default(PropertyBuilder);
}
public MethodBuilder DefineMethod (string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
return default(MethodBuilder);
}
public MethodBuilder DefineMethod (string name, System.Reflection.MethodAttributes attributes, Type returnType, Type[] parameterTypes) {
return default(MethodBuilder);
}
public void AddInterfaceImplementation (Type interfaceType) {
Contract.Requires(interfaceType != null);
}
public void SetParent (Type parent) {
Contract.Requires(parent != null);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HTLib2.Bioinfo
{
public partial class Universe
{
public int Minimize_ConjugateGradient_AtomwiseUpdate(
List<ForceField.IForceField> frcflds
, double threshold = 0.001 // * threshold for forces.NormInf
, double? k = null // * step step
// 0.0001
, double max_atom_movement = 0.1 // * maximum atom movement
, int? max_iteration = null // null for the infinite iteration until converged
, bool[] atomsMovable = null // * selection of movable atoms
// move all atoms if (atomsMovable == null) or (atomsMovable[all] == true)
// move only atom whose (atomsMovable[id] == true)
, IMinimizeLogger logger = null // * write log
// = new MinimizeLogger_PrintEnergyForceMag()
, InfoPack extra = null // get extra information
, bool? doSteepDeescent = null // null or true for default
, HPack<double> optOutEnergy = null // optional output for final energy
, List<Vector> optOutForces = null // optional output for final force vectors
, HPack<double> optOutForcesNorm1 = null // optional output for norm of final force vectors
, HPack<double> optOutForcesNorm2 = null // optional output for norm of final force vectors
, HPack<double> optOutForcesNormInf = null // optional output for norm of final force vectors
)
{
if(doSteepDeescent == null)
doSteepDeescent = true;
if(k == null)
{
k = double.MaxValue;
foreach(ForceField.IForceField frcfld in frcflds)
{
double? kk = frcfld.GetDefaultMinimizeStep();
if(kk.HasValue)
k = Math.Min(k.Value, kk.Value);
}
}
int iter = 0;
// 0. Initial configuration of atoms
Vector[] coords = GetCoords();
if(atomsMovable == null)
{
atomsMovable = new bool[size];
for(int i=0; i<size; i++)
atomsMovable[i] = true;
}
Vectors h = GetVectorsZero();
Vectors forces = Vector.NewVectors(size, new double[3]);
Vectors moves = Vector.NewVectors(size, new double[3]);
Nonbondeds_v1 nonbondeds = null;
// Dictionary<string,object> cache = new Dictionary<string, object>();
double energy = GetPotentialUpdated(frcflds, null, null, null, coords, forces, ref nonbondeds);
double forces_NormInf = NormInf(forces, atomsMovable);
double forces_Norm1 = Norm(1, forces, atomsMovable);
double forces_Norm2 = Norm(2, forces, atomsMovable);
Vector[] forces0 = forces;
double energy0 = energy;
Vectors moves0 = moves;
double leastMove = 0.000001;
while(true)
{
if(forces.IsComputable == false)
{
System.Console.Error.WriteLine("non-computable components while doing steepest-descent");
HEnvironment.Exit(0);
}
if(logger != null)
{
logger.log(iter, coords, energy, forces, atomsMovable);
logger.logTrajectory(this, iter, coords);
}
// 1. Save the position of atoms
// 2. Calculate the potential energy of system and the net forces on atoms
// 3. Check if every force reaches to zero,
// , and END if yes
bool stopIteration = false;
if(forces_NormInf < threshold) stopIteration = true;
if((max_iteration != null) && (iter>=max_iteration.Value)) stopIteration = true;
if(stopIteration)
{
// double check
//cache = new Dictionary<string, object>(); // reset cache
//energy = GetPotential(frcflds, coords, out forces, cache);
nonbondeds = null;
energy = GetPotentialUpdated(frcflds, null, null, null, coords, forces, ref nonbondeds);
forces_NormInf = NormInf(forces, atomsMovable);
forces_Norm1 = Norm(1, forces, atomsMovable);
forces_Norm2 = Norm(2, forces, atomsMovable);
if(forces_NormInf < threshold)
{
if(iter != 1)
{
SetCoords(coords);
}
{
if(optOutEnergy != null) optOutEnergy.value = energy;
if(optOutForces != null) {optOutForces.Clear(); optOutForces.AddRange(forces.ToArray()); }
if(optOutForcesNorm1 != null) optOutForcesNorm1 .value = forces_Norm1 ;
if(optOutForcesNorm2 != null) optOutForcesNorm2 .value = forces_Norm2 ;
if(optOutForcesNormInf != null) optOutForcesNormInf.value = forces_NormInf;
}
return iter;
}
}
// 4. Move atoms with conjugated gradient
Vectors coords_prd;
double kk;
{
if((iter > 0) && (iter % 100 == 0))
{
//cache = new Dictionary<string, object>(); // reset cache
nonbondeds = null;
}
if(iter > 1)
{
HDebug.Assert(forces0 != null);
double r = Vectors.VtV(forces, forces).Sum() / Vectors.VtV(forces0, forces0).Sum();
h = forces + r * h;
kk = k.Value;
double hNormInf = NormInf(h, atomsMovable);
if(kk*hNormInf > max_atom_movement)
// make the maximum movement as atomsMovable
kk = max_atom_movement/(hNormInf);
moves = moves0.Clone();
coords_prd = AddConditional(coords, atomsMovable, moves, kk * h, leastMove);
}
else
{
// same to the steepest descent for the first iteration
h = forces;
kk = k.Value;
double hNormInf = NormInf(h, atomsMovable);
if(kk*hNormInf > max_atom_movement)
// make the maximum movement as atomsMovable
kk = max_atom_movement/(hNormInf);
//double kk = (k*h.NormsInf().NormInf() < max_atom_movement) ? k : (max_atom_movement/h.NormsInf().NormInf());
//double kk = (k.Value*NormInf(h,atomsMovable) < max_atom_movement)? k.Value : (max_atom_movement/NormInf(h, atomsMovable));
moves = moves0.Clone();
coords_prd = AddConditional(coords, atomsMovable, moves, kk * h, leastMove);
}
}
// 5. Predict energy or forces on atoms
Vectors forces_prd = forces.Clone();
double energy_prd = GetPotentialUpdated(frcflds, energy, coords, forces, coords_prd, forces_prd, ref nonbondeds); iter++;
//double energy_prd = GetPotential(frcflds, coords_prd, out forces_prd, cache); iter++;
double forces_prd_NormInf = NormInf(forces_prd, atomsMovable);
double forces_prd_Norm1 = Norm(1, forces_prd, atomsMovable);
double forces_prd_Norm2 = Norm(2, forces_prd, atomsMovable);
// 6. Check if the predicted forces or energy will exceed over the limit
// , and goto 1 if no
doSteepDeescent = true;
//if((doSteepDeescent == false) || ((energy_prd <= energy) && (forces_prd_NormInf < forces_NormInf+1.0))
if((energy_prd < energy+0.1) && (forces_prd_NormInf < forces_NormInf+0.0001))
{
energy0 = energy;
forces0 = forces;
moves0 = moves;
coords = coords_prd;
forces = forces_prd;
energy = energy_prd;
forces_NormInf = forces_prd_NormInf;
forces_Norm1 = forces_prd_Norm1;
forces_Norm2 = forces_prd_Norm2;
continue;
}
if(logger != null)
logger.log(iter, coords_prd, energy_prd, forces_prd, atomsMovable, "will do steepest");
// 7. Back to saved configuration
// 8. Move atoms with simple gradient
{
// same to the steepest descent
h = forces;
kk = k.Value;
double hNormInf = NormInf(h, atomsMovable);
if(kk*hNormInf > max_atom_movement)
// make the maximum movement as atomsMovable
kk = max_atom_movement/(hNormInf);
moves = moves0.Clone();
coords_prd = AddConditional(coords, atomsMovable, moves, kk * h, leastMove);
}
//energy_prd = GetPotential(frcflds, coords_prd, out forces_prd, cache);
energy_prd = GetPotentialUpdated(frcflds, energy, coords, forces, coords_prd, forces_prd, ref nonbondeds);
forces_prd_NormInf = NormInf(forces_prd, atomsMovable);
forces_prd_Norm1 = Norm(1, forces_prd, atomsMovable);
forces_prd_Norm2 = Norm(2, forces_prd, atomsMovable);
energy0 = energy;
forces0 = forces;
moves0 = moves;
coords = coords_prd;
forces = forces_prd;
energy = energy_prd;
forces_NormInf = forces_prd_NormInf;
forces_Norm1 = forces_prd_Norm1;
forces_Norm2 = forces_prd_Norm2;
// 9. goto 1
}
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace DotSpatial.Data
{
/// <summary>
/// Numbers are based on the old school dbf definitions of data formats, and so can only store
/// a very limited range of values.
/// </summary>
public class NumberConverter
{
#region Fields
/// <summary>
/// Numbers can contain ASCII text up till 18 characters long, but no longer.
/// </summary>
public const int MaximumLength = 18;
/// <summary>
/// Format provider to use to convert DBF numbers to strings and characters
/// </summary>
public static readonly IFormatProvider NumberConversionFormatProvider = CultureInfo.GetCultureInfo("en-US");
private static readonly Random Rnd = new Random();
private int _decimalCount; // when the number is treated like a string, this is the number of recorded values after the decimal, plus one digit in front of the decimal.
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="NumberConverter"/> class.
/// Creates a new instance of NumberConverter where the length and decimal count are known.
/// </summary>
/// <param name="inLength">The length.</param>
/// <param name="inDecimalCount">The decimal count.</param>
public NumberConverter(int inLength, int inDecimalCount)
{
Length = inLength;
_decimalCount = inDecimalCount;
if (Length < 4)
{
_decimalCount = 0;
}
else if (_decimalCount > Length - 3)
{
_decimalCount = Length - 3;
}
UpdateDecimalFormatString();
}
/// <summary>
/// Initializes a new instance of the <see cref="NumberConverter"/> class.
/// Cycles through the numeric values in the specified column and determines a selection of
/// length and decimal count can accurately store the data.
/// </summary>
/// <param name="values">The values.</param>
/// <exception cref="NumberException">If the value was to small or lage to be encode with 18 ASCII characters.</exception>
public NumberConverter(IList<double> values)
{
int maxExp = 0;
int minExp = 0;
foreach (double value in values)
{
int exp = (int)Math.Log10(Math.Abs(value));
if (exp > MaximumLength - 1)
{
throw new NumberException(string.Format(DataStrings.NumberException_TooLarge_S, value));
}
if (exp < -(MaximumLength - 1))
{
throw new NumberException(string.Format(DataStrings.NumberException_TooSmall_S, value));
}
if (exp > maxExp) maxExp = exp;
if (exp < minExp) minExp = exp;
if (exp < MaximumLength - 2) continue;
// If this happens, we know that we need all the characters for values greater than 1, so no characters are left
// for storing both the decimal itself and the numbers beyond the decimal.
Length = MaximumLength;
_decimalCount = 0;
UpdateDecimalFormatString();
return;
}
UpdateDecimalFormatString();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the decimal count to use for this number converter
/// </summary>
public int DecimalCount
{
get
{
return _decimalCount;
}
set
{
_decimalCount = value;
UpdateDecimalFormatString();
}
}
/// <summary>
/// Gets or sets the format string used to convert doubles, floats, and decimals to strings
/// </summary>
public string DecimalFormatString { get; set; }
/// <summary>
/// Gets or sets the length.
/// </summary>
public int Length { get; set; }
#endregion
#region Methods
/// <summary>
/// Converts from a string, or 0 if the parse failed.
/// </summary>
/// <param name="value">The string value to parse</param>
/// <returns>The parse result.</returns>
public double FromString(string value)
{
double result;
double.TryParse(value, out result);
return result;
}
/// <summary>
/// Creates a new random array of characters that represents a number and is constrained by the specified length and decimal count
/// </summary>
/// <param name="numDigits">The integer number of significant (non-zero) digits that should be created as part of the number.</param>
/// <returns>A character array of that matches the length and decimal count specified by this properties on this number converter</returns>
public char[] RandomChars(int numDigits)
{
if (numDigits > Length - 1)
{
numDigits = Length - 1; // crop digits to length (reserve one spot for negative sign)
}
else if (numDigits < Length - 2)
{
if (_decimalCount > 0 && numDigits >= _decimalCount) numDigits += 1; // extend digits by decimal
}
bool isNegative = Rnd.Next(0, 1) == 0;
char[] c = new char[Length];
// i represents the distance from the end, moving backwards
for (int i = 0; i < Length; i++)
{
if (_decimalCount > 0 && i == _decimalCount - 2)
{
c[i] = '.';
}
else if (i < numDigits)
{
c[i] = (char)Rnd.Next(48, 57);
}
else if (i < _decimalCount - 2)
{
c[i] = '0';
}
else
{
c[i] = ' ';
}
}
if (isNegative)
{
c[numDigits] = '-';
}
Array.Reverse(c);
return c;
}
/// <summary>
/// Creates a new, random decimal that is constrained by the specified length and decimal count.
/// </summary>
/// <returns>The created random decimal.</returns>
public decimal RandomDecimal()
{
string test = new string(RandomChars(16));
return decimal.Parse(test);
}
/// <summary>
/// Creates a new, random double that is constrained by the specified length and decimal count.
/// </summary>
/// <returns>The created random double.</returns>
public double RandomDouble()
{
string test = new string(RandomChars(14));
return double.Parse(test);
}
/// <summary>
/// Creates a new, random float that is constrained by the specified length and decimal count.
/// </summary>
/// <returns>A new float. Floats can only store about 8 digits of precision, so specifying a high </returns>
public float RandomFloat()
{
string test = new string(RandomChars(6));
return float.Parse(test);
}
/// <summary>
/// Converts the specified decimal value to a string that can be used for the number field
/// </summary>
/// <param name="number">The decimal value to convert to a string</param>
/// <returns>A string version of the specified number</returns>
public char[] ToChar(double number)
{
return ToCharInternal(number);
}
/// <summary>
/// Converts the specified decimal value to a string that can be used for the number field
/// </summary>
/// <param name="number">The decimal value to convert to a string</param>
/// <returns>A string version of the specified number</returns>
public char[] ToChar(float number)
{
return ToCharInternal(number);
}
/// <summary>
/// Converts the specified decimal value to a string that can be used for the number field
/// </summary>
/// <param name="number">The decimal value to convert to a string</param>
/// <returns>A string version of the specified number</returns>
public char[] ToChar(decimal number)
{
return ToCharInternal(number);
}
/// <summary>
/// Converts the specified double value to a string that can be used for the number field
/// </summary>
/// <param name="number">The double precision floating point value to convert to a string</param>
/// <returns>A string version of the specified number</returns>
public string ToString(double number)
{
return ToStringInternal(number);
}
/// <summary>
/// Converts the specified decimal value to a string that can be used for the number field
/// </summary>
/// <param name="number">The decimal value to convert to a string</param>
/// <returns>A string version of the specified number</returns>
public string ToString(decimal number)
{
return ToStringInternal(number);
}
/// <summary>
/// Converts the specified float value to a string that can be used for the number field
/// </summary>
/// <param name="number">The floating point value to convert to a string</param>
/// <returns>A string version of the specified number</returns>
public string ToString(float number)
{
return ToStringInternal(number);
}
/// <summary>
/// Compute and update the DecimalFormatString from the precision specifier
/// </summary>
public void UpdateDecimalFormatString()
{
string format = "{0:";
for (int i = 0; i < _decimalCount; i++)
{
if (i == 0) format = format + "0.";
format = format + "0";
}
DecimalFormatString = format + "}";
}
private char[] ToCharInternal(object number)
{
char[] c = new char[Length];
string str = string.Format(NumberConversionFormatProvider, DecimalFormatString, number);
if (str.Length >= Length)
{
for (int i = 0; i < Length; i++)
{
c[i] = str[i]; // keep the left characters, and chop off lesser characters
}
}
else
{
for (int i = 0; i < Length; i++)
{
int ci = i - (Length - str.Length);
c[i] = ci < 0 ? ' ' : str[ci];
}
}
return c;
}
private string ToStringInternal(object number)
{
var sb = new StringBuilder();
var str = string.Format(NumberConversionFormatProvider, DecimalFormatString, number);
for (var i = 0; i < Length - str.Length; i++)
{
sb.Append(' ');
}
sb.Append(str);
return sb.ToString();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Xunit;
#pragma warning disable 618
namespace System.Runtime.InteropServices.Tests
{
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Marshalling between VARIANT and Object is not supported in AppX")]
public class GetObjectForNativeVariantTests
{
[StructLayout(LayoutKind.Sequential)]
public struct Record
{
public IntPtr _record;
public IntPtr _recordInfo;
}
[StructLayout(LayoutKind.Explicit)]
public struct UnionTypes
{
[FieldOffset(0)] internal sbyte _i1;
[FieldOffset(0)] internal short _i2;
[FieldOffset(0)] internal int _i4;
[FieldOffset(0)] internal long _i8;
[FieldOffset(0)] internal byte _ui1;
[FieldOffset(0)] internal ushort _ui2;
[FieldOffset(0)] internal uint _ui4;
[FieldOffset(0)] internal ulong _ui8;
[FieldOffset(0)] internal int _int;
[FieldOffset(0)] internal uint _uint;
[FieldOffset(0)] internal float _r4;
[FieldOffset(0)] internal double _r8;
[FieldOffset(0)] internal long _cy;
[FieldOffset(0)] internal double _date;
[FieldOffset(0)] internal IntPtr _bstr;
[FieldOffset(0)] internal IntPtr _unknown;
[FieldOffset(0)] internal IntPtr _dispatch;
[FieldOffset(0)] internal int _error;
[FieldOffset(0)] internal IntPtr _pvarVal;
[FieldOffset(0)] internal IntPtr _byref;
[FieldOffset(0)] internal Record _record;
[FieldOffset(0)] internal IntPtr _parray;
}
[StructLayout(LayoutKind.Sequential)]
public struct TypeUnion
{
public ushort vt;
public ushort wReserved1;
public ushort wReserved2;
public ushort wReserved3;
public UnionTypes _unionTypes;
}
[StructLayout(LayoutKind.Explicit)]
public struct Variant
{
[FieldOffset(0)] public TypeUnion m_Variant;
[FieldOffset(0)] public decimal m_decimal;
public override string ToString() => "0x" + m_Variant.vt.ToString("X");
}
// Taken from wtypes.h
public const ushort VT_EMPTY = 0;
public const ushort VT_NULL = 1;
public const ushort VT_I2 = 2;
public const ushort VT_I4 = 3;
public const ushort VT_R4 = 4;
public const ushort VT_R8 = 5;
public const ushort VT_CY = 6;
public const ushort VT_DATE = 7;
public const ushort VT_BSTR = 8;
public const ushort VT_DISPATCH = 9;
public const ushort VT_ERROR = 10;
public const ushort VT_BOOL = 11;
public const ushort VT_VARIANT = 12;
public const ushort VT_UNKNOWN = 13;
public const ushort VT_DECIMAL = 14;
public const ushort VT_I1 = 16;
public const ushort VT_UI1 = 17;
public const ushort VT_UI2 = 18;
public const ushort VT_UI4 = 19;
public const ushort VT_I8 = 20;
public const ushort VT_UI8 = 21;
public const ushort VT_INT = 22;
public const ushort VT_UINT = 23;
public const ushort VT_VOID = 24;
public const ushort VT_HRESULT = 25;
public const ushort VT_PTR = 26;
public const ushort VT_SAFEARRAY = 27;
public const ushort VT_CARRAY = 28;
public const ushort VT_USERDEFINED = 29;
public const ushort VT_LPSTR = 30;
public const ushort VT_LPWSTR = 31;
public const ushort VT_RECORD = 36;
public const ushort VT_INT_PTR = 37;
public const ushort VT_UINT_PTR = 38;
public const ushort VT_FILETIME = 64;
public const ushort VT_BLOB = 65;
public const ushort VT_STREAM = 66;
public const ushort VT_STORAGE = 67;
public const ushort VT_STREAMED_OBJECT = 68;
public const ushort VT_STORED_OBJECT = 69;
public const ushort VT_BLOB_OBJECT = 70;
public const ushort VT_CF = 71;
public const ushort VT_CLSID = 72;
public const ushort VT_VERSIONED_STREAM = 73;
public const ushort VT_BSTR_BLOB = 0xfff;
public const ushort VT_VECTOR = 0x1000;
public const ushort VT_ARRAY = 0x2000;
public const ushort VT_BYREF = 0x4000;
public const ushort VT_RESERVED = 0x8000;
public const ushort VT_ILLEGAL = 0xffff;
public const ushort VT_ILLEGALMASKED = 0xfff;
public const ushort VT_TYPEMASK = 0xfff;
public static IEnumerable<object[]> GetObjectForNativeVariant_PrimitivesByRef_TestData()
{
// VT_NULL => null.
yield return new object[]
{
CreateVariant(VT_NULL, new UnionTypes { _byref = IntPtr.Zero }),
DBNull.Value
};
yield return new object[]
{
CreateVariant(VT_NULL, new UnionTypes { _byref = (IntPtr)10 }),
DBNull.Value
};
// VT_I2 => short.
yield return new object[]
{
CreateVariant(VT_I2, new UnionTypes { _i2 = 10 }),
(short)10
};
yield return new object[]
{
CreateVariant(VT_I2, new UnionTypes { _i2 = 0 }),
(short)0
};
yield return new object[]
{
CreateVariant(VT_I2, new UnionTypes { _i2 = -10 }),
(short)(-10)
};
// VT_I4 => int.
yield return new object[]
{
CreateVariant(VT_I4, new UnionTypes { _i4 = 10 }),
10
};
yield return new object[]
{
CreateVariant(VT_I4, new UnionTypes { _i4 = 0 }),
0
};
yield return new object[]
{
CreateVariant(VT_I4, new UnionTypes { _i4 = -10 }),
-10
};
// VT_R4 => float.
yield return new object[]
{
CreateVariant(VT_R4, new UnionTypes { _r4 = 10 }),
(float)10
};
yield return new object[]
{
CreateVariant(VT_R4, new UnionTypes { _r4 = 0 }),
(float)0
};
yield return new object[]
{
CreateVariant(VT_R4, new UnionTypes { _r4 = -10 }),
(float)(-10)
};
yield return new object[]
{
CreateVariant(VT_R4, new UnionTypes { _r4 = float.PositiveInfinity }),
float.PositiveInfinity
};
yield return new object[]
{
CreateVariant(VT_R4, new UnionTypes { _r4 = float.NegativeInfinity }),
float.NegativeInfinity
};
yield return new object[]
{
CreateVariant(VT_R4, new UnionTypes { _r4 = float.NaN }),
float.NaN
};
// VT_R8 => double.
yield return new object[]
{
CreateVariant(VT_R8, new UnionTypes { _r8 = 10 }),
(double)10
};
yield return new object[]
{
CreateVariant(VT_R8, new UnionTypes { _r8 = 0 }),
(double)0
};
yield return new object[]
{
CreateVariant(VT_R8, new UnionTypes { _r8 = -10 }),
(double)(-10)
};
yield return new object[]
{
CreateVariant(VT_R8, new UnionTypes { _r8 = double.PositiveInfinity }),
double.PositiveInfinity
};
yield return new object[]
{
CreateVariant(VT_R8, new UnionTypes { _r8 = double.NegativeInfinity }),
double.NegativeInfinity
};
yield return new object[]
{
CreateVariant(VT_R8, new UnionTypes { _r8 = double.NaN }),
double.NaN
};
// VT_CY => decimal.
yield return new object[]
{
CreateVariant(VT_CY, new UnionTypes { _cy = 200 }),
0.02m
};
yield return new object[]
{
CreateVariant(VT_CY, new UnionTypes { _cy = 0 }),
0m
};
yield return new object[]
{
CreateVariant(VT_CY, new UnionTypes { _cy = -200 }),
-0.02m
};
// VT_DATE => DateTime.
DateTime maxDate = DateTime.MaxValue;
yield return new object[]
{
CreateVariant(VT_DATE, new UnionTypes { _date = maxDate.ToOADate() }),
new DateTime(9999, 12, 31, 23, 59, 59, 999)
};
yield return new object[]
{
CreateVariant(VT_DATE, new UnionTypes { _date = 200 }),
new DateTime(1900, 07, 18)
};
yield return new object[]
{
CreateVariant(VT_DATE, new UnionTypes { _date = 0.5 }),
new DateTime(1899, 12, 30, 12, 0, 0)
};
yield return new object[]
{
CreateVariant(VT_DATE, new UnionTypes { _date = 0 }),
new DateTime(1899, 12, 30)
};
yield return new object[]
{
CreateVariant(VT_DATE, new UnionTypes { _date = -0.5 }),
new DateTime(1899, 12, 30, 12, 0, 0)
};
yield return new object[]
{
CreateVariant(VT_DATE, new UnionTypes { _date = -200 }),
new DateTime(1899, 06, 13)
};
DateTime minDate = new DateTime(100, 01, 01, 23, 59, 59, 999);
yield return new object[]
{
CreateVariant(VT_DATE, new UnionTypes { _date = minDate.ToOADate() }),
minDate
};
// VT_BSTR => string.
yield return new object[]
{
CreateVariant(VT_BSTR, new UnionTypes { _bstr = IntPtr.Zero }),
null
};
IntPtr emptyString = Marshal.StringToBSTR("");
yield return new object[]
{
CreateVariant(VT_BSTR, new UnionTypes { _bstr = emptyString }),
""
};
IntPtr oneLetterString = Marshal.StringToBSTR("a");
yield return new object[]
{
CreateVariant(VT_BSTR, new UnionTypes { _bstr = oneLetterString }),
"a"
};
IntPtr twoLetterString = Marshal.StringToBSTR("ab");
yield return new object[]
{
CreateVariant(VT_BSTR, new UnionTypes { _bstr = twoLetterString }),
"ab"
};
IntPtr embeddedNullString = Marshal.StringToBSTR("a\0c");
yield return new object[]
{
CreateVariant(VT_BSTR, new UnionTypes { _bstr = embeddedNullString }),
"a\0c"
};
// VT_DISPATCH => object.
yield return new object[]
{
CreateVariant(VT_DISPATCH, new UnionTypes { _dispatch = IntPtr.Zero }),
null
};
var obj = new object();
if (!PlatformDetection.IsNetCore)
{
IntPtr dispatch = Marshal.GetIDispatchForObject(obj);
yield return new object[]
{
CreateVariant(VT_DISPATCH, new UnionTypes { _dispatch = dispatch }),
obj
};
}
else
{
Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetIDispatchForObject(obj));
}
// VT_ERROR => int.
yield return new object[]
{
CreateVariant(VT_ERROR, new UnionTypes { _error = int.MaxValue }),
int.MaxValue
};
yield return new object[]
{
CreateVariant(VT_ERROR, new UnionTypes { _error = 0 }),
0
};
yield return new object[]
{
CreateVariant(VT_ERROR, new UnionTypes { _error = int.MinValue }),
int.MinValue
};
// VT_BOOL => bool.
yield return new object[]
{
CreateVariant(VT_BOOL, new UnionTypes { _i1 = 1 }),
true
};
yield return new object[]
{
CreateVariant(VT_BOOL, new UnionTypes { _i1 = 0 }),
false
};
yield return new object[]
{
CreateVariant(VT_BOOL, new UnionTypes { _i1 = -1 }),
true
};
// VT_UNKNOWN => object.
yield return new object[]
{
CreateVariant(VT_UNKNOWN, new UnionTypes { _unknown = IntPtr.Zero }),
null
};
IntPtr unknown = Marshal.GetIUnknownForObject(obj);
yield return new object[]
{
CreateVariant(VT_UNKNOWN, new UnionTypes { _unknown = unknown }),
obj
};
// VT_I1 => sbyte.
yield return new object[]
{
CreateVariant(VT_I1, new UnionTypes { _i1 = 10 }),
(sbyte)10
};
yield return new object[]
{
CreateVariant(VT_I1, new UnionTypes { _i1 = 0 }),
(sbyte)0
};
yield return new object[]
{
CreateVariant(VT_I1, new UnionTypes { _i1 = -10 }),
(sbyte)(-10)
};
// VT_UI1 => byte.
yield return new object[]
{
CreateVariant(VT_UI1, new UnionTypes { _ui1 = 10 }),
(byte)10
};
yield return new object[]
{
CreateVariant(VT_UI1, new UnionTypes { _ui1 = 0 }),
(byte)0
};
// VT_UI2 => ushort.
yield return new object[]
{
CreateVariant(VT_UI2, new UnionTypes { _ui2 = 10 }),
(ushort)10
};
yield return new object[]
{
CreateVariant(VT_UI2, new UnionTypes { _ui2 = 0 }),
(ushort)0
};
// VT_UI4 => uint.
yield return new object[]
{
CreateVariant(VT_UI4, new UnionTypes { _ui4 = 10 }),
(uint)10
};
yield return new object[]
{
CreateVariant(VT_UI4, new UnionTypes { _ui4 = 0 }),
(uint)0
};
// VT_I8 => long.
yield return new object[]
{
CreateVariant(VT_I8, new UnionTypes { _i8 = 10 }),
(long)10
};
yield return new object[]
{
CreateVariant(VT_I8, new UnionTypes { _i8 = 0 }),
(long)0
};
yield return new object[]
{
CreateVariant(VT_I8, new UnionTypes { _i8 = -10 }),
(long)(-10)
};
// VT_UI8 => ulong.
yield return new object[]
{
CreateVariant(VT_UI8, new UnionTypes { _ui8 = 10 }),
(ulong)10
};
yield return new object[]
{
CreateVariant(VT_UI8, new UnionTypes { _ui8 = 0 }),
(ulong)0
};
// VT_INT => int.
yield return new object[]
{
CreateVariant(VT_INT, new UnionTypes { _int = 10 }),
10
};
yield return new object[]
{
CreateVariant(VT_INT, new UnionTypes { _int = 0 }),
0
};
yield return new object[]
{
CreateVariant(VT_INT, new UnionTypes { _int = -10 }),
-10
};
// VT_UINT => uint.
yield return new object[]
{
CreateVariant(VT_UINT, new UnionTypes { _uint = 10 }),
(uint)10
};
yield return new object[]
{
CreateVariant(VT_UINT, new UnionTypes { _uint = 0 }),
(uint)0
};
// VT_VOID => null.
yield return new object[]
{
CreateVariant(VT_VOID, new UnionTypes()),
null
};
}
public static IEnumerable<object[]> GetObjectForNativeVariant_TestData()
{
// VT_EMPTY => null.
yield return new object[]
{
CreateVariant(VT_EMPTY, new UnionTypes { _byref = IntPtr.Zero }),
null
};
yield return new object[]
{
CreateVariant(VT_EMPTY, new UnionTypes { _byref = (IntPtr)10 }),
null
};
// VT_EMPTY | VT_BYREF => zero.
object expectedZero;
if (IntPtr.Size == 8)
{
expectedZero = (ulong)0;
}
else
{
expectedZero = (uint)0;
}
yield return new object[]
{
CreateVariant(VT_EMPTY | VT_BYREF, new UnionTypes { _byref = IntPtr.Zero }),
expectedZero
};
object expectedTen;
if (IntPtr.Size == 8)
{
expectedTen = (ulong)10;
}
else
{
expectedTen = (uint)10;
}
yield return new object[]
{
CreateVariant(VT_EMPTY | VT_BYREF, new UnionTypes { _byref = (IntPtr)10 }),
expectedTen
};
// VT_RECORD.
yield return new object[]
{
CreateVariant(VT_RECORD, new UnionTypes { _record = new Record { _record = IntPtr.Zero, _recordInfo = (IntPtr)1 } }),
null
};
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_PrimitivesByRef_TestData))]
[MemberData(nameof(GetObjectForNativeVariant_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_Normal_ReturnsExpected(Variant variant, object expected)
{
try
{
Assert.Equal(expected, GetObjectForNativeVariant(variant));
}
finally
{
DeleteVariant(variant);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_ErrorMissing_ReturnsTypeMissing()
{
// This cannot be in the [MemberData] as XUnit uses reflection to invoke the test method
// and Type.Missing is handled specially by the runtime.
GetObjectForNativeVariant_Normal_ReturnsExpected(CreateVariant(VT_ERROR, new UnionTypes { _error = unchecked((int)0x80020004) }), Type.Missing);
}
public static IEnumerable<object[]> GetObjectForNativeVariant_Decimal_TestData()
{
// VT_DECIMAL => decimal.
yield return new object[] { 10.5m };
yield return new object[] { 10m };
yield return new object[] { 0m };
yield return new object[] { -10m };
yield return new object[] { -10.5m };
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_Decimal_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_Decimal_ReturnsExpected(decimal d)
{
var variant = new Variant { m_decimal = d };
variant.m_Variant.vt = VT_DECIMAL;
Assert.Equal(d, GetObjectForNativeVariant(variant));
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_PrimitivesByRef_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_NestedVariant_ReturnsExpected(Variant source, object expected)
{
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf<Variant>());
try
{
Marshal.StructureToPtr(source, ptr, fDeleteOld: false);
Variant variant = CreateVariant(VT_VARIANT | VT_BYREF, new UnionTypes { _pvarVal = ptr });
Assert.Equal(expected, GetObjectForNativeVariant(variant));
}
finally
{
DeleteVariant(source);
Marshal.DestroyStructure<Variant>(ptr);
Marshal.FreeHGlobal(ptr);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[ActiveIssue(31480, TargetFrameworkMonikers.Netcoreapp)]
public void GetObjectForNativeVariant_Record_ReturnsExpected()
{
int record = 10;
var recordInfo = new RecordInfo { Guid = typeof(int).GUID };
IntPtr pRecord = Marshal.AllocHGlobal(Marshal.SizeOf<int>());
IntPtr pRecordInfo = Marshal.GetComInterfaceForObject<RecordInfo, IRecordInfo>(recordInfo);
try
{
Marshal.StructureToPtr(record, pRecord, fDeleteOld: false);
Variant variant = CreateVariant(VT_RECORD, new UnionTypes
{
_record = new Record
{
_record = pRecord,
_recordInfo = pRecordInfo
}
});
Assert.Equal(10, GetObjectForNativeVariant(variant));
GetObjectForNativeVariant_NestedVariant_ReturnsExpected(variant, record);
variant.m_Variant.vt |= VT_BYREF;
Assert.Equal(10, GetObjectForNativeVariant(variant));
}
finally
{
Marshal.DestroyStructure<int>(pRecord);
Marshal.FreeHGlobal(pRecord);
Marshal.Release(pRecordInfo);
}
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_PrimitivesByRef_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public unsafe void GetObjectForNativeVariant_ByRef_ReturnsExpected(Variant source, object value)
{
try
{
IntPtr ptr = new IntPtr(&source.m_Variant._unionTypes);
var variant = new Variant();
variant.m_Variant.vt = (ushort)(source.m_Variant.vt | VT_BYREF);
variant.m_Variant._unionTypes._byref = ptr;
Assert.Equal(value, GetObjectForNativeVariant(variant));
}
finally
{
DeleteVariant(source);
}
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_Decimal_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public unsafe void GetObjectForNativeVariant_DecimalByRef_Success(decimal d)
{
IntPtr ptr = new IntPtr(&d);
Variant variant = CreateVariant(VT_DECIMAL | VT_BYREF, new UnionTypes { _pvarVal = ptr });
Assert.Equal(d, GetObjectForNativeVariant(variant));
}
public static IEnumerable<object[]> GetObjectForNativeVariant_Array_TestData()
{
yield return new object[]
{
CreateVariant(VT_ARRAY, new UnionTypes { _parray = IntPtr.Zero }),
null
};
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_Array_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_Array_ReturnsExpected(Variant source, object expected)
{
Assert.Equal(expected, GetObjectForNativeVariant(source));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void GetObjectForNativeVariant_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetObjectForNativeVariant(IntPtr.Zero));
Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetObjectForNativeVariant<int>(IntPtr.Zero));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_ZeroPointer_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("pSrcNativeVariant", () => Marshal.GetObjectForNativeVariant(IntPtr.Zero));
AssertExtensions.Throws<ArgumentNullException>("pSrcNativeVariant", () => Marshal.GetObjectForNativeVariant<int>(IntPtr.Zero));
}
[Theory]
[InlineData(VT_I2 | VT_BYREF)]
[InlineData(VT_UI2 | VT_BYREF)]
[InlineData(VT_I4 | VT_BYREF)]
[InlineData(VT_R4 | VT_BYREF)]
[InlineData(VT_R8 | VT_BYREF)]
[InlineData(VT_CY | VT_BYREF)]
[InlineData(VT_DATE | VT_BYREF)]
[InlineData(VT_BSTR | VT_BYREF)]
[InlineData(VT_DISPATCH | VT_BYREF)]
[InlineData(VT_ERROR | VT_BYREF)]
[InlineData(VT_BOOL | VT_BYREF)]
[InlineData(VT_VARIANT | VT_BYREF)]
[InlineData(VT_UNKNOWN | VT_BYREF)]
[InlineData(VT_I1 | VT_BYREF)]
[InlineData(VT_UI1 | VT_BYREF)]
[InlineData(VT_UI2 | VT_BYREF)]
[InlineData(VT_UI4 | VT_BYREF)]
[InlineData(VT_I8 | VT_BYREF)]
[InlineData(VT_UI8 | VT_BYREF)]
[InlineData(VT_INT | VT_BYREF)]
[InlineData(VT_UINT | VT_BYREF)]
[InlineData(VT_VOID | VT_BYREF)]
[InlineData(VT_HRESULT | VT_BYREF)]
[InlineData(VT_PTR | VT_BYREF)]
[InlineData(VT_SAFEARRAY | VT_BYREF)]
[InlineData(VT_CARRAY | VT_BYREF)]
[InlineData(VT_USERDEFINED | VT_BYREF)]
[InlineData(VT_LPSTR | VT_BYREF)]
[InlineData(VT_LPWSTR | VT_BYREF)]
[InlineData(VT_RECORD | VT_BYREF)]
[InlineData(VT_INT_PTR | VT_BYREF)]
[InlineData(VT_UINT_PTR | VT_BYREF)]
[InlineData(VT_FILETIME | VT_BYREF)]
[InlineData(VT_BLOB | VT_BYREF)]
[InlineData(VT_STREAM | VT_BYREF)]
[InlineData(VT_STORAGE | VT_BYREF)]
[InlineData(VT_STREAMED_OBJECT | VT_BYREF)]
[InlineData(VT_STORED_OBJECT | VT_BYREF)]
[InlineData(VT_BLOB_OBJECT | VT_BYREF)]
[InlineData(VT_CF | VT_BYREF)]
[InlineData(VT_CLSID | VT_BYREF)]
[InlineData(VT_VERSIONED_STREAM | VT_BYREF)]
[InlineData(VT_BSTR_BLOB | VT_BYREF)]
[InlineData(VT_VECTOR | VT_BYREF)]
[InlineData(VT_ARRAY | VT_BYREF)]
[InlineData(VT_RESERVED | VT_BYREF)]
[InlineData(VT_ILLEGAL | VT_BYREF)]
[InlineData(VT_ILLEGALMASKED | VT_BYREF)]
[InlineData(VT_TYPEMASK| VT_BYREF)]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_ZeroByRefTypeNotEmptyOrNull_ThrowsArgumentException(ushort vt)
{
var variant = new Variant();
variant.m_Variant.vt = vt;
variant.m_Variant._unionTypes._byref = IntPtr.Zero;
AssertExtensions.Throws<ArgumentException>(null, () => GetObjectForNativeVariant(variant));
}
[Theory]
[InlineData(-657435.0)]
[InlineData(2958466.0)]
[InlineData(double.NegativeInfinity)]
[InlineData(double.PositiveInfinity)]
[InlineData(double.NaN)]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_InvalidDate_ThrowsArgumentException(double value)
{
Variant variant = CreateVariant(VT_DATE, new UnionTypes { _date = value });
AssertExtensions.Throws<ArgumentException>(null, () => GetObjectForNativeVariant(variant));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_NoDataForRecord_ThrowsArgumentException()
{
Variant variant = CreateVariant(VT_RECORD, new UnionTypes { _record = new Record { _recordInfo = IntPtr.Zero } });
AssertExtensions.Throws<ArgumentException>(null, () => GetObjectForNativeVariant(variant));
}
public static IEnumerable<object[]> GetObjectForNativeVariant_NoSuchGuid_TestData()
{
yield return new object[] { typeof(string).GUID };
yield return new object[] { Guid.Empty };
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_NoSuchGuid_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_NoSuchGuid_ThrowsArgumentException(Guid guid)
{
int record = 10;
var recordInfo = new RecordInfo { Guid = guid };
IntPtr pRecord = Marshal.AllocHGlobal(Marshal.SizeOf<int>());
IntPtr pRecordInfo = Marshal.GetComInterfaceForObject<RecordInfo, IRecordInfo>(recordInfo);
try
{
Marshal.StructureToPtr(record, pRecord, fDeleteOld: false);
Variant variant = CreateVariant(VT_RECORD, new UnionTypes
{
_record = new Record
{
_record = pRecord,
_recordInfo = pRecordInfo
}
});
AssertExtensions.Throws<ArgumentException>(null, () => GetObjectForNativeVariant(variant));
}
finally
{
Marshal.DestroyStructure<int>(pRecord);
Marshal.FreeHGlobal(pRecord);
Marshal.Release(pRecordInfo);
}
}
public static IEnumerable<object[]> GetObjectForNativeVariant_CantMap_ThrowsArgumentException()
{
yield return new object[] { CreateVariant(VT_VARIANT, new UnionTypes()) };
yield return new object[] { CreateVariant(15, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_HRESULT, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_PTR, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_SAFEARRAY, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_CARRAY, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_USERDEFINED, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_LPSTR, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_LPWSTR, new UnionTypes()) };
yield return new object[] { CreateVariant(32, new UnionTypes()) };
yield return new object[] { CreateVariant(33, new UnionTypes()) };
yield return new object[] { CreateVariant(34, new UnionTypes()) };
yield return new object[] { CreateVariant(35, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_INT_PTR, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_UINT_PTR, new UnionTypes()) };
yield return new object[] { CreateVariant(39, new UnionTypes()) };
yield return new object[] { CreateVariant(63, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_FILETIME, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_BLOB, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_STREAM, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_STORAGE, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_STREAMED_OBJECT, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_STORED_OBJECT, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_BLOB_OBJECT, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_CF, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_CLSID, new UnionTypes()) };
yield return new object[] { CreateVariant(VT_VERSIONED_STREAM, new UnionTypes()) };
yield return new object[] { CreateVariant(74, new UnionTypes()) };
yield return new object[] { CreateVariant(127, new UnionTypes()) };
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_CantMap_ThrowsArgumentException))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_CantMap_ThrowsArgumentException(Variant variant)
{
AssertExtensions.Throws<ArgumentException>(null, () => GetObjectForNativeVariant(variant));
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_CantMap_ThrowsArgumentException))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_CantMapByRef_ThrowsArgumentException(Variant variant)
{
variant.m_Variant.vt |= VT_BYREF;
AssertExtensions.Throws<ArgumentException>(null, () => GetObjectForNativeVariant(variant));
}
public static IEnumerable<object[]> GetObjectForNativeVariant_InvalidVarType_TestData()
{
yield return new object[] { 128 };
yield return new object[] { 4094 };
yield return new object[] { VT_BSTR_BLOB };
yield return new object[] { VT_ILLEGALMASKED };
yield return new object[] { VT_TYPEMASK };
yield return new object[] { VT_VECTOR };
yield return new object[] { 4097 };
yield return new object[] { 8191 };
yield return new object[] { 16383 };
yield return new object[] { VT_RESERVED };
yield return new object[] { 65534 };
yield return new object[] { VT_ILLEGAL };
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_InvalidVarType_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_InvalidVarType_InvalidOleVariantTypeException(ushort vt)
{
Variant variant = CreateVariant(vt, new UnionTypes { _byref = (IntPtr)10 });
Assert.Throws<InvalidOleVariantTypeException>(() => GetObjectForNativeVariant(variant));
}
[Theory]
[MemberData(nameof(GetObjectForNativeVariant_InvalidVarType_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_InvalidVarTypeByRef_InvalidOleVariantTypeException(ushort vt)
{
Variant variant = CreateVariant((ushort)(vt | VT_BYREF), new UnionTypes { _byref = (IntPtr)10 });
Assert.Throws<InvalidOleVariantTypeException>(() => GetObjectForNativeVariant(variant));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_ByRefNestedVariant_InvalidOleVariantTypeException()
{
var source = new Variant();
source.m_Variant.vt = VT_INT | VT_BYREF;
source.m_Variant._unionTypes._byref = (IntPtr)10;
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf<Variant>());
try
{
Marshal.StructureToPtr(source, ptr, fDeleteOld: false);
var variant = new Variant();
variant.m_Variant.vt = VT_VARIANT | VT_BYREF;
variant.m_Variant._unionTypes._pvarVal = ptr;
Assert.Throws<InvalidOleVariantTypeException>(() => GetObjectForNativeVariant(variant));
}
finally
{
Marshal.DestroyStructure<Variant>(ptr);
Marshal.FreeHGlobal(ptr);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetObjectForNativeVariant_ArrayOfEmpty_ThrowsInvalidOleVariantTypeException()
{
Variant variant = CreateVariant(VT_ARRAY, new UnionTypes { _parray = (IntPtr)10 });
Assert.Throws<InvalidOleVariantTypeException>(() => GetObjectForNativeVariant(variant));
}
private static object GetObjectForNativeVariant(Variant variant)
{
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf<Variant>());
try
{
Marshal.StructureToPtr(variant, ptr, fDeleteOld: false);
return Marshal.GetObjectForNativeVariant(ptr);
}
finally
{
Marshal.DestroyStructure<Variant>(ptr);
Marshal.FreeHGlobal(ptr);
}
}
private static Variant CreateVariant(ushort vt, UnionTypes union)
{
var variant = new Variant();
variant.m_Variant.vt = vt;
variant.m_Variant._unionTypes = union;
return variant;
}
private static void DeleteVariant(Variant variant)
{
if (variant.m_Variant.vt == VT_BSTR)
{
Marshal.FreeBSTR(variant.m_Variant._unionTypes._bstr);
}
else if (variant.m_Variant.vt == VT_UNKNOWN && variant.m_Variant._unionTypes._unknown != IntPtr.Zero)
{
Marshal.Release(variant.m_Variant._unionTypes._unknown);
}
else if (variant.m_Variant.vt == VT_DISPATCH && variant.m_Variant._unionTypes._dispatch != IntPtr.Zero)
{
Marshal.Release(variant.m_Variant._unionTypes._dispatch);
}
}
public class RecordInfo : IRecordInfo
{
public Guid Guid { get; set; }
public void RecordInit([Out] IntPtr pvNew)
{
throw new NotImplementedException();
}
public void RecordClear([In] IntPtr pvExisting)
{
throw new NotImplementedException();
}
public void RecordCopy([In] IntPtr pvExisting, [Out] IntPtr pvNew)
{
throw new NotImplementedException();
}
public void GetGuid(out Guid pguid)
{
pguid = Guid;
}
public void GetName([MarshalAs(UnmanagedType.BStr)] out string pbstrName)
{
throw new NotImplementedException();
}
public void GetSize(out uint pcbSize)
{
throw new NotImplementedException();
}
public void GetTypeInfo([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "System.Runtime.InteropServices.CustomMarshalers.TypeToTypeInfoMarshaler")] out Type ppTypeInfo)
{
throw new NotImplementedException();
}
public void GetField([In] IntPtr pvData, [In, MarshalAs(UnmanagedType.LPWStr)] string szFieldName, [MarshalAs(UnmanagedType.Struct)] out object pvarField)
{
throw new NotImplementedException();
}
public void GetFieldNoCopy([In] IntPtr pvData, [In, MarshalAs(UnmanagedType.LPWStr)] string szFieldName, [MarshalAs(UnmanagedType.Struct)] out object pvarField, out IntPtr ppvDataCArray)
{
throw new NotImplementedException();
}
public void PutField([In] uint wFlags, [In, Out] IntPtr pvData, [In, MarshalAs(UnmanagedType.LPWStr)] string szFieldName, [In, MarshalAs(UnmanagedType.Struct)] ref object pvarField)
{
throw new NotImplementedException();
}
public void PutFieldNoCopy([In] uint wFlags, [In, Out] IntPtr pvData, [In, MarshalAs(UnmanagedType.LPWStr)] string szFieldName, [In, MarshalAs(UnmanagedType.Struct)] ref object pvarField)
{
throw new NotImplementedException();
}
public void GetFieldNames([In, Out] ref uint pcNames, [MarshalAs(UnmanagedType.BStr)] out string rgBstrNames)
{
throw new NotImplementedException();
}
public int IsMatchingType([In, MarshalAs(UnmanagedType.Interface)] IRecordInfo pRecordInfo)
{
throw new NotImplementedException();
}
public IntPtr RecordCreate()
{
throw new NotImplementedException();
}
public void RecordCreateCopy([In] IntPtr pvSource, out IntPtr ppvDest)
{
throw new NotImplementedException();
}
public void RecordDestroy([In] IntPtr pvRecord)
{
throw new NotImplementedException();
}
}
[Guid("0000002F-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IRecordInfo
{
[MethodImpl(MethodImplOptions.InternalCall)]
void RecordInit([Out] IntPtr pvNew);
[MethodImpl(MethodImplOptions.InternalCall)]
void RecordClear([In] IntPtr pvExisting);
[MethodImpl(MethodImplOptions.InternalCall)]
void RecordCopy([In] IntPtr pvExisting, [Out] IntPtr pvNew);
[MethodImpl(MethodImplOptions.InternalCall)]
void GetGuid(out Guid pguid);
[MethodImpl(MethodImplOptions.InternalCall)]
void GetName([MarshalAs(UnmanagedType.BStr)] out string pbstrName);
[MethodImpl(MethodImplOptions.InternalCall)]
void GetSize(out uint pcbSize);
[MethodImpl(MethodImplOptions.InternalCall)]
void GetTypeInfo([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "System.Runtime.InteropServices.CustomMarshalers.TypeToTypeInfoMarshaler")] out Type ppTypeInfo);
[MethodImpl(MethodImplOptions.InternalCall)]
void GetField([In] IntPtr pvData, [MarshalAs(UnmanagedType.LPWStr)] [In] string szFieldName, [MarshalAs(UnmanagedType.Struct)] out object pvarField);
[MethodImpl(MethodImplOptions.InternalCall)]
void GetFieldNoCopy([In] IntPtr pvData, [MarshalAs(UnmanagedType.LPWStr)] [In] string szFieldName, [MarshalAs(UnmanagedType.Struct)] out object pvarField, out IntPtr ppvDataCArray);
[MethodImpl(MethodImplOptions.InternalCall)]
void PutField([In] uint wFlags, [In] [Out] IntPtr pvData, [MarshalAs(UnmanagedType.LPWStr)] [In] string szFieldName, [MarshalAs(UnmanagedType.Struct)] [In] ref object pvarField);
[MethodImpl(MethodImplOptions.InternalCall)]
void PutFieldNoCopy([In] uint wFlags, [In] [Out] IntPtr pvData, [MarshalAs(UnmanagedType.LPWStr)] [In] string szFieldName, [MarshalAs(UnmanagedType.Struct)] [In] ref object pvarField);
[MethodImpl(MethodImplOptions.InternalCall)]
void GetFieldNames([In] [Out] ref uint pcNames, [MarshalAs(UnmanagedType.BStr)] out string rgBstrNames);
[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)]
int IsMatchingType([MarshalAs(UnmanagedType.Interface)] [In] IRecordInfo pRecordInfo);
[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall)]
IntPtr RecordCreate();
[MethodImpl(MethodImplOptions.InternalCall)]
void RecordCreateCopy([In] IntPtr pvSource, out IntPtr ppvDest);
[MethodImpl(MethodImplOptions.InternalCall)]
void RecordDestroy([In] IntPtr pvRecord);
}
}
}
#pragma warning restore 618
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Globalization;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using SolarWinds.InformationService.Contract2;
namespace SolarWinds.InformationService.InformationServiceClient
{
/// <summary>
/// Provides a way of reading a forward-only stream of rows from a SolarWinds Information Service.
/// </summary>
public sealed class InformationServiceDataReader : DbDataReader
{
internal const string DBNullNamespace = "http://www.w3.org/2001/XMLSchema-instance";
internal const string DBNullPrefix = "xsi";
internal const string DBNullAttribute = "nil";
internal const string DBNullValue = "true";
private readonly DbDataReader _resultsReader;
private List<ErrorMessage> _errors;
private Lazy<DataTable> _lazySchemaTable;
private bool _closed;
private readonly DataSetDateTime _dateTimeMode;
// This is a *very* basic implementation of Lazy<T> for .NET 3.5.
private class Lazy<T>
{
private readonly Func<T> _initializer;
private readonly object _locker = new object();
private T _value;
private bool _isValueCreated;
public Lazy(Func<T> initializer)
{
if (initializer == null) throw new ArgumentNullException(nameof(initializer));
_initializer = initializer;
}
public T Value
{
get
{
lock (_locker)
{
if (_isValueCreated)
{
return _value;
}
_value = _initializer();
_isValueCreated = true;
return _value;
}
}
}
}
internal InformationServiceDataReader(InformationServiceCommand command, XmlDictionaryReader reader, DataSetDateTime dateTimeMode)
{
if (command == null)
throw new ArgumentNullException(nameof(command));
if (reader == null)
throw new ArgumentNullException(nameof(reader));
_dateTimeMode = dateTimeMode;
_resultsReader = LoadData(reader);
}
#region DbDataReader Methods
public override void Close()
{
if (_closed)
throw new InvalidOperationException("already closed");
_closed = true;
if (!_resultsReader.IsClosed)
_resultsReader.Close();
}
public override int Depth
{
get { return _resultsReader.Depth; }
}
public override int FieldCount
{
get { return _resultsReader.FieldCount; }
}
public override bool GetBoolean(int ordinal)
{
return _resultsReader.GetBoolean(ordinal);
}
public override byte GetByte(int ordinal)
{
return _resultsReader.GetByte(ordinal);
}
public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
{
return _resultsReader.GetBytes(ordinal, dataOffset, buffer, bufferOffset, length);
}
public override char GetChar(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return _resultsReader.GetChar(ordinal);
}
public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
{
return _resultsReader.GetChars(ordinal, dataOffset, buffer, bufferOffset, length);
}
public override string GetDataTypeName(int ordinal)
{
return _resultsReader.GetDataTypeName(ordinal);
}
public override DateTime GetDateTime(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return _resultsReader.GetDateTime(ordinal);
}
public override decimal GetDecimal(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return _resultsReader.GetDecimal(ordinal);
}
public override double GetDouble(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return _resultsReader.GetDouble(ordinal);
}
public override System.Collections.IEnumerator GetEnumerator()
{
return _resultsReader.GetEnumerator();
}
public override Type GetFieldType(int ordinal)
{
return _resultsReader.GetFieldType(ordinal);
}
public override float GetFloat(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return _resultsReader.GetFloat(ordinal);
}
public override Guid GetGuid(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return _resultsReader.GetGuid(ordinal);
}
public override short GetInt16(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return _resultsReader.GetInt16(ordinal);
}
public override int GetInt32(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return _resultsReader.GetInt32(ordinal);
}
public override long GetInt64(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return _resultsReader.GetInt64(ordinal);
}
public override string GetName(int ordinal)
{
return _resultsReader.GetName(ordinal);
}
public override int GetOrdinal(string name)
{
return _resultsReader.GetOrdinal(name);
}
public override DataTable GetSchemaTable()
{
return _lazySchemaTable != null ? _lazySchemaTable.Value : _resultsReader.GetSchemaTable();
}
public override string GetString(int ordinal)
{
if (IsDBNull(ordinal))
return null;
return _resultsReader.GetString(ordinal);
}
public T[] GetArray<T>(int ordinal)
{
if (IsDBNull(ordinal))
return null;
return (T[])_resultsReader[ordinal];
}
public override object GetValue(int ordinal)
{
return _resultsReader.GetValue(ordinal);
}
public override int GetValues(object[] values)
{
return _resultsReader.GetValues(values);
}
public override bool HasRows
{
get { return _resultsReader.HasRows; }
}
public override bool IsClosed
{
get { return _closed; }
}
public override bool IsDBNull(int ordinal)
{
return _resultsReader.IsDBNull(ordinal);
}
public override bool NextResult()
{
return _resultsReader.NextResult();
}
public override bool Read()
{
return _resultsReader.Read();
}
public override int RecordsAffected
{
get { return _resultsReader.RecordsAffected; }
}
public override object this[string name]
{
get { return _resultsReader[name]; }
}
public override object this[int ordinal]
{
get { return _resultsReader[ordinal]; }
}
#endregion
private DbDataReader LoadData(XmlDictionaryReader reader)
{
DataTable dataTable = new DataTable();
var dataReader = new InformationServiceResultsReader(reader, _dateTimeMode);
var adapter = new InformationServiceDataAdapter();
adapter.FillData(dataTable, dataReader);
TotalRows = dataReader.TotalRows;
QueryPlan = dataReader.QueryPlan;
QueryStats = dataReader.QueryStats;
_errors = dataReader.Errors;
_lazySchemaTable = new Lazy<DataTable>(() => dataReader.GetSchemaTable());
return dataTable.CreateDataReader();
}
public long? TotalRows { get; private set; }
public XmlDocument QueryPlan { get; private set; }
public XmlDocument QueryStats { get; private set; }
public List<ErrorMessage> Errors
{
get
{
if (_errors != null)
return _errors;
var reader = _resultsReader as InformationServiceResultsReader;
if (reader != null)
{
if (reader.Errors != null)
return reader.Errors;
}
return null;
}
}
private class InformationServiceResultsReader : DbDataReader
{
private enum ParserState
{
Start,
Root,
Template,
ResultSet,
PropertyTemplate,
Data,
Row,
Column,
ArrayColumn,
ArrayItem,
Errors,
Error
}
private readonly XmlDictionaryReader reader;
private ParserState state;
private List<ColumnInfo> columns;
private int currentColumnOrdinal;
private bool currentColumnDBNull;
private bool currentColumnEncoded;
private string currentColumnEncodingType;
private readonly object[] values;
private readonly List<object> arrayColumnValues = new List<object>();
private bool closed = false;
private DataTable schemaTable = null;
private bool hasRows = false;
private static readonly XmlSerializer serializer = new XmlSerializer(typeof(ErrorMessage));
internal const string DBNullNamespace = "http://www.w3.org/2001/XMLSchema-instance";
internal const string DBNullPrefix = "xsi";
internal const string DBNullAttribute = "nil";
internal const string DBNullValue = "true";
internal const string DBBase64 = "Base64";
internal const string IsEncodedAttribute = "isEncoded";
internal const string EncodingTypeAttribute = "encodingType";
public List<ErrorMessage> Errors { get; private set; }
public DataSetDateTime DateTimeMode { get; set; }
internal InformationServiceResultsReader(XmlDictionaryReader reader, DataSetDateTime dateTimeMode)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
DateTimeMode = dateTimeMode;
this.reader = reader;
ReadMetadata();
values = new object[columns.Count];
}
public override void Close()
{
if (closed)
throw new InvalidOperationException("already closed");
closed = true;
}
public override int Depth
{
get { return 0; }
}
public override int FieldCount
{
get { return columns.Count; }
}
public override bool GetBoolean(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (bool)values[ordinal];
}
public override byte GetByte(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (byte)values[ordinal];
}
public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
{
throw new NotSupportedException("GetBytes");
}
public override char GetChar(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (char)values[ordinal];
}
public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
{
throw new NotSupportedException("GetChars");
}
public override string GetDataTypeName(int ordinal)
{
return columns[ordinal].TypeName;
}
public override DateTime GetDateTime(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (DateTime)values[ordinal];
}
public override decimal GetDecimal(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (decimal)values[ordinal];
}
public override double GetDouble(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (double)values[ordinal];
}
public override System.Collections.IEnumerator GetEnumerator()
{
throw new NotSupportedException("GetEnumerator");
}
public override Type GetFieldType(int ordinal)
{
return columns[ordinal].Type;
}
public override float GetFloat(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (float)values[ordinal];
}
public override Guid GetGuid(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (Guid)values[ordinal];
}
public override short GetInt16(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (short)values[ordinal];
}
public override int GetInt32(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (int)values[ordinal];
}
public override long GetInt64(int ordinal)
{
if (IsDBNull(ordinal))
throw new SqlNullValueException(string.Format("Column contains {0} DBNull", ordinal));
return (long)values[ordinal];
}
public override string GetName(int ordinal)
{
return columns[ordinal].Name;
}
public override int GetOrdinal(string name)
{
for (int i = 0; i < columns.Count; ++i)
{
if (columns[i].Name.Equals(name, StringComparison.Ordinal))
return i;
}
for (int i = 0; i < columns.Count; ++i)
{
if (columns[i].Name.Equals(name, StringComparison.OrdinalIgnoreCase))
return i;
}
throw new IndexOutOfRangeException("The name specified is not a valid column name");
}
public override DataTable GetSchemaTable()
{
if (schemaTable == null)
BuildSchemaTable();
return schemaTable;
}
public override string GetString(int ordinal)
{
if (IsDBNull(ordinal))
return null;
return (string)values[ordinal];
}
public override object GetValue(int ordinal)
{
return values[ordinal];
}
public override int GetValues(object[] values)
{
this.values.CopyTo(values, 0);
return this.values.Length;
}
public override bool HasRows
{
get
{
if (closed)
throw new InvalidOperationException("DataReader is closed");
return hasRows;
}
}
public override bool IsClosed
{
get { return closed; }
}
public override bool IsDBNull(int ordinal)
{
return (values[ordinal] == DBNull.Value);
}
public override bool NextResult()
{
return false;
}
public override bool Read()
{
if (closed)
throw new InvalidOperationException("DataReader is closed");
return ReadNextEntity();
}
public override int RecordsAffected
{
get { return -1; }
}
public long? TotalRows { get; private set; }
public override object this[string name]
{
get { return values[GetOrdinal(name)]; }
}
public override object this[int ordinal]
{
get { return values[ordinal]; }
}
public XmlDocument QueryPlan { get; private set; }
public XmlDocument QueryStats { get; private set; }
public void ReadMetadata()
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
switch (state)
{
case ParserState.Start:
// Assumption:
// - skip the soap response tags
if ((reader.LocalName == "QueryXmlResponse") ||
(reader.LocalName == "QueryXmlResult"))
continue;
if (string.CompareOrdinal(reader.LocalName, "queryResult") == 0)
state = ParserState.Root;
else
throw new InvalidOperationException(
"Expecting <queryResult> element but found " + reader.LocalName);
break;
case ParserState.Root:
if (string.CompareOrdinal(reader.LocalName, "queryPlan") == 0)
{
QueryPlan = new XmlDocument();
QueryPlan.Load(reader.ReadSubtree());
}
// obsolete since 2016.2 - the statistics was put after data
else if (string.CompareOrdinal(reader.LocalName, "statistics") == 0)
{
QueryStats = new XmlDocument();
QueryStats.Load(reader.ReadSubtree());
}
else if (string.CompareOrdinal(reader.LocalName, "template") == 0)
{
state = ParserState.Template;
}
else if (string.CompareOrdinal(reader.LocalName, "data") == 0)
{
state = ParserState.Data;
hasRows = true;
string totalRowsAttr = reader.GetAttribute("totalRows");
if (!string.IsNullOrEmpty(totalRowsAttr))
TotalRows = Convert.ToInt64(totalRowsAttr, CultureInfo.InvariantCulture);
return;
}
else
{
throw new InvalidOperationException("Unexepected element " + reader.LocalName);
}
break;
case ParserState.Template:
if (string.CompareOrdinal(reader.LocalName, "resultset") == 0)
{
if (columns != null)
throw new InvalidOperationException("Only one resultset is supported");
state = ParserState.ResultSet;
}
break;
case ParserState.ResultSet:
if (string.CompareOrdinal(reader.LocalName, "column") != 0)
throw new InvalidOperationException(
"Only <column> elements are expected as children of a <resultset> element");
if (columns == null)
{
columns = new List<ColumnInfo>();
}
ColumnInfo columnInfo = new ColumnInfo(reader["name"], reader["type"],
int.Parse(reader["ordinal"], CultureInfo.InvariantCulture));
// TODO: this should be define in column definition
columnInfo.DateTimeMode = DateTimeMode;
while (reader.MoveToNextAttribute())
{
var name = reader.Name;
if (!name.Equals("name", StringComparison.OrdinalIgnoreCase) && !name.Equals("type", StringComparison.OrdinalIgnoreCase) && !name.Equals("ordinal", StringComparison.OrdinalIgnoreCase))
columnInfo.AddMetadata(name, reader.Value);
}
reader.MoveToElement();
columns.Add(columnInfo);
// Sometime empty elements come with an end element, adjust the statemachine state accordingly
if (!reader.IsEmptyElement)
state = ParserState.PropertyTemplate;
break;
default:
throw new InvalidOperationException("Unexpected state " + state);
}
break;
case XmlNodeType.EndElement:
switch (state)
{
case ParserState.Root:
if (string.CompareOrdinal(reader.LocalName, "queryResult") != 0)
throw new InvalidOperationException(
string.Format("Not expecting element {0} while in state {1}",
reader.LocalName, state));
return;
case ParserState.Template:
ValidateEndElement(reader.LocalName, "template", ParserState.Root);
break;
case ParserState.ResultSet:
ValidateEndElement(reader.LocalName, "resultset", ParserState.Template);
break;
case ParserState.PropertyTemplate:
ValidateEndElement(reader.LocalName, "column", ParserState.ResultSet);
break;
default:
throw new InvalidOperationException(
string.Format("Not expecting element {0} while in state {1}", reader.LocalName,
state));
}
break;
}
}
throw new InvalidOperationException("Malformed Xml result");
}
private void ReadErrors(XmlReader reader)
{
if (Errors == null)
Errors = new List<ErrorMessage>();
ErrorMessage message = (ErrorMessage)serializer.Deserialize(reader.ReadSubtree());
if (message != null)
Errors.Add(message);
}
private bool ReadNextEntity()
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (state)
{
case ParserState.Data:
BeginRootEntity(reader);
break;
case ParserState.Row:
BeginColumn(reader);
break;
case ParserState.ArrayColumn:
BeginArrayItem(reader);
break;
case ParserState.Errors:
if (reader.LocalName == "errors")
{
state = ParserState.Error;
}
break;
case ParserState.Error:
ReadErrors(reader);
break;
case ParserState.Root:
{
if (reader.LocalName == "errors")
{
state = ParserState.Error;
}
else if (reader.LocalName == "statistics")
{
QueryStats = new XmlDocument();
QueryStats.Load(reader.ReadSubtree());
}
else
throw new InvalidOperationException("Unexpected state " + state);
break;
}
default:
throw new InvalidOperationException("Unexpected state " + state);
}
}
if (reader.NodeType == XmlNodeType.EndElement ||
(reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement))
{
switch (state)
{
case ParserState.Error:
if (reader.LocalName == "errors")
return false;
break;
case ParserState.Errors:
return false;
case ParserState.Root:
if (reader.LocalName == "statistics")
break;
if (hasRows)
ValidateEndElement(reader.LocalName, "queryResult", ParserState.Errors);
else
return false;
break;
case ParserState.Data:
ValidateEndElement(reader.LocalName, "data", ParserState.Root);
break;
case ParserState.Column:
EndColumn(reader);
break;
case ParserState.ArrayItem:
ValidateEndElement(reader.LocalName, "item", ParserState.ArrayColumn);
break;
case ParserState.ArrayColumn:
EndArrayColumn();
break;
case ParserState.Row:
ValidateEndElement(reader.LocalName, "row", ParserState.Data);
EndRootEntity();
return true;
default:
throw new InvalidOperationException(
string.Format("Not expecting element {0} while in state {1}", reader.LocalName,
state));
}
}
if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.Whitespace)
{
if (!currentColumnDBNull)
{
switch (state)
{
case ParserState.Column:
ProcessColumnValue(reader);
break;
case ParserState.ArrayItem:
ProcessArrayItem(reader);
break;
default:
if (reader.NodeType == XmlNodeType.Whitespace)
break;
throw new InvalidOperationException("Not expecting element content for state " +
state);
}
}
}
}
return false;
}
private void ValidateEndElement(string elementName, string expectedName, ParserState targetState)
{
if (string.CompareOrdinal(elementName, expectedName) != 0)
throw new InvalidOperationException(string.Format("Expecting </{0}> but encountered {1}",
expectedName, elementName));
state = targetState;
}
private void BeginRootEntity(XmlReader reader)
{
// Assumptions:
// - expecting top level elements to be entities of the type expected by the query
// - name must match exactly between the XML element and the type name
// - not handling simple scalar results at this point, only classes/structs with properties
// - not handling fields
if (string.CompareOrdinal("row", reader.LocalName) != 0)
throw new InvalidOperationException("Expecting <row> element but found " + reader.LocalName);
state = ParserState.Row;
for (int i = 0; i < values.Length; ++i)
values[i] = DBNull.Value;
}
private void EndRootEntity()
{
state = ParserState.Data;
}
private void BeginColumn(XmlReader reader)
{
currentColumnOrdinal = Parse(reader.LocalName, 1, reader.LocalName.Length);
string dbNullAtt = reader.GetAttribute(DBNullAttribute, DBNullNamespace);
currentColumnDBNull = (!string.IsNullOrEmpty(dbNullAtt) && dbNullAtt.CompareTo(DBNullValue) == 0);
bool.TryParse(reader.GetAttribute(IsEncodedAttribute), out currentColumnEncoded);
currentColumnEncodingType = currentColumnEncoded ? reader.GetAttribute(EncodingTypeAttribute) : string.Empty;
ColumnInfo columnInfo = columns[currentColumnOrdinal];
if (columnInfo.IsArray)
state = ParserState.ArrayColumn;
else
{
state = ParserState.Column;
if (columnInfo.EntityPropertyType == EntityPropertyType.String && !currentColumnDBNull)
values[currentColumnOrdinal] = string.Empty;
}
}
private static int Parse(string str, int start, int end)
{
// parse input
int result = 0;
for (; start < end; ++start)
{
result = unchecked(10 * result + (str[start] - '0'));
}
return result;
}
private void BeginArrayItem(XmlDictionaryReader reader)
{
if (string.CompareOrdinal("item", reader.LocalName) != 0)
throw new InvalidOperationException("Expecting <item> element but found " + reader.LocalName);
state = ParserState.ArrayItem;
}
private void ProcessArrayItem(XmlDictionaryReader reader)
{
ColumnInfo columnInfo = columns[currentColumnOrdinal];
arrayColumnValues.Add(
DeserializeScalarValue(reader.Value, columnInfo.EntityPropertyType, columnInfo.Type.GetElementType(), columnInfo));
}
private void ProcessColumnValue(XmlDictionaryReader reader)
{
ColumnInfo columnInfo = columns[currentColumnOrdinal];
object value = DeserializeScalarValue(reader.Value, columnInfo.EntityPropertyType, columnInfo.Type, columnInfo);
if (columnInfo.EntityPropertyType == EntityPropertyType.String)
{
value = values[currentColumnOrdinal] + value.ToString();
}
values[currentColumnOrdinal] = value;
}
private object DeserializeScalarValue(string value, EntityPropertyType columnType, Type targetType, ColumnInfo currentColumn)
{
switch (columnType)
{
case EntityPropertyType.String:
if (currentColumnEncoded)
{
if (DBBase64.Equals(currentColumnEncodingType, StringComparison.OrdinalIgnoreCase))
value = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value));
}
return Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture);
case EntityPropertyType.Boolean:
case EntityPropertyType.Byte:
case EntityPropertyType.Char:
case EntityPropertyType.Decimal:
case EntityPropertyType.Double:
case EntityPropertyType.Int16:
case EntityPropertyType.Int32:
case EntityPropertyType.Int64:
case EntityPropertyType.Single:
case EntityPropertyType.Type:
case EntityPropertyType.Uri:
return Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture);
case EntityPropertyType.Blob:
return Convert.FromBase64String(value);
case EntityPropertyType.Guid:
return new Guid(value);
case EntityPropertyType.DateTime:
if (currentColumn.DateTimeMode.HasValue)
{
if (currentColumn.DateTimeMode.Value == DataSetDateTime.Local)
return DateTime.ParseExact(value, "o", CultureInfo.InvariantCulture);
else if (currentColumn.DateTimeMode.Value == DataSetDateTime.Utc)
return DateTime.ParseExact(value, "o", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
}
return DateTime.ParseExact(value, "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
case EntityPropertyType.Null:
return value;
default:
throw new InvalidOperationException(string.Format("Unsupported property type {0}", columnType));
}
}
private void EndColumn(XmlReader reader)
{
if (string.CompareOrdinal(reader.LocalName, columns[currentColumnOrdinal].ElementName) != 0)
throw new InvalidOperationException(string.Format("Expecting </{0}> but encountered {1}",
columns[currentColumnOrdinal].ElementName, reader.LocalName));
currentColumnOrdinal = -1;
state = ParserState.Row;
}
private void EndArrayColumn()
{
if (string.CompareOrdinal(reader.LocalName, columns[currentColumnOrdinal].ElementName) != 0)
throw new InvalidOperationException(string.Format("Expecting </{0}> but encountered {1}",
columns[currentColumnOrdinal].ElementName, reader.LocalName));
ColumnInfo column = columns[currentColumnOrdinal];
Array values = Array.CreateInstance(column.Type.GetElementType(), arrayColumnValues.Count);
for (int i = 0; i < values.Length; i++)
values.SetValue(arrayColumnValues[i], i);
this.values[currentColumnOrdinal] = values;
arrayColumnValues.Clear();
currentColumnOrdinal = -1;
state = ParserState.Row;
}
private void BuildSchemaTable()
{
schemaTable = new DataTable("SchemaTable");
schemaTable.MinimumCapacity = columns.Count;
DataColumn nameColumn = new DataColumn("ColumnName", typeof(string));
schemaTable.Columns.Add(nameColumn);
DataColumn ordinalColumn = new DataColumn("ColumnOrdinal", typeof(int));
schemaTable.Columns.Add(ordinalColumn);
DataColumn typeColumn = new DataColumn("ColumnType", typeof(Type));
schemaTable.Columns.Add(typeColumn);
DataColumn dateTimeMode = new DataColumn("ColumnDateTimeMode", typeof(DataSetDateTime));
schemaTable.Columns.Add(dateTimeMode);
foreach (var metadataName in columns.SelectMany(c => c.MetadataNames).Distinct())
{
schemaTable.Columns.Add(metadataName, typeof(string));
}
foreach (ColumnInfo columnInfo in columns)
{
DataRow row = schemaTable.NewRow();
row["ColumnName"] = columnInfo.Name;
row["ColumnOrdinal"] = columnInfo.Ordinal;
row["ColumnType"] = columnInfo.Type;
row["ColumnDateTimeMode"] = DateTimeMode;
foreach (var metadataName in columnInfo.MetadataNames)
{
row[metadataName] = columnInfo[metadataName];
}
schemaTable.Rows.Add(row);
}
}
private class ColumnInfo : EntityPropertyInfo
{
private readonly Dictionary<string, string> metadata = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public ColumnInfo(string name, string typeName, int ordinal)
: base(name, typeName)
{
Ordinal = ordinal;
ElementName = "c" + ordinal.ToString(CultureInfo.InvariantCulture);
}
public int Ordinal { get; }
public string ElementName { get; }
public void AddMetadata(string key, string value)
{
metadata.Add(key, value);
}
public IEnumerable<string> MetadataNames { get { return metadata.Keys; } }
public string this[string key] { get { return metadata[key]; } }
public DataSetDateTime? DateTimeMode { get; set; }
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Edm;
using Simple.OData.Client.V3.Adapter;
using Xunit;
namespace Simple.OData.Client.Tests.Core
{
public class ResponseReaderV3Tests : CoreTestBase
{
private const int productProperties = 10;
private const int categoryProperties = 4;
public override string MetadataFile => "Northwind3.xml";
public override IFormatSettings FormatSettings => new ODataV3Format();
[Fact]
public async Task GetSingleProduct()
{
var response = SetUpResourceMock("SingleProduct.xml");
var responseReader = new ResponseReader(_session, await _client.GetMetadataAsync<IEdmModel>());
var result = (await responseReader.GetResponseAsync(response)).AsEntry(false);
Assert.Equal(productProperties, result.Count);
}
[Fact]
public async Task GetMultipleProducts()
{
var response = SetUpResourceMock("MultipleProducts.xml");
var responseReader = new ResponseReader(_session, await _client.GetMetadataAsync<IEdmModel>());
var result = (await responseReader.GetResponseAsync(response)).Feed.Entries;
Assert.Equal(20, result.Count());
Assert.Equal(productProperties, result.First().Data.Count);
}
[Fact]
public async Task GetSingleProductWithCategory()
{
var response = SetUpResourceMock("SingleProductWithCategory.xml");
var responseReader = new ResponseReader(_session, await _client.GetMetadataAsync<IEdmModel>());
var result = (await responseReader.GetResponseAsync(response)).AsEntry(false);
Assert.Equal(productProperties + 1, result.Count);
Assert.Equal(categoryProperties, (result["Category"] as IDictionary<string, object>).Count);
}
[Fact]
public async Task GetMultipleProductsWithCategory()
{
var response = SetUpResourceMock("MultipleProductsWithCategory.xml");
var responseReader = new ResponseReader(_session, await _client.GetMetadataAsync<IEdmModel>());
var result = (await responseReader.GetResponseAsync(response)).Feed.Entries;
Assert.Equal(20, result.Count());
Assert.Equal(productProperties + 1, result.First().Data.Count);
Assert.Equal(categoryProperties, (result.First().Data["Category"] as IDictionary<string, object>).Count);
}
[Fact]
public async Task GetSingleCategoryWithProducts()
{
var response = SetUpResourceMock("SingleCategoryWithProducts.xml");
var responseReader = new ResponseReader(_session, await _client.GetMetadataAsync<IEdmModel>());
var result = (await responseReader.GetResponseAsync(response)).AsEntry(false);
Assert.Equal(categoryProperties + 1, result.Count);
Assert.Equal(12, (result["Products"] as IEnumerable<IDictionary<string, object>>).Count());
Assert.Equal(productProperties, (result["Products"] as IEnumerable<IDictionary<string, object>>).First().Count);
}
[Fact]
public async Task GetMultipleCategoriesWithProducts()
{
var response = SetUpResourceMock("MultipleCategoriesWithProducts.xml");
var responseReader = new ResponseReader(_session, await _client.GetMetadataAsync<IEdmModel>());
var result = (await responseReader.GetResponseAsync(response)).Feed.Entries;
Assert.Equal(8, result.Count());
Assert.Equal(categoryProperties + 1, result.First().Data.Count);
Assert.Equal(12, (result.First().Data["Products"] as IEnumerable<IDictionary<string, object>>).Count());
Assert.Equal(productProperties, (result.First().Data["Products"] as IEnumerable<IDictionary<string, object>>).First().Count);
}
[Fact]
public async Task GetSingleProductWithComplexProperty()
{
var response = SetUpResourceMock("SingleProductWithComplexProperty.xml");
var responseReader = new ResponseReader(_session, null);
var result = (await responseReader.GetResponseAsync(response)).AsEntry(false);
Assert.Equal(productProperties + 1, result.Count);
var quantity = result["Quantity"] as IDictionary<string, object>;
Assert.NotNull(quantity);
Assert.Equal(10d, quantity["Value"]);
Assert.Equal("bags", quantity["Units"]);
}
[Fact]
public async Task GetSingleProductWithCollectionOfPrimitiveProperties()
{
var response = SetUpResourceMock("SingleProductWithCollectionOfPrimitiveProperties.xml");
var responseReader = new ResponseReader(_session, null);
var result = (await responseReader.GetResponseAsync(response)).AsEntry(false);
Assert.Equal(productProperties + 2, result.Count);
var tags = result["Tags"] as IList<dynamic>;
Assert.Equal(2, tags.Count);
Assert.Equal("Bakery", tags[0]);
Assert.Equal("Food", tags[1]);
var ids = result["Ids"] as IList<dynamic>;
Assert.Equal(2, ids.Count);
Assert.Equal(1, ids[0]);
Assert.Equal(2, ids[1]);
}
[Fact]
public async Task GetSingleProductWithCollectionOfComplexProperties()
{
var response = SetUpResourceMock("SingleProductWithCollectionOfComplexProperties.xml");
var responseReader = new ResponseReader(_session, null);
var result = (await responseReader.GetResponseAsync(response)).AsEntry(false);
Assert.Equal(productProperties + 1, result.Count);
var tags = result["Tags"] as IList<dynamic>;
Assert.Equal(2, tags.Count);
Assert.Equal("Food", tags[0]["group"]);
Assert.Equal("Bakery", tags[0]["value"]);
Assert.Equal("Food", tags[1]["group"]);
Assert.Equal("Meat", tags[1]["value"]);
}
[Fact]
public async Task GetSingleProductWithEmptyCollectionOfComplexProperties()
{
var response = SetUpResourceMock("SingleProductWithEmptyCollectionOfComplexProperties.xml");
var responseReader = new ResponseReader(_session, null);
var result = (await responseReader.GetResponseAsync(response)).AsEntry(false);
Assert.Equal(productProperties + 1, result.Count);
var tags = result["Tags"] as IList<dynamic>;
Assert.Equal(0, tags.Count);
}
[Fact]
public Task GetColorsSchema()
{
return ParseSchema("Colors");
}
[Fact]
public Task GetFacebookSchema()
{
return ParseSchema("Facebook");
}
[Fact]
public Task GetFlickrSchema()
{
return ParseSchema("Flickr");
}
[Fact]
public Task GetGoogleMapsSchema()
{
return ParseSchema("GoogleMaps");
}
[Fact]
public Task GetiPhoneSchema()
{
return ParseSchema("iPhone");
}
[Fact]
public Task GetTwitterSchema()
{
return ParseSchema("Twitter");
}
[Fact]
public Task GetYouTubeSchema()
{
return ParseSchema("YouTube");
}
[Fact]
public Task GetNestedSchema()
{
return ParseSchema("Nested");
}
[Fact]
public Task GetArrayOfNestedSchema()
{
return ParseSchema("ArrayOfNested");
}
private Task ParseSchema(string schemaName)
{
var document = GetResourceAsString(schemaName + ".edmx");
var metadata = ODataClient.ParseMetadataString<IEdmModel>(document);
var entityType = metadata.SchemaElements
.Single(x => x.SchemaElementKind == EdmSchemaElementKind.TypeDefinition &&
(x as IEdmType).TypeKind == EdmTypeKind.Entity);
Assert.Equal(schemaName, entityType.Name);
return Task.FromResult(0);
}
}
}
| |
// 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 Microsoft.Protocols.TestTools.StackSdk.Messages;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb
{
/// <summary>
/// Packets for SmbOpenAndx Response
/// </summary>
public class SmbOpenAndxResponsePacket : Cifs.SmbOpenAndxResponsePacket
{
#region Fields
private SMB_COM_OPEN_ANDX_Response_SMB_Parameters smbParameters;
#endregion
#region Properties
/// <summary>
/// get or set the Smb_Parameters:SMB_COM_OPEN_ANDX_Response_SMB_Parameters
/// </summary>
public new SMB_COM_OPEN_ANDX_Response_SMB_Parameters SmbParameters
{
get
{
return this.smbParameters;
}
set
{
this.smbParameters = value;
// update the smbParameters of base class.
Cifs.SMB_COM_OPEN_ANDX_Response_SMB_Parameters param =
new Cifs.SMB_COM_OPEN_ANDX_Response_SMB_Parameters();
param.FID = this.smbParameters.FID;
param.WordCount = this.smbParameters.WordCount;
param.AndXCommand = this.smbParameters.AndXCommand;
param.AndXReserved = this.smbParameters.AndXReserved;
param.AndXOffset = this.smbParameters.AndXOffset;
param.FID = this.smbParameters.FID;
param.FileAttrs = this.smbParameters.FileAttrs;
param.LastWriteTime = this.smbParameters.LastWriteTime;
param.FileDataSize = this.smbParameters.DataSize;
param.AccessRights = this.smbParameters.GrantedAccess;
param.ResourceType = this.smbParameters.FileType;
param.NMPipeStatus = this.smbParameters.DeviceState;
param.OpenResults = this.smbParameters.Action;
param.Reserved = new ushort[3];
base.SmbParameters = param;
}
}
/// <summary>
/// the SmbCommand of the andx packet.
/// </summary>
protected override SmbCommand AndxCommand
{
get
{
return this.SmbParameters.AndXCommand;
}
}
/// <summary>
/// Set the AndXOffset from batched request
/// </summary>
protected override ushort AndXOffset
{
get
{
return this.smbParameters.AndXOffset;
}
set
{
this.smbParameters.AndXOffset = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public SmbOpenAndxResponsePacket()
: base()
{
this.InitDefaultValue();
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
public SmbOpenAndxResponsePacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
public SmbOpenAndxResponsePacket(SmbOpenAndxResponsePacket packet)
: base(packet)
{
this.InitDefaultValue();
this.smbParameters.WordCount = packet.SmbParameters.WordCount;
this.smbParameters.AndXCommand = packet.SmbParameters.AndXCommand;
this.smbParameters.AndXReserved = packet.SmbParameters.AndXReserved;
this.smbParameters.AndXOffset = packet.SmbParameters.AndXOffset;
this.smbParameters.FID = packet.SmbParameters.FID;
this.smbParameters.FileAttrs = packet.SmbParameters.FileAttrs;
this.smbParameters.LastWriteTime = packet.SmbParameters.LastWriteTime;
this.smbParameters.DataSize = packet.SmbParameters.DataSize;
this.smbParameters.GrantedAccess = packet.SmbParameters.GrantedAccess;
this.smbParameters.FileType = packet.SmbParameters.FileType;
this.smbParameters.DeviceState = packet.SmbParameters.DeviceState;
this.smbParameters.Action = packet.SmbParameters.Action;
this.smbParameters.ServerFid = packet.SmbParameters.ServerFid;
this.smbParameters.Reserved = packet.SmbParameters.Reserved;
this.smbParameters.MaximalAccessRights = packet.SmbParameters.MaximalAccessRights;
this.smbParameters.GuestMaximalAccessRights = packet.SmbParameters.GuestMaximalAccessRights;
}
#endregion
#region override methods
/// <summary>
/// to create an instance of the StackPacket class that is identical to the current StackPacket.
/// </summary>
/// <returns>a new Packet cloned from this. </returns>
public override StackPacket Clone()
{
return new SmbOpenAndxResponsePacket(this);
}
/// <summary>
/// Encode the struct of SMB_COM_OPEN_ANDX_Response_SMB_Parameters into the struct of SmbParameters
/// </summary>
protected override void EncodeParameters()
{
this.smbParametersBlock = CifsMessageUtils.ToStuct<SmbParameters>(
CifsMessageUtils.ToBytes<SMB_COM_OPEN_ANDX_Response_SMB_Parameters>(this.smbParameters));
}
/// <summary>
/// Encode the struct of SMB_COM_OPEN_ANDX_Response_SMB_Data into the struct of SmbData
/// </summary>
protected override void EncodeData()
{
this.smbDataBlock.ByteCount = 0x00;
}
/// <summary>
/// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters.
/// </summary>
protected override void DecodeParameters()
{
if (this.SmbParametersBlock.WordCount > 0)
{
this.SmbParameters = CifsMessageUtils.ToStuct<SMB_COM_OPEN_ANDX_Response_SMB_Parameters>(
CifsMessageUtils.ToBytes<SmbParameters>(this.smbParametersBlock));
}
else
{
this.smbParameters.WordCount = this.SmbParametersBlock.WordCount;
}
}
/// <summary>
/// to decode the smb data: from the general SmbDada to the concrete Smb Data.
/// </summary>
protected override void DecodeData()
{
SMB_COM_OPEN_ANDX_Response_SMB_Data smbData = base.SmbData;
smbData.ByteCount = this.smbDataBlock.ByteCount;
base.SmbData = smbData;
}
/// <summary>
/// to unmarshal the SmbDada struct from a channel. the open response need to parse specially, because its
/// data only contains a ByteCount.
/// </summary>
/// <param name = "channel">the channel started with SmbDada. </param>
/// <returns>the size in bytes of the SmbDada. </returns>
protected override int ReadDataFromChannel(Channel channel)
{
this.smbDataBlock.ByteCount = channel.Read<ushort>();
this.DecodeData();
return 2;
}
/// <summary>
/// to encode the SmbParameters and SmbDada into bytes.
/// </summary>
/// <returns>the bytes array of SmbParameters, SmbDada, and AndX if existed.</returns>
protected override byte[] GetBytesWithoutHeader()
{
byte[] bytes = base.GetBytesWithoutHeader();
// set the byte count of open.
// Windows-based servers may return a response where the ByteCount field is not initialized to 0.
int byteCountIndex = this.smbParametersBlock.WordCount * SmbCapability.NUM_BYTES_OF_WORD + SmbCapability.NUM_BYTES_OF_BYTE;
bytes[byteCountIndex] = (byte)(this.SmbData.ByteCount); // low bits
bytes[byteCountIndex + 1] = (byte)(this.SmbData.ByteCount >> 8); // high bits
return bytes;
}
#endregion
#region initialize fields with default value
/// <summary>
/// init packet, set default field data
/// </summary>
private void InitDefaultValue()
{
this.smbParameters.AndXCommand = SmbCommand.SMB_COM_NO_ANDX_COMMAND;
}
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Xml;
using System.Diagnostics;
using System.Xml.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;
using Microsoft.Research.DryadLinq.Internal;
namespace Microsoft.Research.DryadLinq
{
/// <summary>
/// This class explains in detail the generated plan.
/// </summary>
internal sealed class DryadLinqQueryExplain
{
/// <summary>
/// Visit the set of nodes in the query plan and build an explanation of the plan.
/// </summary>
/// <param name="plan">Return plan description here.</param>
/// <param name="nodes">Nodes to explain.</param>
internal void CodeShowVisit(StringBuilder plan, DLinqQueryNode[] nodes)
{
HashSet<DLinqQueryNode> visited = new HashSet<DLinqQueryNode>();
foreach (DLinqQueryNode n in nodes)
{
CodeShowVisit(plan, n, visited);
}
}
/// <summary>
/// Helper for CodeShowVisit: do not revisit a node twice.
/// </summary>
/// <param name="plan">Return plan here.</param>
/// <param name="n">Node to explain.</param>
/// <param name="visited">Set of nodes already visited.</param>
private void CodeShowVisit(StringBuilder plan, DLinqQueryNode n, HashSet<DLinqQueryNode> visited)
{
if (visited.Contains(n)) return;
visited.Add(n);
foreach (DLinqQueryNode c in n.Children)
{
CodeShowVisit(plan, c, visited);
}
ExplainNode(plan, n);
}
/// <summary>
/// Explain one query node.
/// </summary>
/// <param name="plan">Return plan here.</param>
/// <param name="n">Node to explain.</param>
internal static void ExplainNode(StringBuilder plan, DLinqQueryNode n)
{
if (n is DLinqTeeNode || n is DLinqOutputNode ||
n is DLinqDoWhileNode || n is DLinqDummyNode)
{
return;
}
else if (n is DLinqInputNode)
{
plan.AppendLine("Input:");
plan.Append("\t");
n.BuildString(plan);
plan.AppendLine();
return;
}
plan.Append(n.m_vertexEntryMethod);
plan.AppendLine(":");
HashSet<DLinqQueryNode> allchildren = new HashSet<DLinqQueryNode>();
if (n is DLinqSuperNode)
{
DLinqSuperNode sn = n as DLinqSuperNode;
List<DLinqQueryNode> tovisit = new List<DLinqQueryNode>();
tovisit.Add(sn.RootNode);
while (tovisit.Count > 0)
{
DLinqQueryNode t = tovisit[0];
tovisit.RemoveAt(0);
if (!(t is DLinqSuperNode))
allchildren.Add(t);
foreach (DLinqQueryNode tc in t.Children)
{
if (!allchildren.Contains(tc) && sn.Contains(tc))
tovisit.Add(tc);
}
}
}
else
{
allchildren.Add(n);
}
foreach (DLinqQueryNode nc in allchildren.Reverse())
{
Expression expression = null; // expression to print
List<string> additional = new List<string>(); // additional arguments to print
int argsToSkip = 0;
string methodname = nc.OpName;
plan.Append("\t");
if (nc is DLinqMergeNode)
{
expression = ((DLinqMergeNode)nc).ComparerExpression;
}
else if (nc is DLinqHashPartitionNode)
{
DLinqHashPartitionNode hp = (DLinqHashPartitionNode)nc;
expression = hp.KeySelectExpression;
additional.Add(hp.NumberOfPartitions.ToString());
}
else if (nc is DLinqGroupByNode)
{
DLinqGroupByNode gb = (DLinqGroupByNode)nc;
expression = gb.KeySelectExpression;
if (gb.ElemSelectExpression != null)
additional.Add(DryadLinqExpression.Summarize(gb.ElemSelectExpression));
if (gb.ResSelectExpression != null)
additional.Add(DryadLinqExpression.Summarize(gb.ResSelectExpression));
if (gb.ComparerExpression != null)
additional.Add(DryadLinqExpression.Summarize(gb.ComparerExpression));
if (gb.SeedExpression != null)
additional.Add(DryadLinqExpression.Summarize(gb.SeedExpression));
if (gb.AccumulatorExpression != null)
additional.Add(DryadLinqExpression.Summarize(gb.AccumulatorExpression));
}
else if (nc is DLinqOrderByNode)
{
DLinqOrderByNode ob = (DLinqOrderByNode)nc;
expression = ob.KeySelectExpression;
if (ob.ComparerExpression != null)
additional.Add(DryadLinqExpression.Summarize(ob.ComparerExpression));
}
else if (nc is DLinqWhereNode)
{
expression = ((DLinqWhereNode)nc).WhereExpression;
}
else if (nc is DLinqSelectNode)
{
DLinqSelectNode s = (DLinqSelectNode)nc;
expression = s.SelectExpression;
if (s.ResultSelectExpression != null)
additional.Add(DryadLinqExpression.Summarize(s.ResultSelectExpression));
}
else if (nc is DLinqAggregateNode)
{
DLinqAggregateNode a = (DLinqAggregateNode)nc;
expression = a.FuncLambda;
if (a.SeedExpression != null)
additional.Add(DryadLinqExpression.Summarize(a.SeedExpression));
if (a.ResultLambda != null)
additional.Add(DryadLinqExpression.Summarize(a.ResultLambda));
}
else if (nc is DLinqPartitionOpNode)
{
expression = ((DLinqPartitionOpNode)nc).ControlExpression;
}
else if (nc is DLinqJoinNode)
{
DLinqJoinNode j = (DLinqJoinNode)nc;
expression = j.OuterKeySelectorExpression;
additional.Add(DryadLinqExpression.Summarize(j.InnerKeySelectorExpression));
additional.Add(DryadLinqExpression.Summarize(j.ResultSelectorExpression));
if (j.ComparerExpression != null)
additional.Add(DryadLinqExpression.Summarize(j.ComparerExpression));
}
else if (nc is DLinqDistinctNode)
{
expression = ((DLinqDistinctNode)nc).ComparerExpression;
}
else if (nc is DLinqContainsNode)
{
DLinqContainsNode c = (DLinqContainsNode)nc;
expression = c.ValueExpression;
if (c.ComparerExpression != null)
additional.Add(DryadLinqExpression.Summarize(c.ComparerExpression));
}
else if (nc is DLinqBasicAggregateNode)
{
expression = ((DLinqBasicAggregateNode)nc).SelectExpression;
}
else if (nc is DLinqConcatNode)
// nothing to do
{
}
else if (nc is DLinqSetOperationNode)
{
expression = ((DLinqSetOperationNode)nc).ComparerExpression;
}
else if (nc is DLinqRangePartitionNode)
{
DLinqRangePartitionNode r = (DLinqRangePartitionNode)nc;
expression = r.CountExpression;
// TODO: there's some other possible interesting info
}
else if (nc is DLinqApplyNode)
{
expression = ((DLinqApplyNode)nc).LambdaExpression;
}
else if (nc is DLinqForkNode)
{
expression = ((DLinqForkNode)nc).ForkLambda;
}
else if (nc is DLinqTeeNode)
{
// nothing
}
else if (nc is DLinqDynamicNode)
{
// nothing
}
else
{
expression = nc.QueryExpression;
}
if (expression is MethodCallExpression)
{
MethodCallExpression mc = (MethodCallExpression)expression;
methodname = mc.Method.Name; // overwrite methodname
// determine which arguments to skip
#region LINQMETHODS
switch (mc.Method.Name)
{
case "Aggregate":
case "AggregateAsQuery":
case "Select":
case "LongSelect":
case "SelectMany":
case "LongSelectMany":
case "OfType":
case "Where":
case "LongWhere":
case "First":
case "FirstOrDefault":
case "FirstAsQuery":
case "Single":
case "SingleOrDefault":
case "SingleAsQuery":
case "Last":
case "LastOrDefault":
case "LastAsQuery":
case "Distinct":
case "Any":
case "AnyAsQuery":
case "All":
case "AllAsQuery":
case "Count":
case "CountAsQuery":
case "LongCount":
case "LongCountAsQuery":
case "Sum":
case "SumAsQuery":
case "Min":
case "MinAsQuery":
case "Max":
case "MaxAsQuery":
case "Average":
case "AverageAsQuery":
case "GroupBy":
case "OrderBy":
case "OrderByDescending":
case "ThenBy":
case "ThenByDescending":
case "Take":
case "TakeWhile":
case "LongTakeWhile":
case "Skip":
case "SkipWhile":
case "LongSkipWhile":
case "Contains":
case "ContainsAsQuery":
case "Reverse":
case "Merge":
case "HashPartition":
case "RangePartition":
case "Fork":
case "ForkChoose":
case "AssumeHashPartition":
case "AssumeRangePartition":
case "AssumeOrderBy":
case "ToPartitionedTableLazy":
case "AddCacheEntry":
case "SlidingWindow":
case "ApplyWithPartitionIndex":
case "DoWhile":
argsToSkip = 1;
break;
case "Join":
case "GroupJoin":
case "Concat":
case "MultiConcat":
case "Union":
case "Intersect":
case "Except":
case "SequenceEqual":
case "SequenceEqualAsQuery":
case "Zip":
argsToSkip = 2;
break;
case "Apply":
case "ApplyPerPartition":
if (mc.Arguments.Count < 3)
argsToSkip = 1;
else
argsToSkip = 2;
break;
default:
throw DryadLinqException.Create(DryadLinqErrorCode.OperatorNotSupported,
String.Format(SR.OperatorNotSupported, mc.Method.Name),
expression);
}
#endregion
plan.Append(methodname);
plan.Append("(");
int argno = 0;
foreach (var arg in mc.Arguments)
{
argno++;
if (argno <= argsToSkip) continue;
if (argno > argsToSkip + 1)
{
plan.Append(",");
}
plan.Append(DryadLinqExpression.Summarize(arg));
}
plan.AppendLine(")");
}
else
{
// expression is not methodcall
plan.Append(methodname);
plan.Append("(");
if (expression != null)
{
plan.Append(DryadLinqExpression.Summarize(expression));
}
foreach (string e in additional)
{
plan.Append(",");
plan.Append(e);
}
plan.AppendLine(")");
}
}
}
/// <summary>
/// Explain a query plan in terms of elementary operations.
/// </summary>
/// <param name="gen">Query generator.</param>
/// <returns>A string explaining the plan.</returns>
internal string Explain(DryadLinqQueryGen gen)
{
StringBuilder plan = new StringBuilder();
gen.CodeGenVisit();
this.CodeShowVisit(plan, gen.QueryPlan());
return plan.ToString();
}
}
/// <summary>
/// Summary information about a job query plan.
/// </summary>
internal class DryadLinqJobStaticPlan
{
/// <summary>
/// Connection between two stages.
/// </summary>
public class Connection
{
/// <summary>
/// Arity of connection.
/// </summary>
public enum ConnectionType
{
/// <summary>
/// Point-to-point connection between two stages.
/// </summary>
PointToPoint,
/// <summary>
/// Cross-product connection between two stages.
/// </summary>
AllToAll
};
/// <summary>
/// Type of channel backing the connection.
/// </summary>
public enum ChannelType
{
/// <summary>
/// Persistent file.
/// </summary>
DiskFile,
/// <summary>
/// In-memory fifo.
/// </summary>
Fifo,
/// <summary>
/// TCP pipe.
/// </summary>
TCP
}
/// <summary>
/// Stage originating the connection.
/// </summary>
public Stage From { internal set; get; }
/// <summary>
/// Stage terminating the connection.
/// </summary>
public Stage To { internal set; get; }
/// <summary>
/// Type of connection.
/// </summary>
public ConnectionType Arity { get; internal set; }
/// <summary>
/// Type of channel backing the connection.
/// </summary>
public ChannelType ChannelKind { get; internal set; }
/// <summary>
/// Dynamic manager associated with the connection.
/// </summary>
public string ConnectionManager { get; internal set; }
/// <summary>
/// Color used to represent the connection.
/// </summary>
/// <returns>A string describing the color.</returns>
public string Color()
{
switch (this.ChannelKind)
{
case ChannelType.DiskFile:
return "black";
case ChannelType.Fifo:
return "red";
case ChannelType.TCP:
return "yellow";
default:
throw new Exception(String.Format(SR.UnknownChannelType, this.ChannelKind.ToString()));
}
}
}
/// <summary>
/// Per-node connection information (should be per-edge...)
/// </summary>
struct ConnectionInformation
{
/// <summary>
/// Type of connection.
/// </summary>
public Connection.ConnectionType Arity { get; internal set; }
/// <summary>
/// Type of channel backing the connection.
/// </summary>
public Connection.ChannelType ChannelKind { get; internal set; }
/// <summary>
/// Dynamic manager associated with the connection.
/// </summary>
public string ConnectionManager { get; internal set; }
}
/// <summary>
/// Information about a stage.
/// </summary>
public class Stage
{
/// <summary>
/// Stage name.
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// Code executed in the stage.
/// </summary>
public string[] Code { get; internal set; }
/// <summary>
/// DryadLINQ operator implemented by the stage.
/// </summary>
public string Operator { get; internal set; }
/// <summary>
/// Number of vertices in stage.
/// </summary>
public int Replication { get; internal set; }
/// <summary>
/// Unique identifier.
/// </summary>
public int Id { get; set; }
/// <summary>
/// True if the stage is an input.
/// </summary>
public bool IsInput { get; internal set; }
/// <summary>
/// True if the stage is an output.
/// </summary>
public bool IsOutput { get; internal set; }
/// <summary>
/// True if the stage is a tee.
/// </summary>
public bool IsTee { get; internal set; }
/// <summary>
/// True if the stage is a concatenation.
/// </summary>
public bool IsConcat { get; internal set; }
/// <summary>
/// True if the stage is virtual (no real vertices synthesized).
/// </summary>
public bool IsVirtual { get { return this.IsInput || this.IsOutput || this.IsTee || this.IsConcat; } }
/// <summary>
/// Only defined for tables.
/// </summary>
public string Uri { get; internal set; }
/// <summary>
/// Only defined for tables.
/// </summary>
public string UriType { get; internal set; }
}
/// <summary>
/// File containing the plan.
/// </summary>
string xmlPlanFile;
/// <summary>
/// Map from stage id to stage.
/// </summary>
Dictionary<int, Stage> stages;
/// <summary>
/// List of inter-stage connections in the plan.
/// </summary>
List<Connection> connections;
/// <summary>
/// Store here per-node connection information (map from node id).
/// </summary>
Dictionary<int, ConnectionInformation> perNodeConnectionInfo;
/// <summary>
/// Create a dryadlinq job plan starting from an xml plan file.
/// </summary>
/// <param name="xmlPlanFile">Plan file to parse.</param>
public DryadLinqJobStaticPlan(string xmlPlanFile)
{
this.stages = new Dictionary<int, Stage>();
this.connections = new List<Connection>();
this.perNodeConnectionInfo = new Dictionary<int, ConnectionInformation>();
this.xmlPlanFile = xmlPlanFile;
this.ParseQueryPlan();
}
/// <summary>
/// Parse an XML query plan and represent that information.
/// </summary>
private void ParseQueryPlan()
{
if (!File.Exists(this.xmlPlanFile))
throw new Exception(String.Format( SR.CannotReadQueryPlan , this.xmlPlanFile));
XDocument plan = XDocument.Load(this.xmlPlanFile);
XElement query = plan.Root.Elements().Where(e => e.Name == "QueryPlan").First();
IEnumerable<XElement> vertices = query.Elements().Where(e => e.Name == "Vertex");
foreach (XElement v in vertices)
{
Stage stage = new Stage();
stage.Id = int.Parse(v.Element("UniqueId").Value);
stage.Replication = int.Parse(v.Element("Partitions").Value);
stage.Operator = v.Element("Type").Value;
stage.Name = v.Element("Name").Value;
{
string code = v.Element("Explain").Value;
stage.Code = code.Split('\n').
Skip(1). // drop stage name
Select(l => l.Trim()). // remove leading tab
ToArray();
}
this.stages.Add(stage.Id, stage);
{
// These should be connection attributes, not stage attributes.
string cht = v.Element("ChannelType").Value;
string connectionManager = v.Element("DynamicManager").Element("Type").Value;
string connection = v.Element("ConnectionOperator").Value;
ConnectionInformation info = new ConnectionInformation();
info.ConnectionManager = connectionManager;
switch (connection)
{
case "Pointwise":
info.Arity = Connection.ConnectionType.PointToPoint;
break;
case "CrossProduct":
info.Arity = Connection.ConnectionType.AllToAll;
break;
default:
throw new Exception(String.Format( SR.UnknownConnectionType , connection));
}
switch (cht)
{
case "DiskFile":
info.ChannelKind = Connection.ChannelType.DiskFile;
break;
case "TCPPipe":
info.ChannelKind = Connection.ChannelType.TCP;
break;
case "MemoryFIFO":
info.ChannelKind = Connection.ChannelType.Fifo;
break;
default:
throw new Exception(String.Format( SR.UnknownChannelType2 , cht));
}
this.perNodeConnectionInfo.Add(stage.Id, info);
}
switch (stage.Operator)
{
case "InputTable":
stage.IsInput = true;
stage.UriType = v.Element("StorageSet").Element("Type").Value;
stage.Uri = v.Element("StorageSet").Element("SourceURI").Value;
break;
case "OutputTable":
stage.IsOutput = true;
stage.UriType = v.Element("StorageSet").Element("Type").Value;
stage.Uri = v.Element("StorageSet").Element("SinkURI").Value;
break;
case "Tee":
stage.IsTee = true;
break;
case "Concat":
stage.IsConcat = true;
break;
default:
break;
}
if (v.Elements("Children").Count() == 0)
continue;
bool first = true;
IEnumerable<XElement> children = v.Element("Children").Elements().Where(e => e.Name == "Child");
foreach (XElement child in children)
{
// This code parallels the graphbuilder.cpp for XmlExecHost
Connection conn = new Connection();
int fromid = int.Parse(child.Element("UniqueId").Value);
ConnectionInformation fromConnectionInformation = this.perNodeConnectionInfo[fromid];
Stage from = this.stages[fromid];
conn.From = from;
conn.To = stage;
conn.ChannelKind = fromConnectionInformation.ChannelKind;
switch (fromConnectionInformation.ConnectionManager)
{
case "FullAggregator":
case "HashDistributor":
case "RangeDistributor":
// Ignore except first child
if (first)
{
first = false;
conn.ConnectionManager = fromConnectionInformation.ConnectionManager;
}
else
{
conn.ConnectionManager = "";
}
break;
case "PartialAggregator":
case "Broadcast":
// All children have the same connection manager
conn.ConnectionManager = fromConnectionInformation.ConnectionManager;
break;
case "Splitter":
// The connection manager depends on the number of children
if (first)
{
first = false;
if (children.Count() == 1)
conn.ConnectionManager = fromConnectionInformation.ConnectionManager;
else
conn.ConnectionManager = "SemiSplitter";
}
else
{
conn.ConnectionManager = "";
}
break;
case "None":
case "":
break;
}
conn.Arity = fromConnectionInformation.Arity;
this.connections.Add(conn);
}
}
}
/// <summary>
/// Find the stage given the stage id as a string.
/// </summary>
/// <param name="stageId">Stage id.</param>
/// <returns>A handle to the stage with the specified static Id.</returns>
public Stage GetStageByStaticId(string stageId)
{
int id = int.Parse(stageId);
return this.stages[id];
}
/// <summary>
/// Find the stage given the stage name.
/// </summary>
/// <param name="name">Name of stage to return.</param>
/// <returns>The stage with the given name or null.</returns>
public Stage GetStageByName(string name)
{
foreach (Stage s in this.stages.Values)
{
if (s.Name.Equals(name))
return s;
}
return null;
}
/// <summary>
/// The list of all stages in the plan.
/// </summary>
/// <returns>An iterator over the list of stages.</returns>
public IEnumerable<Stage> GetAllStages()
{
return this.stages.Values;
}
/// <summary>
/// The list of all connections in the plan.
/// </summary>
/// <returns>An iterator over a list of connections.</returns>
public IEnumerable<Connection> GetAllConnections()
{
return this.connections;
}
}
}
| |
// 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.Dynamic.Utils;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;
using AstUtils = System.Linq.Expressions.Utils;
namespace System.Linq.Expressions.Interpreter
{
public partial class LightLambda
{
private readonly IStrongBox[] _closure;
private readonly Interpreter _interpreter;
#if NO_FEATURE_STATIC_DELEGATE
private static readonly CacheDict<Type, Func<LightLambda, Delegate>> _runCache = new CacheDict<Type, Func<LightLambda, Delegate>>(100);
#endif
// Adaptive compilation support
private readonly LightDelegateCreator _delegateCreator;
internal LightLambda(LightDelegateCreator delegateCreator, IStrongBox[] closure)
{
_delegateCreator = delegateCreator;
_closure = closure;
_interpreter = delegateCreator.Interpreter;
}
#if NO_FEATURE_STATIC_DELEGATE
private static Func<LightLambda, Delegate> GetRunDelegateCtor(Type delegateType)
{
lock (_runCache)
{
Func<LightLambda, Delegate> fastCtor;
if (_runCache.TryGetValue(delegateType, out fastCtor))
{
return fastCtor;
}
return MakeRunDelegateCtor(delegateType);
}
}
private static Func<LightLambda, Delegate> MakeRunDelegateCtor(Type delegateType)
{
var method = delegateType.GetMethod("Invoke");
var paramInfos = method.GetParameters();
Type[] paramTypes;
string name = "Run";
if (paramInfos.Length >= MaxParameters)
{
return null;
}
if (method.ReturnType == typeof(void))
{
name += "Void";
paramTypes = new Type[paramInfos.Length];
}
else
{
paramTypes = new Type[paramInfos.Length + 1];
paramTypes[paramTypes.Length - 1] = method.ReturnType;
}
MethodInfo runMethod;
if (method.ReturnType == typeof(void) && paramTypes.Length == 2 &&
paramInfos[0].ParameterType.IsByRef && paramInfos[1].ParameterType.IsByRef)
{
runMethod = typeof(LightLambda).GetMethod("RunVoidRef2", BindingFlags.NonPublic | BindingFlags.Instance);
paramTypes[0] = paramInfos[0].ParameterType.GetElementType();
paramTypes[1] = paramInfos[1].ParameterType.GetElementType();
}
else if (method.ReturnType == typeof(void) && paramTypes.Length == 0)
{
runMethod = typeof(LightLambda).GetMethod("RunVoid0", BindingFlags.NonPublic | BindingFlags.Instance);
}
else
{
for (int i = 0; i < paramInfos.Length; i++)
{
paramTypes[i] = paramInfos[i].ParameterType;
if (paramTypes[i].IsByRef)
{
return null;
}
}
#if FEATURE_MAKE_RUN_METHODS
if (DelegateHelpers.MakeDelegate(paramTypes) == delegateType)
{
name = "Make" + name + paramInfos.Length;
MethodInfo ctorMethod = typeof(LightLambda).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(paramTypes);
return _runCache[delegateType] = (Func<LightLambda, Delegate>)ctorMethod.CreateDelegate(typeof(Func<LightLambda, Delegate>));
}
#endif
runMethod = typeof(LightLambda).GetMethod(name + paramInfos.Length, BindingFlags.NonPublic | BindingFlags.Instance);
}
/*
try {
DynamicMethod dm = new DynamicMethod("FastCtor", typeof(Delegate), new[] { typeof(LightLambda) }, typeof(LightLambda), true);
var ilgen = dm.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Ldftn, runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod);
ilgen.Emit(OpCodes.Newobj, delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) }));
ilgen.Emit(OpCodes.Ret);
return _runCache[delegateType] = (Func<LightLambda, Delegate>)dm.CreateDelegate(typeof(Func<LightLambda, Delegate>));
} catch (SecurityException) {
}*/
// we don't have permission for restricted skip visibility dynamic methods, use the slower Delegate.CreateDelegate.
var targetMethod = runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod;
return _runCache[delegateType] = lambda => targetMethod.CreateDelegate(delegateType, lambda);
}
//TODO enable sharing of these custom delegates
private Delegate CreateCustomDelegate(Type delegateType)
{
//PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Synchronously compiling a custom delegate");
var method = delegateType.GetMethod("Invoke");
var paramInfos = method.GetParameters();
var parameters = new ParameterExpression[paramInfos.Length];
var parametersAsObject = new Expression[paramInfos.Length];
bool hasByRef = false;
for (int i = 0; i < paramInfos.Length; i++)
{
ParameterExpression parameter = Expression.Parameter(paramInfos[i].ParameterType, paramInfos[i].Name);
hasByRef = hasByRef || paramInfos[i].ParameterType.IsByRef;
parameters[i] = parameter;
parametersAsObject[i] = Expression.Convert(parameter, typeof(object));
}
var data = Expression.NewArrayInit(typeof(object), parametersAsObject);
var dlg = new Func<object[], object>(Run);
var dlgExpr = AstUtils.Constant(dlg);
var argsParam = Expression.Parameter(typeof(object[]), "$args");
Expression body;
if (method.ReturnType == typeof(void))
{
body = Expression.Block(typeof(void), Expression.Invoke(dlgExpr, argsParam));
}
else
{
body = Expression.Convert(Expression.Invoke(dlgExpr, argsParam), method.ReturnType);
}
if (hasByRef)
{
List<Expression> updates = new List<Expression>();
for (int i = 0; i < paramInfos.Length; i++)
{
if (paramInfos[i].ParameterType.IsByRef)
{
updates.Add(
Expression.Assign(
parameters[i],
Expression.Convert(
Expression.ArrayAccess(argsParam, Expression.Constant(i)),
paramInfos[i].ParameterType.GetElementType()
)
)
);
}
}
body = Expression.TryFinally(body, Expression.Block(typeof(void), updates));
}
body = Expression.Block(
method.ReturnType,
new[] { argsParam },
Expression.Assign(argsParam, data),
body
);
var lambda = Expression.Lambda(delegateType, body, parameters);
//return System.Linq.Expressions.Compiler.LambdaCompiler.Compile(lambda, null);
throw new NotImplementedException("byref delegate");
}
#endif
internal Delegate MakeDelegate(Type delegateType)
{
#if !NO_FEATURE_STATIC_DELEGATE
var method = delegateType.GetMethod("Invoke");
if (method.ReturnType == typeof(void))
{
return System.Dynamic.Utils.DelegateHelpers.CreateObjectArrayDelegate(delegateType, RunVoid);
}
else
{
return System.Dynamic.Utils.DelegateHelpers.CreateObjectArrayDelegate(delegateType, Run);
}
#else
Func<LightLambda, Delegate> fastCtor = GetRunDelegateCtor(delegateType);
if (fastCtor != null)
{
return fastCtor(this);
}
else
{
return CreateCustomDelegate(delegateType);
}
#endif
}
private InterpretedFrame MakeFrame()
{
return new InterpretedFrame(_interpreter, _closure);
}
#if NO_FEATURE_STATIC_DELEGATE
[EnableInvokeTesting]
internal void RunVoidRef2<T0, T1>(ref T0 arg0, ref T1 arg1)
{
// copy in and copy out for today...
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
var currentFrame = frame.Enter();
try
{
_interpreter.Run(frame);
}
finally
{
frame.Leave(currentFrame);
arg0 = (T0)frame.Data[0];
arg1 = (T1)frame.Data[1];
}
}
#endif
public object Run(params object[] arguments)
{
var frame = MakeFrame();
for (int i = 0; i < arguments.Length; i++)
{
frame.Data[i] = arguments[i];
}
var currentFrame = frame.Enter();
try
{
_interpreter.Run(frame);
}
finally
{
for (int i = 0; i < arguments.Length; i++)
{
arguments[i] = frame.Data[i];
}
frame.Leave(currentFrame);
}
return frame.Pop();
}
public object RunVoid(params object[] arguments)
{
var frame = MakeFrame();
for (int i = 0; i < arguments.Length; i++)
{
frame.Data[i] = arguments[i];
}
var currentFrame = frame.Enter();
try
{
_interpreter.Run(frame);
}
finally
{
for (int i = 0; i < arguments.Length; i++)
{
arguments[i] = frame.Data[i];
}
frame.Leave(currentFrame);
}
return null;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class DkmUtilities
{
private static readonly Guid s_symUnmanagedReaderClassId = Guid.Parse("B4CE6286-2A6B-3712-A3B7-1EE1DAD467B5");
internal unsafe delegate IntPtr GetMetadataBytesPtrFunction(AssemblyIdentity assemblyIdentity, out uint uSize);
private static IEnumerable<DkmClrModuleInstance> GetModulesInAppDomain(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain)
{
if (appDomain.IsUnloaded)
{
return SpecializedCollections.EmptyEnumerable<DkmClrModuleInstance>();
}
var appDomainId = appDomain.Id;
return runtime.GetModuleInstances().
Cast<DkmClrModuleInstance>().
Where(module =>
{
var moduleAppDomain = module.AppDomain;
return !moduleAppDomain.IsUnloaded && (moduleAppDomain.Id == appDomainId);
});
}
internal unsafe static ImmutableArray<MetadataBlock> GetMetadataBlocks(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain)
{
var builder = ArrayBuilder<MetadataBlock>.GetInstance();
IntPtr ptr;
uint size;
foreach (DkmClrModuleInstance module in runtime.GetModulesInAppDomain(appDomain))
{
MetadataBlock block;
try
{
ptr = module.GetMetaDataBytesPtr(out size);
Debug.Assert(size > 0);
block = GetMetadataBlock(ptr, size);
}
catch (Exception e) when (MetadataUtilities.IsBadOrMissingMetadataException(e, module.FullName))
{
continue;
}
Debug.Assert(block.ModuleVersionId == module.Mvid);
builder.Add(block);
}
// Include "intrinsic method" assembly.
ptr = runtime.GetIntrinsicAssemblyMetaDataBytesPtr(out size);
builder.Add(GetMetadataBlock(ptr, size));
return builder.ToImmutableAndFree();
}
internal static ImmutableArray<MetadataBlock> GetMetadataBlocks(GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities)
{
ArrayBuilder<MetadataBlock> builder = null;
foreach (AssemblyIdentity missingAssemblyIdentity in missingAssemblyIdentities)
{
MetadataBlock block;
try
{
uint size;
IntPtr ptr;
ptr = getMetaDataBytesPtrFunction(missingAssemblyIdentity, out size);
Debug.Assert(size > 0);
block = GetMetadataBlock(ptr, size);
}
catch (Exception e) when (MetadataUtilities.IsBadOrMissingMetadataException(e, missingAssemblyIdentity.GetDisplayName()))
{
continue;
}
if (builder == null)
{
builder = ArrayBuilder<MetadataBlock>.GetInstance();
}
builder.Add(block);
}
return builder == null ? ImmutableArray<MetadataBlock>.Empty : builder.ToImmutableAndFree();
}
internal static ImmutableArray<AssemblyReaders> MakeAssemblyReaders(this DkmClrInstructionAddress instructionAddress)
{
var builder = ArrayBuilder<AssemblyReaders>.GetInstance();
foreach (DkmClrModuleInstance module in instructionAddress.RuntimeInstance.GetModulesInAppDomain(instructionAddress.ModuleInstance.AppDomain))
{
var symReader = module.GetSymReader();
if (symReader == null)
{
continue;
}
MetadataReader reader;
unsafe
{
try
{
uint size;
IntPtr ptr;
ptr = module.GetMetaDataBytesPtr(out size);
Debug.Assert(size > 0);
reader = new MetadataReader((byte*)ptr, (int)size);
}
catch (Exception e) when (MetadataUtilities.IsBadOrMissingMetadataException(e, module.FullName))
{
continue;
}
}
builder.Add(new AssemblyReaders(reader, symReader));
}
return builder.ToImmutableAndFree();
}
private unsafe static MetadataBlock GetMetadataBlock(IntPtr ptr, uint size)
{
var reader = new MetadataReader((byte*)ptr, (int)size);
var moduleDef = reader.GetModuleDefinition();
var moduleVersionId = reader.GetGuid(moduleDef.Mvid);
var generationId = reader.GetGuid(moduleDef.GenerationId);
return new MetadataBlock(moduleVersionId, generationId, ptr, (int)size);
}
internal static object GetSymReader(this DkmClrModuleInstance clrModule)
{
var module = clrModule.Module; // Null if there are no symbols.
return (module == null) ? null : module.GetSymbolInterface(s_symUnmanagedReaderClassId);
}
internal static DkmCompiledClrInspectionQuery ToQueryResult(
this CompileResult compResult,
DkmCompilerId languageId,
ResultProperties resultProperties,
DkmClrRuntimeInstance runtimeInstance)
{
if (compResult == null)
{
return null;
}
Debug.Assert(compResult.Assembly != null);
Debug.Assert(compResult.TypeName != null);
Debug.Assert(compResult.MethodName != null);
return DkmCompiledClrInspectionQuery.Create(
runtimeInstance,
Binary: new ReadOnlyCollection<byte>(compResult.Assembly),
DataContainer: null,
LanguageId: languageId,
TypeName: compResult.TypeName,
MethodName: compResult.MethodName,
FormatSpecifiers: compResult.FormatSpecifiers,
CompilationFlags: resultProperties.Flags,
ResultCategory: resultProperties.Category,
Access: resultProperties.AccessType,
StorageType: resultProperties.StorageType,
TypeModifierFlags: resultProperties.ModifierFlags,
CustomTypeInfo: compResult.GetCustomTypeInfo().ToDkmClrCustomTypeInfo());
}
internal static ResultProperties GetResultProperties<TSymbol>(this TSymbol symbol, DkmClrCompilationResultFlags flags, bool isConstant)
where TSymbol : ISymbol
{
var haveSymbol = symbol != null;
var category = haveSymbol
? GetResultCategory(symbol.Kind)
: DkmEvaluationResultCategory.Data;
var accessType = haveSymbol
? GetResultAccessType(symbol.DeclaredAccessibility)
: DkmEvaluationResultAccessType.None;
var storageType = haveSymbol && symbol.IsStatic
? DkmEvaluationResultStorageType.Static
: DkmEvaluationResultStorageType.None;
var modifierFlags = DkmEvaluationResultTypeModifierFlags.None;
if (isConstant)
{
modifierFlags = DkmEvaluationResultTypeModifierFlags.Constant;
}
else if (!haveSymbol)
{
// No change.
}
else if (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride)
{
modifierFlags = DkmEvaluationResultTypeModifierFlags.Virtual;
}
else if (symbol.Kind == SymbolKind.Field && ((IFieldSymbol)symbol).IsVolatile)
{
modifierFlags = DkmEvaluationResultTypeModifierFlags.Volatile;
}
// CONSIDER: for completeness, we could check for [MethodImpl(MethodImplOptions.Synchronized)]
// and set DkmEvaluationResultTypeModifierFlags.Synchronized, but it doesn't seem to have any
// impact on the UI. It is exposed through the DTE, but cscompee didn't set the flag either.
return new ResultProperties(flags, category, accessType, storageType, modifierFlags);
}
private static DkmEvaluationResultCategory GetResultCategory(SymbolKind kind)
{
switch (kind)
{
case SymbolKind.Method:
return DkmEvaluationResultCategory.Method;
case SymbolKind.Property:
return DkmEvaluationResultCategory.Property;
default:
return DkmEvaluationResultCategory.Data;
}
}
private static DkmEvaluationResultAccessType GetResultAccessType(Accessibility accessibility)
{
switch (accessibility)
{
case Accessibility.Public:
return DkmEvaluationResultAccessType.Public;
case Accessibility.Protected:
return DkmEvaluationResultAccessType.Protected;
case Accessibility.Private:
return DkmEvaluationResultAccessType.Private;
case Accessibility.Internal:
case Accessibility.ProtectedOrInternal: // Dev12 treats this as "internal"
case Accessibility.ProtectedAndInternal: // Dev12 treats this as "internal"
return DkmEvaluationResultAccessType.Internal;
case Accessibility.NotApplicable:
return DkmEvaluationResultAccessType.None;
default:
throw ExceptionUtilities.UnexpectedValue(accessibility);
}
}
internal static bool Includes(this DkmVariableInfoFlags flags, DkmVariableInfoFlags desired)
{
return (flags & desired) == desired;
}
internal static TMetadataContext GetMetadataContext<TMetadataContext>(this DkmClrAppDomain appDomain)
where TMetadataContext : struct
{
var dataItem = appDomain.GetDataItem<MetadataContextItem<TMetadataContext>>();
return (dataItem == null) ? default(TMetadataContext) : dataItem.MetadataContext;
}
internal static void SetMetadataContext<TMetadataContext>(this DkmClrAppDomain appDomain, TMetadataContext context)
where TMetadataContext : struct
{
appDomain.SetDataItem(DkmDataCreationDisposition.CreateAlways, new MetadataContextItem<TMetadataContext>(context));
}
internal static void RemoveMetadataContext<TMetadataContext>(this DkmClrAppDomain appDomain)
where TMetadataContext : struct
{
appDomain.RemoveDataItem<MetadataContextItem<TMetadataContext>>();
}
private sealed class MetadataContextItem<TMetadataContext> : DkmDataItem
where TMetadataContext : struct
{
internal readonly TMetadataContext MetadataContext;
internal MetadataContextItem(TMetadataContext metadataContext)
{
this.MetadataContext = metadataContext;
}
}
}
}
| |
//
// Manager.cs
//
// Author:
// Alex Launi <alex.launi@gmail.com>
//
// Copyright (c) 2010 Alex Launi
//
// 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.
#if ENABLE_GIO_HARDWARE
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using GLib;
using GUdev;
using System.Runtime.InteropServices;
using Banshee.Hardware;
namespace Banshee.Hardware.Gio
{
public class Manager : IEnumerable<IDevice>, IDisposable
{
private readonly string[] subsystems = new string[] {"block", "usb"};
private Client client;
private VolumeMonitor monitor;
// When a device is unplugged we need to be able to map the Gio.Volume to the
// GUDev.Device as the device will already be gone from udev. We use the native
// handle for the Gio volume as the key to link it to the correct gudev device.
private Dictionary<IntPtr, GUdev.Device> volume_device_map;
public event EventHandler<MountArgs> DeviceAdded;
public event EventHandler<MountArgs> DeviceRemoved;
public Manager ()
{
client = new Client (subsystems);
monitor = VolumeMonitor.Default;
monitor.MountAdded += HandleMonitorMountAdded;
monitor.MountRemoved += HandleMonitorMountRemoved;
monitor.VolumeRemoved += HandleMonitorVolumeRemoved;
volume_device_map= new Dictionary<IntPtr, GUdev.Device> ();
}
#region IDisposable
public void Dispose ()
{
client.Dispose ();
monitor.Dispose ();
}
#endregion
void HandleMonitorMountAdded (object o, MountAddedArgs args)
{
// Manually get the mount as gio-sharp translates it to the wrong managed object
var mount = GLib.MountAdapter.GetObject ((GLib.Object) args.Args [0]);
if (mount.Volume == null)
return;
var device = GudevDeviceFromGioMount (mount);
volume_device_map [mount.Volume.Handle] = device;
var h = DeviceAdded;
if (h != null) {
var v = new RawVolume (mount.Volume,
this,
new GioVolumeMetadataSource (mount.Volume),
new UdevMetadataSource (device));
h (this, new MountArgs (HardwareManager.Resolve (new Device (v))));
}
}
void HandleMonitorMountRemoved (object o, MountRemovedArgs args)
{
// Manually get the mount as gio-sharp translates it to the wrong managed object
var mount = GLib.MountAdapter.GetObject ((GLib.Object) args.Args [0]);
if (mount.Volume == null) {
return;
}
VolumeRemoved (mount.Volume);
}
void HandleMonitorVolumeRemoved (object o, VolumeRemovedArgs args)
{
var volume = GLib.VolumeAdapter.GetObject ((GLib.Object) args.Args [0]);
if (volume == null) {
return;
}
VolumeRemoved (volume);
}
void VolumeRemoved (GLib.Volume volume)
{
var h = DeviceRemoved;
if (h != null) {
GUdev.Device device;
if (!volume_device_map.TryGetValue (volume.Handle, out device)) {
Hyena.Log.Debug (string.Format ("Tried to unmount {0}/{1} with no matching udev device", volume.Name, volume.Uuid));
return;
}
var v = new RawVolume (volume,
this,
new GioVolumeMetadataSource (volume),
new UdevMetadataSource (device));
h (this, new MountArgs (new Device (v)));
}
}
public IEnumerable<IDevice> GetAllDevices ()
{
foreach (GLib.Volume vol in monitor.Volumes) {
var device = GudevDeviceFromGioVolume (vol);
if (device == null) {
continue;
}
volume_device_map [vol.Handle] = device;
var raw = new RawVolume (vol,
this,
new GioVolumeMetadataSource (vol),
new UdevMetadataSource (device));
yield return HardwareManager.Resolve (new Device (raw));
}
}
public GUdev.Device GudevDeviceFromSubsystemPropertyValue (string sub, string prop, string val)
{
foreach (GUdev.Device dev in client.QueryBySubsystem (sub)) {
if (dev.HasProperty (prop) && dev.GetProperty (prop) == val)
return dev;
}
return null;
}
public GUdev.Device GudevDeviceFromGioDrive (GLib.Drive drive)
{
GUdev.Device device = null;
if (drive == null) {
return null;
}
string devFile = drive.GetIdentifier ("unix-device");
if (!String.IsNullOrEmpty (devFile)) {
device = client.QueryByDeviceFile (devFile);
}
return device;
}
public GUdev.Device GudevDeviceFromGioVolume (GLib.Volume volume)
{
GUdev.Device device = null;
if (volume == null) {
return null;
}
var s = volume.GetIdentifier ("unix-device");
if (!String.IsNullOrEmpty (s)) {
device = client.QueryByDeviceFile (s);
}
if (device == null) {
s = volume.Uuid;
foreach (GUdev.Device d in client.QueryBySubsystem ("usb")) {
if (s == d.GetSysfsAttr ("serial")) {
device = d;
break;
}
}
}
return device;
}
public GUdev.Device GudevDeviceFromGioMount (GLib.Mount mount)
{
if (mount == null) {
return null;
}
return GudevDeviceFromGioVolume (mount.Volume);
}
#region IEnumerable
public IEnumerator<IDevice> GetEnumerator ()
{
foreach (var device in GetAllDevices ())
yield return device;
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
#endregion
}
public class MountArgs : EventArgs
{
public IDevice Device {
get; private set;
}
public MountArgs (IDevice device)
{
Device = device;
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using Internal.Runtime;
namespace Internal.Runtime.CompilerHelpers
{
/// <summary>
/// Math helpers for generated code. The helpers marked with [RuntimeExport] and the type
/// itself need to be public because they constitute a public contract with the .NET Native toolchain.
/// </summary>
[CLSCompliant(false)]
public static class MathHelpers
{
#if !BIT64
//
// 64-bit checked multiplication for 32-bit platforms
//
// Helper to multiply two 32-bit uints
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static UInt64 Mul32x32To64(UInt32 a, UInt32 b)
{
return a * (UInt64)b;
}
// Helper to get high 32-bit of 64-bit int
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static UInt32 Hi32Bits(Int64 a)
{
return (UInt32)(a >> 32);
}
// Helper to get high 32-bit of 64-bit int
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static UInt32 Hi32Bits(UInt64 a)
{
return (UInt32)(a >> 32);
}
[RuntimeExport("LMulOvf")]
public static Int64 LMulOvf(Int64 i, Int64 j)
{
Int64 ret;
// Remember the sign of the result
Int32 sign = (Int32)(Hi32Bits(i) ^ Hi32Bits(j));
// Convert to unsigned multiplication
if (i < 0) i = -i;
if (j < 0) j = -j;
// Get the upper 32 bits of the numbers
UInt32 val1High = Hi32Bits(i);
UInt32 val2High = Hi32Bits(j);
UInt64 valMid;
if (val1High == 0)
{
// Compute the 'middle' bits of the long multiplication
valMid = Mul32x32To64(val2High, (UInt32)i);
}
else
{
if (val2High != 0)
goto ThrowExcep;
// Compute the 'middle' bits of the long multiplication
valMid = Mul32x32To64(val1High, (UInt32)j);
}
// See if any bits after bit 32 are set
if (Hi32Bits(valMid) != 0)
goto ThrowExcep;
ret = (Int64)(Mul32x32To64((UInt32)i, (UInt32)j) + (valMid << 32));
// check for overflow
if (Hi32Bits(ret) < (UInt32)valMid)
goto ThrowExcep;
if (sign >= 0)
{
// have we spilled into the sign bit?
if (ret < 0)
goto ThrowExcep;
}
else
{
ret = -ret;
// have we spilled into the sign bit?
if (ret > 0)
goto ThrowExcep;
}
return ret;
ThrowExcep:
return ThrowLngOvf();
}
[RuntimeExport("ULMulOvf")]
public static UInt64 ULMulOvf(UInt64 i, UInt64 j)
{
UInt64 ret;
// Get the upper 32 bits of the numbers
UInt32 val1High = Hi32Bits(i);
UInt32 val2High = Hi32Bits(j);
UInt64 valMid;
if (val1High == 0)
{
if (val2High == 0)
return Mul32x32To64((UInt32)i, (UInt32)j);
// Compute the 'middle' bits of the long multiplication
valMid = Mul32x32To64(val2High, (UInt32)i);
}
else
{
if (val2High != 0)
goto ThrowExcep;
// Compute the 'middle' bits of the long multiplication
valMid = Mul32x32To64(val1High, (UInt32)j);
}
// See if any bits after bit 32 are set
if (Hi32Bits(valMid) != 0)
goto ThrowExcep;
ret = Mul32x32To64((UInt32)i, (UInt32)j) + (valMid << 32);
// check for overflow
if (Hi32Bits(ret) < (UInt32)valMid)
goto ThrowExcep;
return ret;
ThrowExcep:
return ThrowULngOvf();
}
#endif // BIT64
[RuntimeExport("Dbl2IntOvf")]
public static int Dbl2IntOvf(double val)
{
const double two31 = 2147483648.0;
// Note that this expression also works properly for val = NaN case
if (val > -two31 - 1 && val < two31)
return unchecked((int)val);
return ThrowIntOvf();
}
[RuntimeExport("Dbl2UIntOvf")]
public static uint Dbl2UIntOvf(double val)
{
// Note that this expression also works properly for val = NaN case
if (val > -1.0 && val < 4294967296.0)
return unchecked((uint)val);
return ThrowUIntOvf();
}
[RuntimeExport("Dbl2LngOvf")]
public static long Dbl2LngOvf(double val)
{
const double two63 = 2147483648.0 * 4294967296.0;
// Note that this expression also works properly for val = NaN case
// We need to compare with the very next double to two63. 0x402 is epsilon to get us there.
if (val > -two63 - 0x402 && val < two63)
return unchecked((long)val);
return ThrowLngOvf();
}
[RuntimeExport("Dbl2ULngOvf")]
public static ulong Dbl2ULngOvf(double val)
{
const double two64 = 2.0 * 2147483648.0 * 4294967296.0;
// Note that this expression also works properly for val = NaN case
if (val < two64)
return unchecked((ulong)val);
return ThrowULngOvf();
}
[RuntimeExport("Flt2IntOvf")]
public static int Flt2IntOvf(float val)
{
const double two31 = 2147483648.0;
// Note that this expression also works properly for val = NaN case
if (val > -two31 - 1 && val < two31)
return ((int)val);
return ThrowIntOvf();
}
[RuntimeExport("Flt2LngOvf")]
public static long Flt2LngOvf(float val)
{
const double two63 = 2147483648.0 * 4294967296.0;
// Note that this expression also works properly for val = NaN case
// We need to compare with the very next double to two63. 0x402 is epsilon to get us there.
if (val > -two63 - 0x402 && val < two63)
return ((Int64)val);
return ThrowIntOvf();
}
#if ARM
private const string RuntimeLibrary = "[MRT]";
[RuntimeImport(RuntimeLibrary, "RhpIDiv")]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Int32 RhpIDiv(Int32 i, Int32 j);
public static int IDiv(Int32 i, Int32 j)
{
if (j == 0)
return ThrowIntDivByZero();
else if (j == -1 && i == Int32.MinValue)
return ThrowIntArithExc();
else
return RhpIDiv(i, j);
}
[RuntimeImport(RuntimeLibrary, "RhpUDiv")]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern UInt32 RhpUDiv(UInt32 i, UInt32 j);
public static long UDiv(UInt32 i, UInt32 j)
{
if (j == 0)
return ThrowUIntDivByZero();
else
return RhpUDiv(i, j);
}
[RuntimeImport(RuntimeLibrary, "RhpULDiv")]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern UInt64 RhpULDiv(UInt64 i, UInt64 j);
public static ulong ULDiv(UInt64 i, UInt64 j)
{
if (j == 0)
return ThrowULngDivByZero();
else
return RhpULDiv(i, j);
}
[RuntimeImport(RuntimeLibrary, "RhpLDiv")]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Int64 RhpLDiv(Int64 i, Int64 j);
public static long LDiv(Int64 i, Int64 j)
{
if (j == 0)
return ThrowLngDivByZero();
else if (j == -1 && i == Int64.MinValue)
return ThrowLngArithExc();
else
return RhpLDiv(i, j);
}
[RuntimeImport(RuntimeLibrary, "RhpIMod")]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Int32 RhpIMod(Int32 i, Int32 j);
public static int IMod(Int32 i, Int32 j)
{
if (j == 0)
return ThrowIntDivByZero();
else
return RhpIMod(i, j);
}
[RuntimeImport(RuntimeLibrary, "RhpUMod")]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern UInt32 RhpUMod(UInt32 i, UInt32 j);
public static long UMod(UInt32 i, UInt32 j)
{
if (j == 0)
return ThrowUIntDivByZero();
else
return RhpUMod(i, j);
}
[RuntimeImport(RuntimeLibrary, "RhpULMod")]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern UInt64 RhpULMod(UInt64 i, UInt64 j);
public static ulong ULMod(UInt64 i, UInt64 j)
{
if (j == 0)
return ThrowULngDivByZero();
else
return RhpULMod(i, j);
}
[RuntimeImport(RuntimeLibrary, "RhpLMod")]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Int64 RhpLMod(Int64 i, Int64 j);
public static long LMod(Int64 i, Int64 j)
{
if (j == 0)
return ThrowLngDivByZero();
else
return RhpLMod(i, j);
}
#endif // ARM
//
// Matching return types of throw helpers enables tailcalling them. It improves performance
// of the hot path because of it does not need to raise full stackframe.
//
[MethodImpl(MethodImplOptions.NoInlining)]
private static int ThrowIntOvf()
{
throw new OverflowException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static uint ThrowUIntOvf()
{
throw new OverflowException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static long ThrowLngOvf()
{
throw new OverflowException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ulong ThrowULngOvf()
{
throw new OverflowException();
}
#if ARM
[MethodImpl(MethodImplOptions.NoInlining)]
private static int ThrowIntDivByZero()
{
throw new DivideByZeroException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static uint ThrowUIntDivByZero()
{
throw new DivideByZeroException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static long ThrowLngDivByZero()
{
throw new DivideByZeroException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ulong ThrowULngDivByZero()
{
throw new DivideByZeroException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static int ThrowIntArithExc()
{
throw new ArithmeticException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static long ThrowLngArithExc()
{
throw new ArithmeticException();
}
#endif // ARM
}
}
| |
using System;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Codecs.Lucene40
{
/*
* 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 IndexFileNames = Lucene.Net.Index.IndexFileNames;
using SegmentReadState = Lucene.Net.Index.SegmentReadState;
using SegmentWriteState = Lucene.Net.Index.SegmentWriteState;
/// <summary>
/// Lucene 4.0 DocValues format.
/// <para/>
/// Files:
/// <list type="bullet">
/// <item><description><c>.dv.cfs</c>: compound container (<see cref="Store.CompoundFileDirectory"/>)</description></item>
/// <item><description><c>.dv.cfe</c>: compound entries (<see cref="Store.CompoundFileDirectory"/>)</description></item>
/// </list>
/// Entries within the compound file:
/// <list type="bullet">
/// <item><description><c><segment>_<fieldNumber>.dat</c>: data values</description></item>
/// <item><description><c><segment>_<fieldNumber>.idx</c>: index into the .dat for DEREF types</description></item>
/// </list>
/// <para>
/// There are several many types of <see cref="Index.DocValues"/> with different encodings.
/// From the perspective of filenames, all types store their values in <c>.dat</c>
/// entries within the compound file. In the case of dereferenced/sorted types, the <c>.dat</c>
/// actually contains only the unique values, and an additional <c>.idx</c> file contains
/// pointers to these unique values.
/// </para>
/// Formats:
/// <list type="bullet">
/// <item><description><see cref="LegacyDocValuesType.VAR_INTS"/> .dat --> Header, PackedType, MinValue,
/// DefaultValue, PackedStream</description></item>
/// <item><description><see cref="LegacyDocValuesType.FIXED_INTS_8"/> .dat --> Header, ValueSize,
/// Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) <sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.FIXED_INTS_16"/> .dat --> Header, ValueSize,
/// Short (<see cref="Store.DataOutput.WriteInt16(short)"/>) <sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.FIXED_INTS_32"/> .dat --> Header, ValueSize,
/// Int32 (<see cref="Store.DataOutput.WriteInt32(int)"/>) <sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.FIXED_INTS_64"/> .dat --> Header, ValueSize,
/// Int64 (<see cref="Store.DataOutput.WriteInt64(long)"/>) <sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.FLOAT_32"/> .dat --> Header, ValueSize, Float32<sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.FLOAT_64"/> .dat --> Header, ValueSize, Float64<sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_FIXED_STRAIGHT"/> .dat --> Header, ValueSize,
/// (Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * ValueSize)<sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_STRAIGHT"/> .idx --> Header, TotalBytes, Addresses</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_STRAIGHT"/> .dat --> Header,
/// (Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * <i>variable ValueSize</i>)<sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_FIXED_DEREF"/> .idx --> Header, NumValues, Addresses</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_FIXED_DEREF"/> .dat --> Header, ValueSize,
/// (Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * ValueSize)<sup>NumValues</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_DEREF"/> .idx --> Header, TotalVarBytes, Addresses</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_DEREF"/> .dat --> Header,
/// (LengthPrefix + Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * <i>variable ValueSize</i>)<sup>NumValues</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_FIXED_SORTED"/> .idx --> Header, NumValues, Ordinals</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_FIXED_SORTED"/> .dat --> Header, ValueSize,
/// (Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * ValueSize)<sup>NumValues</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_SORTED"/> .idx --> Header, TotalVarBytes, Addresses, Ordinals</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_SORTED"/> .dat --> Header,
/// (Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * <i>variable ValueSize</i>)<sup>NumValues</sup></description></item>
/// </list>
/// Data Types:
/// <list type="bullet">
/// <item><description>Header --> CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) </description></item>
/// <item><description>PackedType --> Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>)</description></item>
/// <item><description>MaxAddress, MinValue, DefaultValue --> Int64 (<see cref="Store.DataOutput.WriteInt64(long)"/>) </description></item>
/// <item><description>PackedStream, Addresses, Ordinals --> <see cref="Util.Packed.PackedInt32s"/></description></item>
/// <item><description>ValueSize, NumValues --> Int32 (<see cref="Store.DataOutput.WriteInt32(int)"/>) </description></item>
/// <item><description>Float32 --> 32-bit float encoded with <see cref="J2N.BitConversion.SingleToRawInt32Bits(float)"/>
/// then written as Int32 (<see cref="Store.DataOutput.WriteInt32(int)"/>) </description></item>
/// <item><description>Float64 --> 64-bit float encoded with <see cref="J2N.BitConversion.DoubleToRawInt64Bits(double)"/>
/// then written as Int64 (<see cref="Store.DataOutput.WriteInt64(long)"/>) </description></item>
/// <item><description>TotalBytes --> VLong (<see cref="Store.DataOutput.WriteVInt64(long)"/>) </description></item>
/// <item><description>TotalVarBytes --> Int64 (<see cref="Store.DataOutput.WriteInt64(long)"/>) </description></item>
/// <item><description>LengthPrefix --> Length of the data value as VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) (maximum
/// of 2 bytes)</description></item>
/// </list>
/// Notes:
/// <list type="bullet">
/// <item><description>PackedType is a 0 when compressed, 1 when the stream is written as 64-bit integers.</description></item>
/// <item><description>Addresses stores pointers to the actual byte location (indexed by docid). In the VAR_STRAIGHT
/// case, each entry can have a different length, so to determine the length, docid+1 is
/// retrieved. A sentinel address is written at the end for the VAR_STRAIGHT case, so the Addresses
/// stream contains maxdoc+1 indices. For the deduplicated VAR_DEREF case, each length
/// is encoded as a prefix to the data itself as a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>)
/// (maximum of 2 bytes).</description></item>
/// <item><description>Ordinals stores the term ID in sorted order (indexed by docid). In the FIXED_SORTED case,
/// the address into the .dat can be computed from the ordinal as
/// <c>Header+ValueSize+(ordinal*ValueSize)</c> because the byte length is fixed.
/// In the VAR_SORTED case, there is double indirection (docid -> ordinal -> address), but
/// an additional sentinel ordinal+address is always written (so there are NumValues+1 ordinals). To
/// determine the length, ord+1's address is looked up as well.</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_STRAIGHT"/> in contrast to other straight
/// variants uses a <c>.idx</c> file to improve lookup perfromance. In contrast to
/// <see cref="LegacyDocValuesType.BYTES_VAR_DEREF"/> it doesn't apply deduplication of the document values.
/// </description></item>
/// </list>
/// <para/>
/// Limitations:
/// <list type="bullet">
/// <item><description> Binary doc values can be at most <see cref="MAX_BINARY_FIELD_LENGTH"/> in length.</description></item>
/// </list>
/// </summary>
[Obsolete("Only for reading old 4.0 and 4.1 segments")]
[DocValuesFormatName("Lucene40")] // LUCENENET specific - using DocValuesFormatName attribute to ensure the default name passed from subclasses is the same as this class name
public class Lucene40DocValuesFormat : DocValuesFormat
// NOTE: not registered in SPI, doesnt respect segment suffix, etc
// for back compat only!
{
/// <summary>
/// Maximum length for each binary doc values field. </summary>
public static readonly int MAX_BINARY_FIELD_LENGTH = (1 << 15) - 2;
/// <summary>
/// Sole constructor. </summary>
public Lucene40DocValuesFormat()
: base()
{
}
public override DocValuesConsumer FieldsConsumer(SegmentWriteState state)
{
throw UnsupportedOperationException.Create("this codec can only be used for reading");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override DocValuesProducer FieldsProducer(SegmentReadState state)
{
string filename = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, "dv", IndexFileNames.COMPOUND_FILE_EXTENSION);
return new Lucene40DocValuesReader(state, filename, Lucene40FieldInfosReader.LEGACY_DV_TYPE_KEY);
}
// constants for VAR_INTS
internal const string VAR_INTS_CODEC_NAME = "PackedInts";
internal const int VAR_INTS_VERSION_START = 0;
internal const int VAR_INTS_VERSION_CURRENT = VAR_INTS_VERSION_START;
internal const sbyte VAR_INTS_PACKED = 0x00;
internal const sbyte VAR_INTS_FIXED_64 = 0x01;
// constants for FIXED_INTS_8, FIXED_INTS_16, FIXED_INTS_32, FIXED_INTS_64
internal const string INTS_CODEC_NAME = "Ints";
internal const int INTS_VERSION_START = 0;
internal const int INTS_VERSION_CURRENT = INTS_VERSION_START;
// constants for FLOAT_32, FLOAT_64
internal const string FLOATS_CODEC_NAME = "Floats";
internal const int FLOATS_VERSION_START = 0;
internal const int FLOATS_VERSION_CURRENT = FLOATS_VERSION_START;
// constants for BYTES_FIXED_STRAIGHT
internal const string BYTES_FIXED_STRAIGHT_CODEC_NAME = "FixedStraightBytes";
internal const int BYTES_FIXED_STRAIGHT_VERSION_START = 0;
internal const int BYTES_FIXED_STRAIGHT_VERSION_CURRENT = BYTES_FIXED_STRAIGHT_VERSION_START;
// constants for BYTES_VAR_STRAIGHT
internal const string BYTES_VAR_STRAIGHT_CODEC_NAME_IDX = "VarStraightBytesIdx";
internal const string BYTES_VAR_STRAIGHT_CODEC_NAME_DAT = "VarStraightBytesDat";
internal const int BYTES_VAR_STRAIGHT_VERSION_START = 0;
internal const int BYTES_VAR_STRAIGHT_VERSION_CURRENT = BYTES_VAR_STRAIGHT_VERSION_START;
// constants for BYTES_FIXED_DEREF
internal const string BYTES_FIXED_DEREF_CODEC_NAME_IDX = "FixedDerefBytesIdx";
internal const string BYTES_FIXED_DEREF_CODEC_NAME_DAT = "FixedDerefBytesDat";
internal const int BYTES_FIXED_DEREF_VERSION_START = 0;
internal const int BYTES_FIXED_DEREF_VERSION_CURRENT = BYTES_FIXED_DEREF_VERSION_START;
// constants for BYTES_VAR_DEREF
internal const string BYTES_VAR_DEREF_CODEC_NAME_IDX = "VarDerefBytesIdx";
internal const string BYTES_VAR_DEREF_CODEC_NAME_DAT = "VarDerefBytesDat";
internal const int BYTES_VAR_DEREF_VERSION_START = 0;
internal const int BYTES_VAR_DEREF_VERSION_CURRENT = BYTES_VAR_DEREF_VERSION_START;
// constants for BYTES_FIXED_SORTED
internal const string BYTES_FIXED_SORTED_CODEC_NAME_IDX = "FixedSortedBytesIdx";
internal const string BYTES_FIXED_SORTED_CODEC_NAME_DAT = "FixedSortedBytesDat";
internal const int BYTES_FIXED_SORTED_VERSION_START = 0;
internal const int BYTES_FIXED_SORTED_VERSION_CURRENT = BYTES_FIXED_SORTED_VERSION_START;
// constants for BYTES_VAR_SORTED
// NOTE this IS NOT A BUG! 4.0 actually screwed this up (VAR_SORTED and VAR_DEREF have same codec header)
internal const string BYTES_VAR_SORTED_CODEC_NAME_IDX = "VarDerefBytesIdx";
internal const string BYTES_VAR_SORTED_CODEC_NAME_DAT = "VarDerefBytesDat";
internal const int BYTES_VAR_SORTED_VERSION_START = 0;
internal const int BYTES_VAR_SORTED_VERSION_CURRENT = BYTES_VAR_SORTED_VERSION_START;
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NodaTime.Text;
using NodaTime.Text.Patterns;
using NUnit.Framework;
namespace NodaTime.Test.Text
{
public partial class LocalTimePatternTest : PatternTestBase<LocalTime>
{
private static readonly DateTime SampleDateTime = new DateTime(2000, 1, 1, 21, 13, 34, 123, DateTimeKind.Unspecified).AddTicks(4567);
private static readonly LocalTime SampleLocalTime = LocalTime.FromHourMinuteSecondMillisecondTick(21, 13, 34, 123, 4567);
// Characters we expect to work the same in Noda Time as in the BCL.
private const string ExpectedCharacters = "hHms.:fFtT ";
private static readonly CultureInfo AmOnlyCulture = CreateCustomAmPmCulture("am", "");
private static readonly CultureInfo PmOnlyCulture = CreateCustomAmPmCulture("", "pm");
private static readonly CultureInfo NoAmOrPmCulture = CreateCustomAmPmCulture("", "");
internal static readonly Data[] InvalidPatternData = {
new Data { Pattern = "", Message = TextErrorMessages.FormatStringEmpty },
new Data { Pattern = "!", Message = TextErrorMessages.UnknownStandardFormat, Parameters = {'!', typeof(LocalTime).FullName! }},
new Data { Pattern = "%", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '%', typeof(LocalTime).FullName! } },
new Data { Pattern = "\\", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '\\', typeof(LocalTime).FullName! } },
new Data { Pattern = "%%", Message = TextErrorMessages.PercentDoubled },
new Data { Pattern = "%\\", Message = TextErrorMessages.EscapeAtEndOfString },
new Data { Pattern = "ffffffffff", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'f', 9 } },
new Data { Pattern = "FFFFFFFFFF", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'F', 9 } },
new Data { Pattern = "H%", Message = TextErrorMessages.PercentAtEndOfString },
new Data { Pattern = "HHH", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'H', 2 } },
new Data { Pattern = "mmm", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'm', 2 } },
new Data { Pattern = "mmmmmmmmmmmmmmmmmmm", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'm', 2 } },
new Data { Pattern = "'qwe", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
new Data { Pattern = "'qwe\\", Message = TextErrorMessages.EscapeAtEndOfString },
new Data { Pattern = "'qwe\\'", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
new Data { Pattern = "sss", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 's', 2 } },
// T isn't valid in a time pattern
new Data { Pattern = "1970-01-01THH:mm:ss", Message = TextErrorMessages.UnquotedLiteral, Parameters = { 'T' } }
};
internal static Data[] ParseFailureData = {
new Data { Text = "17 6", Pattern = "HH h", Message = TextErrorMessages.InconsistentValues2, Parameters = {'H', 'h', typeof(LocalTime).FullName! }},
new Data { Text = "17 AM", Pattern = "HH tt", Message = TextErrorMessages.InconsistentValues2, Parameters = {'H', 't', typeof(LocalTime).FullName! }},
new Data { Text = "5 foo", Pattern = "h t", Message = TextErrorMessages.MissingAmPmDesignator},
new Data { Text = "04.", Pattern = "ss.FF", Message = TextErrorMessages.MismatchedNumber, Parameters = { "FF" } },
new Data { Text = "04.", Pattern = "ss;FF", Message = TextErrorMessages.MismatchedNumber, Parameters = { "FF" } },
new Data { Text = "04.", Pattern = "ss.ff", Message = TextErrorMessages.MismatchedNumber, Parameters = { "ff" } },
new Data { Text = "04.", Pattern = "ss;ff", Message = TextErrorMessages.MismatchedNumber, Parameters = { "ff" } },
new Data { Text = "04.x", Pattern = "ss.FF", Message = TextErrorMessages.MismatchedNumber, Parameters = { "FF" } },
new Data { Text = "04.x", Pattern = "ss;FF", Message = TextErrorMessages.MismatchedNumber, Parameters = { "FF" } },
new Data { Text = "04.x", Pattern = "ss.ff", Message = TextErrorMessages.MismatchedNumber, Parameters = { "ff" } },
new Data { Text = "04.x", Pattern = "ss;ff", Message = TextErrorMessages.MismatchedNumber, Parameters = { "ff" } },
new Data { Text = "05 Foo", Pattern = "HH tt", Message = TextErrorMessages.MissingAmPmDesignator }
};
internal static Data[] ParseOnlyData = {
new Data(0, 0, 0, 400) { Text = "4", Pattern = "%f", },
new Data(0, 0, 0, 400) { Text = "4", Pattern = "%F", },
new Data(0, 0, 0, 400) { Text = "4", Pattern = "FF", },
new Data(0, 0, 0, 400) { Text = "40", Pattern = "FF", },
new Data(0, 0, 0, 400) { Text = "4", Pattern = "FFF", },
new Data(0, 0, 0, 400) { Text = "40", Pattern = "FFF" },
new Data(0, 0, 0, 400) { Text = "400", Pattern = "FFF" },
new Data(0, 0, 0, 400) { Text = "40", Pattern = "ff", },
new Data(0, 0, 0, 400) { Text = "400", Pattern = "fff", },
new Data(0, 0, 0, 400) { Text = "4000", Pattern = "ffff", },
new Data(0, 0, 0, 400) { Text = "40000", Pattern = "fffff", },
new Data(0, 0, 0, 400) { Text = "400000", Pattern = "ffffff", },
new Data(0, 0, 0, 400) { Text = "4000000", Pattern = "fffffff", },
new Data(0, 0, 0, 450) { Text = "45", Pattern = "ff" },
new Data(0, 0, 0, 450) { Text = "45", Pattern = "FF" },
new Data(0, 0, 0, 450) { Text = "45", Pattern = "FFF" },
new Data(0, 0, 0, 450) { Text = "450", Pattern = "fff" },
new Data(0, 0, 0, 456) { Text = "456", Pattern = "fff" },
new Data(0, 0, 0, 456) { Text = "456", Pattern = "FFF" },
new Data(0, 0, 0, 0) { Text = "0", Pattern = "%f" },
new Data(0, 0, 0, 0) { Text = "00", Pattern = "ff" },
new Data(0, 0, 0, 8) { Text = "008", Pattern = "fff" },
new Data(0, 0, 0, 8) { Text = "008", Pattern = "FFF" },
new Data(5, 0, 0, 0) { Text = "05", Pattern = "HH" },
new Data(0, 6, 0, 0) { Text = "06", Pattern = "mm" },
new Data(0, 0, 7, 0) { Text = "07", Pattern = "ss" },
new Data(5, 0, 0, 0) { Text = "5", Pattern = "%H" },
new Data(0, 6, 0, 0) { Text = "6", Pattern = "%m" },
new Data(0, 0, 7, 0) { Text = "7", Pattern = "%s" },
// AM/PM designator is case-insensitive for both short and long forms
new Data(17, 0, 0, 0) { Text = "5 p", Pattern = "h t" },
new Data(17, 0, 0, 0) { Text = "5 pm", Pattern = "h tt" },
// Parsing using the semi-colon "comma dot" specifier
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;fff", Text = "16:05:20,352" },
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;FFF", Text = "16:05:20,352" },
// Empty fractional section
new Data(0,0,4,0) { Text = "04", Pattern = "ssFF" },
new Data(0,0,4,0) { Text = "040", Pattern = "ssFF" },
new Data(0,0,4,0) { Text = "040", Pattern = "ssFFF" },
new Data(0,0,4,0) { Text = "04", Pattern = "ss.FF"},
};
internal static Data[] FormatOnlyData = {
new Data(5, 6, 7, 8) { Text = "", Pattern = "%F" },
new Data(5, 6, 7, 8) { Text = "", Pattern = "FF" },
new Data(1, 1, 1, 400) { Text = "4", Pattern = "%f" },
new Data(1, 1, 1, 400) { Text = "4", Pattern = "%F" },
new Data(1, 1, 1, 400) { Text = "4", Pattern = "FF" },
new Data(1, 1, 1, 400) { Text = "4", Pattern = "FFF" },
new Data(1, 1, 1, 400) { Text = "40", Pattern = "ff" },
new Data(1, 1, 1, 400) { Text = "400", Pattern = "fff" },
new Data(1, 1, 1, 400) { Text = "4000", Pattern = "ffff" },
new Data(1, 1, 1, 400) { Text = "40000", Pattern = "fffff" },
new Data(1, 1, 1, 400) { Text = "400000", Pattern = "ffffff" },
new Data(1, 1, 1, 400) { Text = "4000000", Pattern = "fffffff" },
new Data(1, 1, 1, 450) { Text = "4", Pattern = "%f" },
new Data(1, 1, 1, 450) { Text = "4", Pattern = "%F" },
new Data(1, 1, 1, 450) { Text = "45", Pattern = "ff" },
new Data(1, 1, 1, 450) { Text = "45", Pattern = "FF" },
new Data(1, 1, 1, 450) { Text = "45", Pattern = "FFF" },
new Data(1, 1, 1, 450) { Text = "450", Pattern = "fff" },
new Data(1, 1, 1, 456) { Text = "4", Pattern = "%f" },
new Data(1, 1, 1, 456) { Text = "4", Pattern = "%F" },
new Data(1, 1, 1, 456) { Text = "45", Pattern = "ff" },
new Data(1, 1, 1, 456) { Text = "45", Pattern = "FF" },
new Data(1, 1, 1, 456) { Text = "456", Pattern = "fff" },
new Data(1, 1, 1, 456) { Text = "456", Pattern = "FFF" },
new Data(0,0,0,0) {Text = "", Pattern = "FF" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "0", Pattern = "%f" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "00", Pattern = "ff" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "008", Pattern = "fff" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "008", Pattern = "FFF" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "05", Pattern = "HH" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "06", Pattern = "mm" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "07", Pattern = "ss" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "5", Pattern = "%H" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "6", Pattern = "%m" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "7", Pattern = "%s" },
// The subminute values are truncated for the short pattern
new Data(14, 15, 16) { Culture = Cultures.DotTimeSeparator, Text = "14.15", Pattern = "t" },
new Data(14, 15, 16) { Culture = Cultures.Invariant, Text = "14:15", Pattern = "t" },
};
internal static Data[] DefaultPatternData = {
// Invariant culture uses HH:mm:ss for the "long" pattern
new Data(5, 0, 0, 0) { Text = "05:00:00" },
new Data(5, 12, 0, 0) { Text = "05:12:00" },
new Data(5, 12, 34, 0) { Text = "05:12:34" },
// US uses hh:mm:ss tt for the "long" pattern
new Data(17, 0, 0, 0) { Culture = Cultures.EnUs, Text = "5:00:00 PM" },
new Data(5, 0, 0, 0) { Culture = Cultures.EnUs, Text = "5:00:00 AM" },
new Data(5, 12, 0, 0) { Culture = Cultures.EnUs, Text = "5:12:00 AM" },
new Data(5, 12, 34, 0) { Culture = Cultures.EnUs, Text = "5:12:34 AM" },
};
internal static readonly Data[] TemplateValueData = {
// Pattern specifies nothing - template value is passed through
new Data(LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5)) { Culture = Cultures.EnUs, Text = "X", Pattern = "'X'", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) },
// Tests for each individual field being propagated
new Data(LocalTime.FromHourMinuteSecondMillisecondTick(1, 6, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "mm:ss.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) },
new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 2, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:ss.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) },
new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 7, 3, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:mm.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) },
new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 7, 8, 4, 5)) { Culture = Cultures.EnUs, Text = "06:07:08", Pattern = "HH:mm:ss", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) },
// Hours are tricky because of the ways they can be specified
new Data(new LocalTime(6, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(1, 2, 3) },
new Data(new LocalTime(18, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(2, 2, 3) },
new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(2, 2, 3) },
new Data(new LocalTime(17, 2, 3)) { Culture = Cultures.EnUs, Text = "5 PM", Pattern = "h tt", Template = new LocalTime(1, 2, 3) },
};
/// <summary>
/// Common test data for both formatting and parsing. A test should be placed here unless is truly
/// cannot be run both ways. This ensures that as many round-trip type tests are performed as possible.
/// </summary>
internal static readonly Data[] FormatAndParseData = {
new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = ".", Pattern = "%." },
new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = ":", Pattern = "%:" },
new Data(LocalTime.Midnight) { Culture = Cultures.DotTimeSeparator, Text = ".", Pattern = "%." },
new Data(LocalTime.Midnight) { Culture = Cultures.DotTimeSeparator, Text = ".", Pattern = "%:" },
new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = "H", Pattern = "\\H" },
new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = "HHss", Pattern = "'HHss'" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "%f" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "%F" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "FF" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "FFF" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "100000000", Pattern = "fffffffff" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "FFFFFFFFF" },
new Data(0, 0, 0, 120) { Culture = Cultures.EnUs, Text = "12", Pattern = "ff" },
new Data(0, 0, 0, 120) { Culture = Cultures.EnUs, Text = "12", Pattern = "FF" },
new Data(0, 0, 0, 120) { Culture = Cultures.EnUs, Text = "12", Pattern = "FFF" },
new Data(0, 0, 0, 123) { Culture = Cultures.EnUs, Text = "123", Pattern = "fff" },
new Data(0, 0, 0, 123) { Culture = Cultures.EnUs, Text = "123", Pattern = "FFF" },
new Data(0, 0, 0, 123, 4000) { Culture = Cultures.EnUs, Text = "1234", Pattern = "ffff" },
new Data(0, 0, 0, 123, 4000) { Culture = Cultures.EnUs, Text = "1234", Pattern = "FFFF" },
new Data(0, 0, 0, 123, 4500) { Culture = Cultures.EnUs, Text = "12345", Pattern = "fffff" },
new Data(0, 0, 0, 123, 4500) { Culture = Cultures.EnUs, Text = "12345", Pattern = "FFFFF" },
new Data(0, 0, 0, 123, 4560) { Culture = Cultures.EnUs, Text = "123456", Pattern = "ffffff" },
new Data(0, 0, 0, 123, 4560) { Culture = Cultures.EnUs, Text = "123456", Pattern = "FFFFFF" },
new Data(0, 0, 0, 123, 4567) { Culture = Cultures.EnUs, Text = "1234567", Pattern = "fffffff" },
new Data(0, 0, 0, 123, 4567) { Culture = Cultures.EnUs, Text = "1234567", Pattern = "FFFFFFF" },
new Data(0, 0, 0, 123456780L) { Culture = Cultures.EnUs, Text = "12345678", Pattern = "ffffffff" },
new Data(0, 0, 0, 123456780L) { Culture = Cultures.EnUs, Text = "12345678", Pattern = "FFFFFFFF" },
new Data(0, 0, 0, 123456789L) { Culture = Cultures.EnUs, Text = "123456789", Pattern = "fffffffff" },
new Data(0, 0, 0, 123456789L) { Culture = Cultures.EnUs, Text = "123456789", Pattern = "FFFFFFFFF" },
new Data(0, 0, 0, 600) { Culture = Cultures.EnUs, Text = ".6", Pattern = ".f" },
new Data(0, 0, 0, 600) { Culture = Cultures.EnUs, Text = ".6", Pattern = ".F" },
new Data(0, 0, 0, 600) { Culture = Cultures.EnUs, Text = ".6", Pattern = ".FFF" }, // Elided fraction
new Data(0, 0, 0, 678) { Culture = Cultures.EnUs, Text = ".678", Pattern = ".fff" },
new Data(0, 0, 0, 678) { Culture = Cultures.EnUs, Text = ".678", Pattern = ".FFF" },
new Data(0, 0, 12, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%s" },
new Data(0, 0, 12, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "ss" },
new Data(0, 0, 2, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%s" },
new Data(0, 12, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%m" },
new Data(0, 12, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "mm" },
new Data(0, 2, 0, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%m" },
new Data(1, 0, 0, 0) { Culture = Cultures.EnUs, Text = "1", Pattern = "H.FFF" }, // Missing fraction
new Data(12, 0, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%H" },
new Data(12, 0, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "HH" },
new Data(2, 0, 0, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%H" },
new Data(0, 0, 12, 340) { Culture = Cultures.EnUs, Text = "12.34", Pattern = "ss.FFF" },
// Standard patterns
new Data(14, 15, 16) { Culture = Cultures.EnUs, Text = "14:15:16", Pattern = "r" },
new Data(14, 15, 16, 700) { Culture = Cultures.EnUs, Text = "14:15:16.7", Pattern = "r" },
new Data(14, 15, 16, 780) { Culture = Cultures.EnUs, Text = "14:15:16.78", Pattern = "r" },
new Data(14, 15, 16, 789) { Culture = Cultures.EnUs, Text = "14:15:16.789", Pattern = "r" },
new Data(14, 15, 16, 789, 1000) { Culture = Cultures.EnUs, Text = "14:15:16.7891", Pattern = "r" },
new Data(14, 15, 16, 789, 1200) { Culture = Cultures.EnUs, Text = "14:15:16.78912", Pattern = "r" },
new Data(14, 15, 16, 789, 1230) { Culture = Cultures.EnUs, Text = "14:15:16.789123", Pattern = "r" },
new Data(14, 15, 16, 789, 1234) { Culture = Cultures.EnUs, Text = "14:15:16.7891234", Pattern = "r" },
new Data(14, 15, 16, 700) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.7", Pattern = "r" },
new Data(14, 15, 16, 780) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.78", Pattern = "r" },
new Data(14, 15, 16, 789) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.789", Pattern = "r" },
new Data(14, 15, 16, 789, 1000) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.7891", Pattern = "r" },
new Data(14, 15, 16, 789, 1200) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.78912", Pattern = "r" },
new Data(14, 15, 16, 789, 1230) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.789123", Pattern = "r" },
new Data(14, 15, 16, 789, 1234) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.7891234", Pattern = "r" },
new Data(14, 15, 16, 789123456L) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.789123456", Pattern = "r" },
new Data(14, 15, 0) { Culture = Cultures.DotTimeSeparator, Text = "14.15", Pattern = "t" },
new Data(14, 15, 0) { Culture = Cultures.Invariant, Text = "14:15", Pattern = "t" },
new Data(14, 15, 16) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16", Pattern = "T" },
new Data(14, 15, 16) { Culture = Cultures.Invariant, Text = "14:15:16", Pattern = "T" },
new Data(14, 15, 16, 789) { StandardPattern = LocalTimePattern.ExtendedIso, Culture = Cultures.DotTimeSeparator, Text = "14:15:16.789", Pattern = "o" },
new Data(14, 15, 16, 789) { StandardPattern = LocalTimePattern.ExtendedIso, Culture = Cultures.EnUs, Text = "14:15:16.789", Pattern = "o" },
new Data(14, 15, 16) { StandardPattern = LocalTimePattern.ExtendedIso, Culture = Cultures.Invariant, Text = "14:15:16", Pattern = "o" },
new Data(14, 15, 16, 789) { StandardPattern = LocalTimePattern.LongExtendedIso, Culture = Cultures.DotTimeSeparator, Text = "14:15:16.789000000", Pattern = "O" },
new Data(14, 15, 16, 789) { StandardPattern = LocalTimePattern.LongExtendedIso, Culture = Cultures.EnUs, Text = "14:15:16.789000000", Pattern = "O" },
new Data(14, 15, 16) { StandardPattern = LocalTimePattern.LongExtendedIso, Culture = Cultures.Invariant, Text = "14:15:16.000000000", Pattern = "O" },
new Data(14, 15, 16) { StandardPattern = LocalTimePattern.GeneralIso, Culture = Cultures.Invariant, Text = "14:15:16", Pattern = "HH:mm:ss" },
// ------------ Template value tests ----------
// Mixtures of 12 and 24 hour times
new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "18 6 PM", Pattern = "HH h tt" },
new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "18 6", Pattern = "HH h" },
new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "18 PM", Pattern = "HH tt" },
new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "6 PM", Pattern = "h tt" },
new Data(6, 0, 0) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h" },
new Data(0, 0, 0) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt" },
new Data(12, 0, 0) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt" },
new Data(0, 0, 0) { Culture = Cultures.EnUs, Text = "A", Pattern = "%t" },
new Data(12, 0, 0) { Culture = Cultures.EnUs, Text = "P", Pattern = "%t" },
// Pattern specifies nothing - template value is passed through
new Data(LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5)) { Culture = Cultures.EnUs, Text = "*", Pattern = "%*", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) },
// Tests for each individual field being propagated
new Data(LocalTime.FromHourMinuteSecondMillisecondTick(1, 6, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "mm:ss.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) },
new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 2, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:ss.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) },
new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 7, 3, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:mm.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) },
new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 7, 8, 4, 5)) { Culture = Cultures.EnUs, Text = "06:07:08", Pattern = "HH:mm:ss", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) },
// Hours are tricky because of the ways they can be specified
new Data(new LocalTime(6, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(1, 2, 3) },
new Data(new LocalTime(18, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(2, 2, 3) },
new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(2, 2, 3) },
new Data(new LocalTime(17, 2, 3)) { Culture = Cultures.EnUs, Text = "5 PM", Pattern = "h tt", Template = new LocalTime(1, 2, 3) },
// --------------- end of template value tests ----------------------
// Only one of the AM/PM designator is present. We should still be able to work out what is meant, by the presence
// or absence of the non-empty one.
new Data(5, 0, 0) { Culture = AmOnlyCulture, Text = "5 am", Pattern = "h tt" },
new Data(15, 0, 0) { Culture = AmOnlyCulture, Text = "3 ", Pattern = "h tt", Description = "Implicit PM" },
new Data(5, 0, 0) { Culture = AmOnlyCulture, Text = "5 a", Pattern = "h t" },
new Data(15, 0, 0) { Culture = AmOnlyCulture, Text = "3 ", Pattern = "h t", Description = "Implicit PM"},
new Data(5, 0, 0) { Culture = PmOnlyCulture, Text = "5 ", Pattern = "h tt" },
new Data(15, 0, 0) { Culture = PmOnlyCulture, Text = "3 pm", Pattern = "h tt" },
new Data(5, 0, 0) { Culture = PmOnlyCulture, Text = "5 ", Pattern = "h t" },
new Data(15, 0, 0) { Culture = PmOnlyCulture, Text = "3 p", Pattern = "h t" },
// AM / PM designators are both empty strings. The parsing side relies on the AM/PM value being correct on the
// template value. (The template value is for the wrong actual hour, but in the right side of noon.)
new Data(5, 0, 0) { Culture = NoAmOrPmCulture, Text = "5 ", Pattern = "h tt", Template = new LocalTime(2, 0, 0) },
new Data(15, 0, 0) { Culture = NoAmOrPmCulture, Text = "3 ", Pattern = "h tt", Template = new LocalTime(14, 0, 0) },
new Data(5, 0, 0) { Culture = NoAmOrPmCulture, Text = "5 ", Pattern = "h t", Template = new LocalTime(2, 0, 0) },
new Data(15, 0, 0) { Culture = NoAmOrPmCulture, Text = "3 ", Pattern = "h t", Template = new LocalTime(14, 0, 0) },
// Use of the semi-colon "comma dot" specifier
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;fff", Text = "16:05:20.352" },
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;FFF", Text = "16:05:20.352" },
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;FFF 'end'", Text = "16:05:20.352 end" },
new Data(16, 05, 20) { Pattern = "HH:mm:ss;FFF 'end'", Text = "16:05:20 end" },
// Check handling of F after non-period.
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss'x'FFF", Text = "16:05:20x352" },
};
internal static IEnumerable<Data> ParseData = ParseOnlyData.Concat(FormatAndParseData);
internal static IEnumerable<Data> FormatData = FormatOnlyData.Concat(FormatAndParseData);
private static CultureInfo CreateCustomAmPmCulture(string amDesignator, string pmDesignator)
{
CultureInfo clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.DateTimeFormat.AMDesignator = amDesignator;
clone.DateTimeFormat.PMDesignator = pmDesignator;
return CultureInfo.ReadOnly(clone);
}
[Test]
public void ParseNull() => AssertParseNull(LocalTimePattern.ExtendedIso);
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclLongTimePatternIsValidNodaPattern(CultureInfo culture)
{
if (culture is null)
{
return;
}
AssertValidNodaPattern(culture, culture.DateTimeFormat.LongTimePattern);
}
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclShortTimePatternIsValidNodaPattern(CultureInfo culture)
{
AssertValidNodaPattern(culture, culture.DateTimeFormat.ShortTimePattern);
}
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclLongTimePatternGivesSameResultsInNoda(CultureInfo culture)
{
AssertBclNodaEquality(culture, culture.DateTimeFormat.LongTimePattern);
}
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclShortTimePatternGivesSameResultsInNoda(CultureInfo culture)
{
AssertBclNodaEquality(culture, culture.DateTimeFormat.ShortTimePattern);
}
[Test]
public void CreateWithInvariantCulture_NullPatternText()
{
Assert.Throws<ArgumentNullException>(() => LocalTimePattern.CreateWithInvariantCulture(null!));
}
[Test]
public void Create_NullFormatInfo()
{
Assert.Throws<ArgumentNullException>(() => LocalTimePattern.Create("HH", null!));
}
[Test]
public void TemplateValue_DefaultsToMidnight()
{
var pattern = LocalTimePattern.CreateWithInvariantCulture("HH");
Assert.AreEqual(LocalTime.Midnight, pattern.TemplateValue);
}
[Test]
public void CreateWithCurrentCulture()
{
using (CultureSaver.SetCultures(Cultures.DotTimeSeparator))
{
var pattern = LocalTimePattern.CreateWithCurrentCulture("HH:mm");
var text = pattern.Format(new LocalTime(13, 45));
Assert.AreEqual("13.45", text);
}
}
[Test]
public void WithTemplateValue_PropertyFetch()
{
LocalTime newValue = new LocalTime(1, 23, 45);
var pattern = LocalTimePattern.CreateWithInvariantCulture("HH").WithTemplateValue(newValue);
Assert.AreEqual(newValue, pattern.TemplateValue);
}
private void AssertBclNodaEquality(CultureInfo culture, string patternText)
{
// On Mono, some general patterns include an offset at the end.
// https://github.com/nodatime/nodatime/issues/98
// For the moment, ignore them.
// TODO(V1.2): Work out what to do in such cases...
if (patternText.EndsWith("z"))
{
return;
}
var pattern = LocalTimePattern.Create(patternText, culture);
Assert.AreEqual(SampleDateTime.ToString(patternText, culture), pattern.Format(SampleLocalTime));
}
private static void AssertValidNodaPattern(CultureInfo culture, string pattern)
{
PatternCursor cursor = new PatternCursor(pattern);
while (cursor.MoveNext())
{
if (cursor.Current == '\'')
{
cursor.GetQuotedString('\'');
}
else
{
// We'll never do anything "special" with non-ascii characters anyway,
// so we don't mind if they're not quoted.
if (cursor.Current < '\u0080')
{
Assert.IsTrue(ExpectedCharacters.Contains(cursor.Current),
$"Pattern '{pattern}' contains unquoted, unexpected characters");
}
}
}
// Check that the pattern parses
LocalTimePattern.Create(pattern, culture);
}
/// <summary>
/// A container for test data for formatting and parsing <see cref="LocalTime" /> objects.
/// </summary>
public sealed class Data : PatternTestData<LocalTime>
{
// Default to midnight
protected override LocalTime DefaultTemplate => LocalTime.Midnight;
protected override string? ValuePatternText => "HH:mm:ss.FFFFFFFFF";
public Data(LocalTime value) : base(value)
{
}
public Data(int hours, int minutes, int seconds)
: this(new LocalTime(hours, minutes, seconds))
{
}
public Data(int hours, int minutes, int seconds, int milliseconds)
: this(new LocalTime(hours, minutes, seconds, milliseconds))
{
}
public Data(int hours, int minutes, int seconds, int milliseconds, int ticksWithinMillisecond)
: this(LocalTime.FromHourMinuteSecondMillisecondTick(hours, minutes, seconds, milliseconds, ticksWithinMillisecond))
{
}
public Data(int hours, int minutes, int seconds, long nanoOfSecond)
: this(new LocalTime(hours, minutes, seconds).PlusNanoseconds(nanoOfSecond))
{
}
public Data() : this(LocalTime.Midnight)
{
}
internal override IPattern<LocalTime> CreatePattern() =>
LocalTimePattern.CreateWithInvariantCulture(Pattern!)
.WithTemplateValue(Template)
.WithCulture(Culture);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using NUnit.Framework.Constraints;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Execution;
namespace NUnit.Framework
{
/// <summary>
/// Provide the context information of the current test.
/// This is an adapter for the internal ExecutionContext
/// class, hiding the internals from the user test.
/// </summary>
public class TestContext
{
private readonly TestExecutionContext _testExecutionContext;
private TestAdapter _test;
private ResultAdapter _result;
#region Constructor
/// <summary>
/// Construct a TestContext for an ExecutionContext
/// </summary>
/// <param name="testExecutionContext">The ExecutionContext to adapt</param>
public TestContext(TestExecutionContext testExecutionContext)
{
_testExecutionContext = testExecutionContext;
}
#endregion
#region Properties
/// <summary>
/// Get the current test context. This is created
/// as needed. The user may save the context for
/// use within a test, but it should not be used
/// outside the test for which it is created.
/// </summary>
public static TestContext CurrentContext
{
get { return new TestContext(TestExecutionContext.CurrentContext); }
}
/// <summary>
/// Gets a TextWriter that will send output to the current test result.
/// </summary>
public static TextWriter Out
{
get { return TestExecutionContext.CurrentContext.OutWriter; }
}
/// <summary>
/// Gets a TextWriter that will send output directly to Console.Error
/// </summary>
public static TextWriter Error = new EventListenerTextWriter("Error", Console.Error);
/// <summary>
/// Gets a TextWriter for use in displaying immediate progress messages
/// </summary>
public static readonly TextWriter Progress = new EventListenerTextWriter("Progress", Console.Error);
/// <summary>
/// TestParameters object holds parameters for the test run, if any are specified
/// </summary>
public static readonly TestParameters Parameters = new TestParameters();
/// <summary>
/// Static DefaultWorkDirectory is now used as the source
/// of the public instance property WorkDirectory. This is
/// a bit odd but necessary to avoid breaking user tests.
/// </summary>
internal static string DefaultWorkDirectory;
/// <summary>
/// Get a representation of the current test.
/// </summary>
public TestAdapter Test
{
get { return _test ?? (_test = new TestAdapter(_testExecutionContext.CurrentTest)); }
}
/// <summary>
/// Gets a Representation of the TestResult for the current test.
/// </summary>
public ResultAdapter Result
{
get { return _result ?? (_result = new ResultAdapter(_testExecutionContext.CurrentResult)); }
}
#if PARALLEL
/// <summary>
/// Gets the unique name of the Worker that is executing this test.
/// </summary>
public string WorkerId
{
get { return _testExecutionContext.TestWorker.Name; }
}
#endif
/// <summary>
/// Gets the directory containing the current test assembly.
/// </summary>
public string TestDirectory
{
get
{
Assembly assembly = _testExecutionContext?.CurrentTest?.TypeInfo?.Assembly;
if (assembly != null)
return AssemblyHelper.GetDirectoryName(assembly);
#if NETSTANDARD1_4
// Test is null, we may be loading tests rather than executing.
// Assume that the NUnit framework is in the same directory as the tests
return AssemblyHelper.GetDirectoryName(typeof(TestContext).GetTypeInfo().Assembly);
#else
// Test is null, we may be loading tests rather than executing.
// Assume that calling assembly is the test assembly.
return AssemblyHelper.GetDirectoryName(Assembly.GetCallingAssembly());
#endif
}
}
/// <summary>
/// Gets the directory to be used for outputting files created
/// by this test run.
/// </summary>
public string WorkDirectory
{
get
{
return DefaultWorkDirectory;
}
}
/// <summary>
/// Gets the random generator.
/// </summary>
/// <value>
/// The random generator.
/// </value>
public Randomizer Random
{
get { return _testExecutionContext.RandomGenerator; }
}
/// <summary>
/// Gets the number of assertions executed
/// up to this point in the test.
/// </summary>
public int AssertCount
{
get { return _testExecutionContext.AssertCount; }
}
/// <summary>
/// Get the number of times the current Test has been repeated. This is currently only
/// set when using the <see cref="RetryAttribute"/>.
/// TODO: add this to the RepeatAttribute as well
/// </summary>
public int CurrentRepeatCount
{
get { return _testExecutionContext.CurrentRepeatCount; }
}
#endregion
#region Static Methods
/// <summary>Write the string representation of a boolean value to the current result</summary>
public static void Write(bool value) { Out.Write(value); }
/// <summary>Write a char to the current result</summary>
public static void Write(char value) { Out.Write(value); }
/// <summary>Write a char array to the current result</summary>
public static void Write(char[] value) { Out.Write(value); }
/// <summary>Write the string representation of a double to the current result</summary>
public static void Write(double value) { Out.Write(value); }
/// <summary>Write the string representation of an Int32 value to the current result</summary>
public static void Write(Int32 value) { Out.Write(value); }
/// <summary>Write the string representation of an Int64 value to the current result</summary>
public static void Write(Int64 value) { Out.Write(value); }
/// <summary>Write the string representation of a decimal value to the current result</summary>
public static void Write(decimal value) { Out.Write(value); }
/// <summary>Write the string representation of an object to the current result</summary>
public static void Write(object value) { Out.Write(value); }
/// <summary>Write the string representation of a Single value to the current result</summary>
public static void Write(Single value) { Out.Write(value); }
/// <summary>Write a string to the current result</summary>
public static void Write(string value) { Out.Write(value); }
/// <summary>Write the string representation of a UInt32 value to the current result</summary>
[CLSCompliant(false)]
public static void Write(UInt32 value) { Out.Write(value); }
/// <summary>Write the string representation of a UInt64 value to the current result</summary>
[CLSCompliant(false)]
public static void Write(UInt64 value) { Out.Write(value); }
/// <summary>Write a formatted string to the current result</summary>
public static void Write(string format, object arg1) { Out.Write(format, arg1); }
/// <summary>Write a formatted string to the current result</summary>
public static void Write(string format, object arg1, object arg2) { Out.Write(format, arg1, arg2); }
/// <summary>Write a formatted string to the current result</summary>
public static void Write(string format, object arg1, object arg2, object arg3) { Out.Write(format, arg1, arg2, arg3); }
/// <summary>Write a formatted string to the current result</summary>
public static void Write(string format, params object[] args) { Out.Write(format, args); }
/// <summary>Write a line terminator to the current result</summary>
public static void WriteLine() { Out.WriteLine(); }
/// <summary>Write the string representation of a boolean value to the current result followed by a line terminator</summary>
public static void WriteLine(bool value) { Out.WriteLine(value); }
/// <summary>Write a char to the current result followed by a line terminator</summary>
public static void WriteLine(char value) { Out.WriteLine(value); }
/// <summary>Write a char array to the current result followed by a line terminator</summary>
public static void WriteLine(char[] value) { Out.WriteLine(value); }
/// <summary>Write the string representation of a double to the current result followed by a line terminator</summary>
public static void WriteLine(double value) { Out.WriteLine(value); }
/// <summary>Write the string representation of an Int32 value to the current result followed by a line terminator</summary>
public static void WriteLine(Int32 value) { Out.WriteLine(value); }
/// <summary>Write the string representation of an Int64 value to the current result followed by a line terminator</summary>
public static void WriteLine(Int64 value) { Out.WriteLine(value); }
/// <summary>Write the string representation of a decimal value to the current result followed by a line terminator</summary>
public static void WriteLine(decimal value) { Out.WriteLine(value); }
/// <summary>Write the string representation of an object to the current result followed by a line terminator</summary>
public static void WriteLine(object value) { Out.WriteLine(value); }
/// <summary>Write the string representation of a Single value to the current result followed by a line terminator</summary>
public static void WriteLine(Single value) { Out.WriteLine(value); }
/// <summary>Write a string to the current result followed by a line terminator</summary>
public static void WriteLine(string value) { Out.WriteLine(value); }
/// <summary>Write the string representation of a UInt32 value to the current result followed by a line terminator</summary>
[CLSCompliant(false)]
public static void WriteLine(UInt32 value) { Out.WriteLine(value); }
/// <summary>Write the string representation of a UInt64 value to the current result followed by a line terminator</summary>
[CLSCompliant(false)]
public static void WriteLine(UInt64 value) { Out.WriteLine(value); }
/// <summary>Write a formatted string to the current result followed by a line terminator</summary>
public static void WriteLine(string format, object arg1) { Out.WriteLine(format, arg1); }
/// <summary>Write a formatted string to the current result followed by a line terminator</summary>
public static void WriteLine(string format, object arg1, object arg2) { Out.WriteLine(format, arg1, arg2); }
/// <summary>Write a formatted string to the current result followed by a line terminator</summary>
public static void WriteLine(string format, object arg1, object arg2, object arg3) { Out.WriteLine(format, arg1, arg2, arg3); }
/// <summary>Write a formatted string to the current result followed by a line terminator</summary>
public static void WriteLine(string format, params object[] args) { Out.WriteLine(format, args); }
/// <summary>
/// This method adds the a new ValueFormatterFactory to the
/// chain of responsibility used for formatting values in messages.
/// The scope of the change is the current TestContext.
/// </summary>
/// <param name="formatterFactory">The factory delegate</param>
public static void AddFormatter(ValueFormatterFactory formatterFactory)
{
TestExecutionContext.CurrentContext.AddFormatter(formatterFactory);
}
/// <summary>
/// Attach a file to the current test result
/// </summary>
/// <param name="filePath">Relative or absolute file path to attachment</param>
/// <param name="description">Optional description of attachment</param>
public static void AddTestAttachment(string filePath, string description = null)
{
Guard.ArgumentNotNull(filePath, nameof(filePath));
Guard.ArgumentValid(filePath.IndexOfAny(Path.GetInvalidPathChars()) == -1,
$"Test attachment file path contains invalid path characters. {filePath}", nameof(filePath));
if (!Path.IsPathRooted(filePath))
filePath = Path.Combine(TestContext.CurrentContext.WorkDirectory, filePath);
if (!File.Exists(filePath))
throw new FileNotFoundException("Test attachment file path could not be found.", filePath);
var result = TestExecutionContext.CurrentContext.CurrentResult;
result.AddTestAttachment(new TestAttachment(filePath, description));
}
/// <summary>
/// This method provides a simplified way to add a ValueFormatter
/// delegate to the chain of responsibility, creating the factory
/// delegate internally. It is useful when the Type of the object
/// is the only criterion for selection of the formatter, since
/// it can be used without getting involved with a compound function.
/// </summary>
/// <typeparam name="TSUPPORTED">The type supported by this formatter</typeparam>
/// <param name="formatter">The ValueFormatter delegate</param>
public static void AddFormatter<TSUPPORTED>(ValueFormatter formatter)
{
AddFormatter(next => val => (val is TSUPPORTED) ? formatter(val) : next(val));
}
#endregion
#region Nested TestAdapter Class
/// <summary>
/// TestAdapter adapts a Test for consumption by
/// the user test code.
/// </summary>
public class TestAdapter
{
private readonly Test _test;
#region Constructor
/// <summary>
/// Construct a TestAdapter for a Test
/// </summary>
/// <param name="test">The Test to be adapted</param>
public TestAdapter(Test test)
{
_test = test;
}
#endregion
#region Properties
/// <summary>
/// Gets the unique Id of a test
/// </summary>
public String ID
{
get { return _test.Id; }
}
/// <summary>
/// The name of the test, which may or may not be
/// the same as the method name.
/// </summary>
public string Name
{
get { return _test.Name; }
}
/// <summary>
/// The name of the method representing the test.
/// </summary>
public string MethodName
{
get
{
return _test is TestMethod
? _test.Method.Name
: null;
}
}
/// <summary>
/// The FullName of the test
/// </summary>
public string FullName
{
get { return _test.FullName; }
}
/// <summary>
/// The ClassName of the test
/// </summary>
public string ClassName
{
get { return _test.ClassName; }
}
/// <summary>
/// A shallow copy of the properties of the test.
/// </summary>
public PropertyBagAdapter Properties
{
get { return new PropertyBagAdapter(_test.Properties); }
}
/// <summary>
/// The arguments to use in creating the test or empty array if none are required.
/// </summary>
public object[] Arguments
{
get { return _test.Arguments; }
}
#endregion
}
#endregion
#region Nested ResultAdapter Class
/// <summary>
/// ResultAdapter adapts a TestResult for consumption by
/// the user test code.
/// </summary>
public class ResultAdapter
{
private readonly TestResult _result;
#region Constructor
/// <summary>
/// Construct a ResultAdapter for a TestResult
/// </summary>
/// <param name="result">The TestResult to be adapted</param>
public ResultAdapter(TestResult result)
{
_result = result;
}
#endregion
#region Properties
/// <summary>
/// Gets a ResultState representing the outcome of the test
/// up to this point in its execution.
/// </summary>
public ResultState Outcome
{
get { return _result.ResultState; }
}
/// <summary>
/// Gets a list of the assertion results generated
/// up to this point in the test.
/// </summary>
public IEnumerable<AssertionResult> Assertions
{
get { return _result.AssertionResults; }
}
/// <summary>
/// Gets the message associated with a test
/// failure or with not running the test
/// </summary>
public string Message
{
get { return _result.Message; }
}
/// <summary>
/// Gets any stack trace associated with an
/// error or failure.
/// </summary>
public virtual string StackTrace
{
get { return _result.StackTrace; }
}
/// <summary>
/// Gets the number of test cases that failed
/// when running the test and all its children.
/// </summary>
public int FailCount
{
get { return _result.FailCount; }
}
/// <summary>
/// Gets the number of test cases that had warnings
/// when running the test and all its children.
/// </summary>
public int WarningCount
{
get { return _result.WarningCount; }
}
/// <summary>
/// Gets the number of test cases that passed
/// when running the test and all its children.
/// </summary>
public int PassCount
{
get { return _result.PassCount; }
}
/// <summary>
/// Gets the number of test cases that were skipped
/// when running the test and all its children.
/// </summary>
public int SkipCount
{
get { return _result.SkipCount; }
}
/// <summary>
/// Gets the number of test cases that were inconclusive
/// when running the test and all its children.
/// </summary>
public int InconclusiveCount
{
get { return _result.InconclusiveCount; }
}
#endregion
}
#endregion
#region Nested PropertyBagAdapter Class
/// <summary>
/// <see cref="PropertyBagAdapter"/> adapts an <see cref="IPropertyBag"/>
/// for consumption by the user.
/// </summary>
public class PropertyBagAdapter
{
private readonly IPropertyBag _source;
/// <summary>
/// Construct a <see cref="PropertyBagAdapter"/> from a source
/// <see cref="IPropertyBag"/>.
/// </summary>
public PropertyBagAdapter(IPropertyBag source)
{
_source = source;
}
/// <summary>
/// Get the first property with the given <paramref name="key"/>, if it can be found, otherwise
/// returns null.
/// </summary>
public object Get(string key)
{
return _source.Get(key);
}
/// <summary>
/// Indicates whether <paramref name="key"/> is found in this
/// <see cref="PropertyBagAdapter"/>.
/// </summary>
public bool ContainsKey(string key)
{
return _source.ContainsKey(key);
}
/// <summary>
/// Returns a collection of properties
/// with the given <paramref name="key"/>.
/// </summary>
public IEnumerable<object> this[string key]
{
get
{
var list = new List<object>();
foreach(var item in _source[key])
{
list.Add(item);
}
return list;
}
}
/// <summary>
/// Returns the count of elements with the given <paramref name="key"/>.
/// </summary>
public int Count(string key)
{
return _source[key].Count;
}
/// <summary>
/// Returns a collection of the property keys.
/// </summary>
public ICollection<string> Keys
{
get
{
return _source.Keys;
}
}
}
#endregion
}
}
| |
// This is an open source non-commercial project. Dear PVS-Studio, please check it. PVS-Studio Static
// Code Analyzer for C, C++ and C#: http://www.viva64.com
namespace EOpt.Math.Optimization.OOOpt
{
using System;
using System.Collections.Generic;
using System.Threading;
using EOpt.Math.Optimization;
using Exceptions;
using Help;
using Math;
using Math.Random;
/// <summary>
/// Optimization method BBBC.
/// </summary>
public class BBBCOptimizer : IBaseOptimizer<BBBCParams, IOOOptProblem>, IOOOptimizer<BBBCParams>
{
private List<Agent> _agents;
private INormalGen _normalRand;
private BBBCParams _parameters;
private IContUniformGen _uniformRand;
private KahanSum _denumKahanSum;
/// <summary>
/// Parameters for method.
/// </summary>
public BBBCParams Parameters => _parameters;
private void Clear()
{
_agents.Clear();
}
/// <summary>
/// Create the object which uses default implementation for random generators.
/// </summary>
public BBBCOptimizer() : this(new ContUniformDist(), new NormalDist())
{
}
/// <summary>
/// Create the object which uses custom implementation for random generators.
/// </summary>
/// <param name="UniformGen"> Object, which implements <see cref="IContUniformGen"/> interface. </param>
/// <param name="NormalGen"> Object, which implements <see cref="INormalGen"/> interface. </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="NormalGen"/> or <paramref name="UniformGen"/> is null.
/// </exception>
public BBBCOptimizer(IContUniformGen UniformGen, INormalGen NormalGen)
{
if (NormalGen == null)
{
throw new ArgumentNullException(nameof(NormalGen));
}
_uniformRand = UniformGen ?? throw new ArgumentNullException(nameof(UniformGen));
_normalRand = NormalGen;
_denumKahanSum = new KahanSum();
}
private PointND _centerOfMass;
private int _indexBestSol;
private Agent _solution;
private void EvalFunction(Func<IReadOnlyList<double>, double> Func)
{
for (int i = 0; i < _agents.Count; i++)
{
_agents[i].Eval(Func);
}
}
/// <summary>
/// </summary>
/// <param name="DimObjs"> </param>
private void InitAgents(IOOOptProblem Problem, int DimObjs)
{
int dimension = Problem.LowerBounds.Count;
for (int i = 0; i < _parameters.NP; i++)
{
PointND point = new PointND(0.0, dimension);
for (int j = 0; j < dimension; j++)
{
point[j] = _uniformRand.URandVal(Problem.LowerBounds[j], Problem.UpperBounds[j]);
}
_agents.Add(new Agent(point, new PointND(0.0, DimObjs)));
}
}
private void FindBestSolution()
{
_indexBestSol = 0;
_solution = _agents[0];
for (int i = 1; i < _agents.Count; i++)
{
if (_agents[i].Objs[0] < _solution.Objs[0])
{
_solution = _agents[i];
_indexBestSol = i;
}
}
}
private void FindCenterOfMass()
{
double mass = 0.0;
_centerOfMass.MultiplyByInplace(0);
_denumKahanSum.SumResest();
for (int i = 0; i < _parameters.NP; i++)
{
mass = _agents[i].Objs[0] - _solution.Objs[0];
if (mass < Constants.VALUE_AVOID_DIV_BY_ZERO)
{
mass += Constants.VALUE_AVOID_DIV_BY_ZERO;
}
mass = 1 / mass;
_denumKahanSum.Add(mass);
for (int coordNum = 0; coordNum < _centerOfMass.Count; coordNum++)
{
_centerOfMass[coordNum] += mass * _agents[i].Point[coordNum];
}
}
_centerOfMass.MultiplyByInplace(1 / _denumKahanSum.Sum);
}
private void GenNextAgents(IReadOnlyList<double> LowerBounds, IReadOnlyList<double> UpperBounds, int IterNum)
{
for (int i = 0; i < _parameters.NP; i++)
{
if (i != _indexBestSol)
{
for (int j = 0; j < _agents[i].Point.Count; j++)
{
_agents[i].Point[j] = _parameters.Beta * _centerOfMass[j] + (1 - _parameters.Beta) * Solution.Point[j] + _normalRand.NRandVal(0, 1)
* _parameters.Alpha * (UpperBounds[j] - LowerBounds[j]) / IterNum;
_agents[i].Point[j] = ClampDouble.Clamp(_agents[i].Point[j], LowerBounds[j], UpperBounds[j]);
}
}
}
}
private void FirstStep(IOOOptProblem Problem)
{
if (Problem == null)
{
throw new ArgumentNullException(nameof(Problem));
}
InitAgents(Problem, 1);
EvalFunction(Problem.TargetFunction);
FindBestSolution();
}
private void Init(BBBCParams Parameters, IOOOptProblem Problem, int DimObjs)
{
if (Problem == null)
{
throw new ArgumentNullException(nameof(Problem));
}
if (!Parameters.IsParamsInit)
{
throw new ArgumentException("The parameters were created by the default constructor and have invalid value\nYou need to create parameters with a custom constructor.", nameof(Parameters));
}
_parameters = Parameters;
if (_agents == null)
{
_agents = new List<Agent>(_parameters.NP);
}
else
{
_agents.Capacity = _parameters.NP;
}
int dim = Problem.LowerBounds.Count;
if (_centerOfMass == null)
{
_centerOfMass = new PointND(0.0, dim);
}
else if (_centerOfMass.Count != dim)
{
_centerOfMass = new PointND(0.0, dim);
}
}
private void NextStep(IOOOptProblem Problem, int Iter)
{
FindCenterOfMass();
GenNextAgents(Problem.LowerBounds, Problem.UpperBounds, Iter);
EvalFunction(Problem.TargetFunction);
FindBestSolution();
}
/// <summary>
/// The solution of the constrained optimization problem.
/// </summary>
public Agent Solution => _solution;
/// <summary>
/// <see cref="IBaseOptimizer{TParams, TProblem}.Minimize(TParams, TProblem)"/>
/// </summary>
/// <param name="Parameters"> Parameters for method. </param>
/// <param name="Problem"> An optimization problem. </param>
/// <exception cref="ArgumentException"> If parameters do not set. </exception>
/// <exception cref="ArgumentNullException"> If <paramref name="Problem"/> is null. </exception>
/// <exception cref="InvalidValueFunctionException">
/// If the function has value is NaN, PositiveInfinity or NegativeInfinity.
/// </exception>
public void Minimize(BBBCParams Parameters, IOOOptProblem Problem)
{
Init(Parameters, Problem, 1);
FirstStep(Problem);
for (int i = 2; i <= _parameters.Imax; i++)
{
NextStep(Problem, i);
}
Clear();
}
/// <summary>
/// <see cref="IBaseOptimizer{TParams, TProblem}.Minimize(TParams, TProblem, CancellationToken)"/>
/// </summary>
/// <param name="Parameters"> Parameters for method. </param>
/// <param name="Problem"> An optimization problem. </param>
/// <param name="CancelToken"> <see cref="CancellationToken"/> </param>
/// <exception cref="ArgumentException"> If parameters do not set. </exception>
/// <exception cref="ArgumentNullException"> If <paramref name="Problem"/> is null. </exception>
/// <exception cref="InvalidValueFunctionException">
/// If the function has value is NaN, PositiveInfinity or NegativeInfinity.
/// </exception>
/// <exception cref="OperationCanceledException"></exception>
public void Minimize(BBBCParams Parameters, IOOOptProblem Problem, CancellationToken CancelToken)
{
Init(Parameters, Problem, 1);
FirstStep(Problem);
for (int i = 2; i <= _parameters.Imax; i++)
{
CancelToken.ThrowIfCancellationRequested();
NextStep(Problem, i);
}
Clear();
}
/// <summary>
/// <see cref="IBaseOptimizer{TParams, TProblem}.Minimize(TParams, TProblem, IProgress{Progress})"/>
/// </summary>
/// <param name="Parameters"> Parameters for method. </param>
/// <param name="Problem"> An optimization problem. </param>
/// <param name="Reporter">
/// Object which implement interface <see cref="IProgress{T}"/>, where T is <see cref="Progress"/>.
/// </param>
/// <exception cref="ArgumentException"> If parameters do not set. </exception>
/// <exception cref="ArgumentNullException">
/// If <paramref name="Problem"/> or <paramref name="Reporter"/> is null.
/// </exception>
/// <exception cref="InvalidValueFunctionException">
/// If the function has value is NaN, PositiveInfinity or NegativeInfinity.
/// </exception>
public void Minimize(BBBCParams Parameters, IOOOptProblem Problem, IProgress<Progress> Reporter)
{
if (Reporter == null)
{
throw new ArgumentNullException(nameof(Reporter));
}
Init(Parameters, Problem, 1);
FirstStep(Problem);
Progress progress = new Progress(this, 1, _parameters.Imax, 1);
Reporter.Report(progress);
for (int i = 2; i <= _parameters.Imax; i++)
{
NextStep(Problem, i);
progress.Current = i;
Reporter.Report(progress);
}
Clear();
}
/// <summary>
/// <see cref="IBaseOptimizer{TParams, TProblem}.Minimize(TParams, TProblem, CancellationToken)"/>
/// </summary>
/// <param name="Parameters"> Parameters for method. </param>
/// <param name="Problem"> An optimization problem. </param>
/// <param name="Reporter">
/// Object which implement interface <see cref="IProgress{T}"/>, where T is <see cref="Progress"/>.
/// </param>
/// <param name="CancelToken"> <see cref="CancellationToken"/> </param>
/// <exception cref="ArgumentException"> If parameters do not set. </exception>
/// <exception cref="ArgumentNullException">
/// If <paramref name="Problem"/> or <paramref name="Reporter"/> is null.
/// </exception>
/// <exception cref="InvalidValueFunctionException">
/// If the function has value is NaN, PositiveInfinity or NegativeInfinity.
/// </exception>
/// <exception cref="OperationCanceledException"></exception>
public void Minimize(BBBCParams Parameters, IOOOptProblem Problem, IProgress<Progress> Reporter, CancellationToken CancelToken)
{
if (Reporter == null)
{
throw new ArgumentNullException(nameof(Reporter));
}
Init(Parameters, Problem, 1);
FirstStep(Problem);
Progress progress = new Progress(this, 1, _parameters.Imax, 1);
Reporter.Report(progress);
for (int i = 2; i <= _parameters.Imax; i++)
{
CancelToken.ThrowIfCancellationRequested();
NextStep(Problem, i);
progress.Current = i;
Reporter.Report(progress);
}
Clear();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace UnityTest
{
[Serializable]
public partial class UnitTestView : EditorWindow
{
private static UnitTestView s_Instance;
private static readonly IUnitTestEngine k_TestEngine = new NUnitTestEngine();
[SerializeField] private List<UnitTestResult> m_ResultList = new List<UnitTestResult>();
[SerializeField] private string[] m_AvailableCategories;
[SerializeField] private List<string> m_FoldMarkers = new List<string>();
[SerializeField] private List<UnitTestRendererLine> m_SelectedLines = new List<UnitTestRendererLine>();
UnitTestRendererLine m_TestLines;
#region runner steering vars
private Vector2 m_TestListScroll, m_TestInfoScroll;
private float m_HorizontalSplitBarPosition = 200;
private float m_VerticalSplitBarPosition = 300;
#endregion
private UnitTestsRunnerSettings m_Settings;
#region GUI Contents
private readonly GUIContent m_GUIRunSelectedTestsIcon = new GUIContent(Icons.RunImg, "Run selected tests");
private readonly GUIContent m_GUIRunAllTestsIcon = new GUIContent(Icons.RunAllImg, "Run all tests");
private readonly GUIContent m_GUIRerunFailedTestsIcon = new GUIContent(Icons.RunFailedImg, "Rerun failed tests");
private readonly GUIContent m_GUIOptionButton = new GUIContent("Options", Icons.GearImg);
private readonly GUIContent m_GUIHideButton = new GUIContent("Hide", Icons.GearImg);
private readonly GUIContent m_GUIRunOnRecompile = new GUIContent("Run on recompile", "Run all tests after recompilation");
private readonly GUIContent m_GUIShowDetailsBelowTests = new GUIContent("Show details below tests", "Show run details below test list");
private readonly GUIContent m_GUIRunTestsOnNewScene = new GUIContent("Run tests on a new scene", "Run tests on a new scene");
private readonly GUIContent m_GUIAutoSaveSceneBeforeRun = new GUIContent("Autosave scene", "The runner will automatically save the current scene changes before it starts");
private readonly GUIContent m_GUIShowSucceededTests = new GUIContent("Succeeded", Icons.SuccessImg, "Show tests that succeeded");
private readonly GUIContent m_GUIShowFailedTests = new GUIContent("Failed", Icons.FailImg, "Show tests that failed");
private readonly GUIContent m_GUIShowIgnoredTests = new GUIContent("Ignored", Icons.IgnoreImg, "Show tests that are ignored");
private readonly GUIContent m_GUIShowNotRunTests = new GUIContent("Not Run", Icons.UnknownImg, "Show tests that didn't run");
#endregion
public UnitTestView()
{
title = "Unit Tests Runner";
m_ResultList.Clear();
}
public void OnEnable()
{
s_Instance = this;
m_Settings = ProjectSettingsBase.Load<UnitTestsRunnerSettings>();
RefreshTests();
EnableBackgroundRunner(m_Settings.runOnRecompilation);
}
public void OnDestroy()
{
s_Instance = null;
EnableBackgroundRunner(false);
}
public void Awake()
{
RefreshTests();
}
public void OnGUI()
{
GUILayout.Space(10);
EditorGUILayout.BeginVertical();
EditorGUILayout.BeginHorizontal();
var layoutOptions = new[] { GUILayout.Width(32), GUILayout.Height(24) };
if (GUILayout.Button(m_GUIRunAllTestsIcon, Styles.buttonLeft, layoutOptions))
{
RunTests();
GUIUtility.ExitGUI();
}
if (GUILayout.Button(m_GUIRunSelectedTestsIcon, Styles.buttonMid, layoutOptions))
{
m_TestLines.RunSelectedTests();
}
if (GUILayout.Button(m_GUIRerunFailedTestsIcon, Styles.buttonRight, layoutOptions))
{
m_TestLines.RunTests(m_ResultList.Where(result => result.IsFailure || result.IsError).Select(l => l.FullName).ToArray());
}
GUILayout.FlexibleSpace();
if (GUILayout.Button(m_Settings.optionsFoldout ? m_GUIHideButton : m_GUIOptionButton, GUILayout.Height(24), GUILayout.Width(80)))
{
m_Settings.optionsFoldout = !m_Settings.optionsFoldout;
}
EditorGUILayout.EndHorizontal();
if (m_Settings.optionsFoldout) DrawOptions();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Filter:", GUILayout.Width(35));
m_Settings.testFilter = EditorGUILayout.TextField(m_Settings.testFilter, EditorStyles.textField);
if (m_AvailableCategories != null && m_AvailableCategories.Length > 0)
m_Settings.categoriesMask = EditorGUILayout.MaskField(m_Settings.categoriesMask, m_AvailableCategories, GUILayout.MaxWidth(90));
if (GUILayout.Button(m_Settings.filtersFoldout ? "Hide" : "Advanced", GUILayout.Width(80), GUILayout.Height(15)))
m_Settings.filtersFoldout = !m_Settings.filtersFoldout;
EditorGUILayout.EndHorizontal();
if (m_Settings.filtersFoldout)
DrawFilters();
if (m_Settings.horizontalSplit)
EditorGUILayout.BeginVertical();
else
EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
RenderTestList();
RenderTestInfo();
if (m_Settings.horizontalSplit)
EditorGUILayout.EndVertical();
else
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
private string[] GetSelectedCategories()
{
var selectedCategories = new List<string>();
foreach (var availableCategory in m_AvailableCategories)
{
var idx = Array.FindIndex(m_AvailableCategories, a => a == availableCategory);
var mask = 1 << idx;
if ((m_Settings.categoriesMask & mask) != 0) selectedCategories.Add(availableCategory);
}
return selectedCategories.ToArray();
}
private void RenderTestList()
{
EditorGUILayout.BeginVertical(Styles.testList);
m_TestListScroll = EditorGUILayout.BeginScrollView(m_TestListScroll,
GUILayout.ExpandWidth(true),
GUILayout.MaxWidth(2000));
if (m_TestLines != null)
{
var options = new RenderingOptions();
options.showSucceeded = m_Settings.showSucceeded;
options.showFailed = m_Settings.showFailed;
options.showIgnored = m_Settings.showIgnored;
options.showNotRunned = m_Settings.showNotRun;
options.nameFilter = m_Settings.testFilter;
options.categories = GetSelectedCategories();
if (m_TestLines.Render(options)) Repaint();
}
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
}
private void RenderTestInfo()
{
var ctrlId = GUIUtility.GetControlID(FocusType.Passive);
var rect = GUILayoutUtility.GetLastRect();
if (m_Settings.horizontalSplit)
{
rect.y = rect.height + rect.y - 1;
rect.height = 3;
}
else
{
rect.x = rect.width + rect.x - 1;
rect.width = 3;
}
EditorGUIUtility.AddCursorRect(rect, m_Settings.horizontalSplit ? MouseCursor.ResizeVertical : MouseCursor.ResizeHorizontal);
var e = Event.current;
switch (e.type)
{
case EventType.MouseDown:
if (GUIUtility.hotControl == 0 && rect.Contains(e.mousePosition))
GUIUtility.hotControl = ctrlId;
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == ctrlId)
{
m_HorizontalSplitBarPosition -= e.delta.y;
if (m_HorizontalSplitBarPosition < 20) m_HorizontalSplitBarPosition = 20;
m_VerticalSplitBarPosition -= e.delta.x;
if (m_VerticalSplitBarPosition < 20) m_VerticalSplitBarPosition = 20;
Repaint();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == ctrlId)
GUIUtility.hotControl = 0;
break;
}
m_TestInfoScroll = EditorGUILayout.BeginScrollView(m_TestInfoScroll, m_Settings.horizontalSplit
? GUILayout.MinHeight(m_HorizontalSplitBarPosition)
: GUILayout.Width(m_VerticalSplitBarPosition));
var text = "";
if (m_SelectedLines.Any())
{
text = m_SelectedLines.First().GetResultText();
}
EditorGUILayout.TextArea(text, Styles.info);
EditorGUILayout.EndScrollView();
}
private void DrawFilters()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
m_Settings.showSucceeded = GUILayout.Toggle(m_Settings.showSucceeded, m_GUIShowSucceededTests, GUI.skin.FindStyle(GUI.skin.button.name + "left"), GUILayout.ExpandWidth(true));
m_Settings.showFailed = GUILayout.Toggle(m_Settings.showFailed, m_GUIShowFailedTests, GUI.skin.FindStyle(GUI.skin.button.name + "mid"));
m_Settings.showIgnored = GUILayout.Toggle(m_Settings.showIgnored, m_GUIShowIgnoredTests, GUI.skin.FindStyle(GUI.skin.button.name + "mid"));
m_Settings.showNotRun = GUILayout.Toggle(m_Settings.showNotRun, m_GUIShowNotRunTests, GUI.skin.FindStyle(GUI.skin.button.name + "right"), GUILayout.ExpandWidth(true));
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck()) m_Settings.Save();
}
private void DrawOptions()
{
EditorGUI.BeginChangeCheck();
EditorGUI.BeginChangeCheck();
m_Settings.runOnRecompilation = EditorGUILayout.Toggle(m_GUIRunOnRecompile, m_Settings.runOnRecompilation);
if (EditorGUI.EndChangeCheck()) EnableBackgroundRunner(m_Settings.runOnRecompilation);
m_Settings.runTestOnANewScene = EditorGUILayout.Toggle(m_GUIRunTestsOnNewScene, m_Settings.runTestOnANewScene);
EditorGUI.BeginDisabledGroup(!m_Settings.runTestOnANewScene);
m_Settings.autoSaveSceneBeforeRun = EditorGUILayout.Toggle(m_GUIAutoSaveSceneBeforeRun, m_Settings.autoSaveSceneBeforeRun);
EditorGUI.EndDisabledGroup();
m_Settings.horizontalSplit = EditorGUILayout.Toggle(m_GUIShowDetailsBelowTests, m_Settings.horizontalSplit);
if (EditorGUI.EndChangeCheck())
{
m_Settings.Save();
}
EditorGUILayout.Space();
}
private void RefreshTests()
{
UnitTestResult[] newResults;
m_TestLines = k_TestEngine.GetTests(out newResults, out m_AvailableCategories);
foreach (var newResult in newResults)
{
var result = m_ResultList.Where(t => t.Test == newResult.Test && t.FullName == newResult.FullName).ToArray();
if (result.Count() != 1) continue;
newResult.Update(result.Single(), true);
}
UnitTestRendererLine.SelectedLines = m_SelectedLines;
UnitTestRendererLine.RunTest = RunTests;
GroupLine.FoldMarkers = m_FoldMarkers;
TestLine.GetUnitTestResult = FindTestResult;
m_ResultList = new List<UnitTestResult>(newResults);
Repaint();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace GreyhoundRacing.WebAPI.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Linq;
using System.Diagnostics;
class SignAnalysis
{
static int GetRandomValue() { return (new System.Random()).Next(0, 1000) - 500; }
int RandomValue { get => GetRandomValue(); }
int random = GetRandomValue();
int SsaSources(int p, int[] values)
{
var v = GetRandomValue();
if (v < 0)
{
return v;
}
v = RandomValue;
if (v < 0)
{
return v;
}
v = p;
if (v < 0)
{
return v;
}
v = random;
if (v < 0)
{
return v;
}
v = values[0];
if (v < 0)
{
return v;
}
int x = values[1];
v = x;
if (v < 0)
{
return v;
}
return 0;
}
void Operations(int i, int j, bool b)
{
if (i < 0 && j < 0)
{
var x = i + j;
System.Console.WriteLine(x); // strictly neg
x = i * j;
System.Console.WriteLine(x); // strictly pos
x = i / j;
System.Console.WriteLine(x); // pos
x = i - j;
System.Console.WriteLine(x); // no clue
x = i % j;
System.Console.WriteLine(x); // neg
x = i++;
System.Console.WriteLine(x); // strictly neg
x = i--;
System.Console.WriteLine(x); // neg
x = -i;
System.Console.WriteLine(x); // strictly pos
x = +i;
System.Console.WriteLine(x); // strictly neg
var l = (long)i;
System.Console.WriteLine(l); // strictly neg
x = i;
x += i;
System.Console.WriteLine(x); // strictly neg
}
if (i < 0 && j > 0)
{
var x = i + j;
System.Console.WriteLine(x);
x = i * j;
System.Console.WriteLine(x); // strictly neg
x = i / j;
System.Console.WriteLine(x); // neg
x = i - j;
System.Console.WriteLine(x); // strictly neg
x = i % j;
System.Console.WriteLine(x); // neg
x = b ? i : j;
System.Console.WriteLine(x); // any (except 0)
}
}
void NumericalTypes()
{
var f = 4.2f;
System.Console.WriteLine(f);
var d = 4.2;
System.Console.WriteLine(d);
var de = 4.2m;
System.Console.WriteLine(de);
var c = 'a';
System.Console.WriteLine(c);
}
int f0;
int f1;
void Field0()
{
f0++;
System.Console.WriteLine(f0); // strictly positive
f0 = 0;
}
void Field1()
{
f1++;
System.Console.WriteLine(f1); // no clue
f1 = -10;
}
void Field2()
{
System.Console.WriteLine(f1); // no clue
}
void Ctor()
{
var i = new Int32(); // const 0 value
i++;
System.Console.WriteLine(i); // strictly pos
}
int Guards(int x, int y)
{
if (x < 0)
{
return x; // strictly negative
}
if (y == 1)
{
return y; // strictly positive
}
if (y is -1)
{
return y; // strictly negative
}
if (x < y)
{
return y; // strictly positive
}
var b = y == 1;
if (b)
{
return y; // strictly positive
}
return 0;
}
void Inconsistent()
{
var i = 1;
if (i < 0)
{
System.Console.WriteLine(i); // reported as strictly pos, although unreachable
}
}
void SpecialValues(int[] ints)
{
System.Console.WriteLine(ints.Length); // positive
ints = new int[] { 1, 2, 3 };
System.Console.WriteLine(ints.Length); // 3, so strictly positive
System.Console.WriteLine(ints.Count()); // positive
System.Console.WriteLine(ints.Count(i => i > 1)); // positive
var s = "abc";
System.Console.WriteLine(s.Length); // positive, could be strictly positive
var enumerable = Enumerable.Empty<int>();
System.Console.WriteLine(enumerable.Count()); // positive
var i = new int[,] { { 1, 1 }, { 1, 2 }, { 1, 3 } };
System.Console.WriteLine(i.Length); // 6, so strictly positive
}
void Phi1(int i)
{
if (i > 0)
{
System.Console.WriteLine(i); // strictly positive
}
else
{
System.Console.WriteLine(i); // negative
}
System.Console.WriteLine(i); // any
}
void Phi2(int i)
{
if (i > 0)
{
System.Console.WriteLine(i); // strictly positive
}
else
{
if (i < 0) // negative
{
System.Console.WriteLine(i); // strictly negative
return;
}
}
System.Console.WriteLine(i); // positive, not found
}
void Phi3(int i)
{
if (i > 0)
{
System.Console.WriteLine(i); // strictly positive
}
else
{
if (i < 0) // negative
{
System.Console.WriteLine(i); // strictly negative
}
else
{
System.Console.WriteLine(i); // zero, nothing is reported
}
}
}
void Loop(int i, int j, int k)
{
if (i > 0)
{
while (i >= 0) // any
{
i--; // positive
System.Console.WriteLine(i); // any
}
System.Console.WriteLine(i); // strictly neg
}
if (j > 0)
{
while (j > 0)
{
j--; // strictly pos
System.Console.WriteLine(j); // positive
}
System.Console.WriteLine(j); // reported negative, can only be 0
}
if (k > 0)
{
while (k > 0)
{
k--; // strictly pos
System.Console.WriteLine(k); // positive
if (k == 5) // positive
{
break;
}
}
System.Console.WriteLine(k); // any
}
}
void Assert(int i, bool b)
{
Debug.Assert(i > 0);
System.Console.WriteLine(i); // strictly positive
if (b)
System.Console.WriteLine(i); // strictly positive
}
void CheckedUnchecked(int i)
{
var x = unchecked(-1 * i * i);
if (x < 0)
{
System.Console.WriteLine(x); // strictly negative
}
x = checked(-1 * i * i);
if (x < 0)
{
System.Console.WriteLine(x); // strictly negative
}
}
void CharMinMax()
{
var min = char.MinValue;
var max = char.MaxValue;
var c = min + 1;
System.Console.WriteLine(c); // strictly positive
c = min - 1;
System.Console.WriteLine(c); // strictly negative
c = max + 1;
System.Console.WriteLine(c); // strictly positive
}
void NullCoalesce(int? v)
{
if (v > 0)
{
var x = v ?? 1;
System.Console.WriteLine(x); // strictly positive
}
if (v == null)
{
var x = v ?? 1;
System.Console.WriteLine(x); // strictly positive
}
if (v < 0)
{
var x = v ?? 0;
System.Console.WriteLine(x); // negative
}
}
async System.Threading.Tasks.Task Await()
{
var i = await System.Threading.Tasks.Task.FromResult(5);
if (i < 0)
{
System.Console.WriteLine(i); // strictly negative
}
}
void Unsigned(uint i)
{
if (i != 0) // positive
{
System.Console.WriteLine(i); // strictly positive
}
}
public int MyField = 0;
void FieldAccess()
{
var x = new SignAnalysis();
var y = x.MyField;
if (y < 0)
{
System.Console.WriteLine(y); // strictly negative
}
}
private static unsafe void Pointer(float d)
{
float* dp = &d;
var x = *dp;
if (x < 0)
{
System.Console.WriteLine(x); // strictly negative
}
}
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit, Size = 15)]
struct MyStruct { }
unsafe void Sizeof()
{
var x = sizeof(MyStruct);
System.Console.WriteLine(x); // strictly positive
}
void SwitchCase(string s)
{
var x = s switch
{
"x" => 0,
_ => 2
};
System.Console.WriteLine(x); // positive
}
void Capture()
{
var i = 1;
void Capture()
{
if (i > 0)
Console.WriteLine(i); // strictly positive
}
Capture();
if (i > 0)
Console.WriteLine(i); // strictly positive
}
public struct MyStruct2 { public int F; }
void RefExpression(MyStruct2 s)
{
ref var x = ref s.F;
if (x < 0)
{
Console.WriteLine(x); // strictly negative
}
}
enum MyEnum { A = 12, B, C }
void EnumOp(MyEnum x, MyEnum y)
{
var i = x - y;
if (i < 0)
{
System.Console.WriteLine(i); // strictly negative
}
}
unsafe void PointerCast(byte* src, byte* dst)
{
var x = (int)(src - dst);
if (x < 0)
{
System.Console.WriteLine(x); // strictly negative
}
byte[] buf = new byte[10];
fixed (byte* to = buf)
{
System.Console.WriteLine((int)to);
}
}
uint Unsigned() { return 1; }
void UnsignedCheck(int i)
{
long l = Unsigned();
if (l != 0)
{
System.Console.WriteLine(l); // strictly positive
}
uint x = (uint)i;
x++;
System.Console.WriteLine(x); // strictly positive
}
void Splitting1(bool b)
{
var x = b ? 1 : -1;
if (b)
System.Console.WriteLine(x); // strictly positive [MISSING]
else
System.Console.WriteLine(x); // strictly negative [MISSING]
}
void Splitting2(bool b)
{
int x;
if (b) x = 1; else x = -1;
System.Console.WriteLine(x); // strictly positive (b = true) or strictly negative (b = false)
if (b)
System.Console.WriteLine(x); // strictly positive
else
System.Console.WriteLine(x); // strictly negative
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace PWLib.Platform.Windows
{
/// <summary>
/// Provides static methods to read system icons for both folders and files.
/// </summary>
/// <example>
/// <code>IconReader.GetFileIcon("c:\\general.xls");</code>
/// </example>
public static class IconHelper
{
#region Shell32 / interop stuff
/// <summary>
/// Wraps necessary Shell32.dll structures and functions required to retrieve Icon Handles using SHGetFileInfo. Code
/// courtesy of MSDN Cold Rooster Consulting case study.
/// </summary>
///
// This code has been left largely untouched from that in the CRC example. The main changes have been moving
// the icon reading code over to the IconReader type.
public class Shell32
{
public const int MAX_PATH = 256;
[StructLayout(LayoutKind.Sequential)]
public struct SHITEMID
{
public ushort cb;
[MarshalAs(UnmanagedType.LPArray)]
public byte[] abID;
}
[StructLayout(LayoutKind.Sequential)]
public struct ITEMIDLIST
{
public SHITEMID mkid;
}
[StructLayout(LayoutKind.Sequential)]
public struct BROWSEINFO
{
public IntPtr hwndOwner;
public IntPtr pidlRoot;
public IntPtr pszDisplayName;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszTitle;
public uint ulFlags;
public IntPtr lpfn;
public int lParam;
public IntPtr iImage;
}
// Browsing for directory.
public const uint BIF_RETURNONLYFSDIRS = 0x0001;
public const uint BIF_DONTGOBELOWDOMAIN = 0x0002;
public const uint BIF_STATUSTEXT = 0x0004;
public const uint BIF_RETURNFSANCESTORS = 0x0008;
public const uint BIF_EDITBOX = 0x0010;
public const uint BIF_VALIDATE = 0x0020;
public const uint BIF_NEWDIALOGSTYLE = 0x0040;
public const uint BIF_USENEWUI = (BIF_NEWDIALOGSTYLE | BIF_EDITBOX);
public const uint BIF_BROWSEINCLUDEURLS = 0x0080;
public const uint BIF_BROWSEFORCOMPUTER = 0x1000;
public const uint BIF_BROWSEFORPRINTER = 0x2000;
public const uint BIF_BROWSEINCLUDEFILES = 0x4000;
public const uint BIF_SHAREABLE = 0x8000;
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public const int NAMESIZE = 80;
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAX_PATH)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=NAMESIZE)]
public string szTypeName;
};
public const uint SHGFI_ICON = 0x000000100; // get icon
public const uint SHGFI_DISPLAYNAME = 0x000000200; // get display name
public const uint SHGFI_TYPENAME = 0x000000400; // get type name
public const uint SHGFI_ATTRIBUTES = 0x000000800; // get attributes
public const uint SHGFI_ICONLOCATION = 0x000001000; // get icon location
public const uint SHGFI_EXETYPE = 0x000002000; // return exe type
public const uint SHGFI_SYSICONINDEX = 0x000004000; // get system icon index
public const uint SHGFI_LINKOVERLAY = 0x000008000; // put a link overlay on icon
public const uint SHGFI_SELECTED = 0x000010000; // show icon in selected state
public const uint SHGFI_ATTR_SPECIFIED = 0x000020000; // get only specified attributes
public const uint SHGFI_LARGEICON = 0x000000000; // get large icon
public const uint SHGFI_SMALLICON = 0x000000001; // get small icon
public const uint SHGFI_OPENICON = 0x000000002; // get open icon
public const uint SHGFI_SHELLICONSIZE = 0x000000004; // get shell size icon
public const uint SHGFI_PIDL = 0x000000008; // pszPath is a pidl
public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010; // use passed dwFileAttribute
public const uint SHGFI_ADDOVERLAYS = 0x000000020; // apply the appropriate overlays
public const uint SHGFI_OVERLAYINDEX = 0x000000040; // Get the index of the overlay
public const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
[DllImport("Shell32.dll")]
public static extern IntPtr SHGetFileInfo(
string pszPath,
uint dwFileAttributes,
ref SHFILEINFO psfi,
uint cbFileInfo,
uint uFlags
);
}
/// <summary>
/// Wraps necessary functions imported from User32.dll. Code courtesy of MSDN Cold Rooster Consulting example.
/// </summary>
public class User32
{
/// <summary>
/// Provides access to function required to delete handle. This method is used internally
/// and is not required to be called separately.
/// </summary>
/// <param name="hIcon">Pointer to icon handle.</param>
/// <returns>N/A</returns>
[DllImport("User32.dll")]
public static extern int DestroyIcon( IntPtr hIcon );
}
#endregion
#region GetFolderIcon / GetFileIcon
/// <summary>
/// Two constants extracted from the FileInfoFlags, the only that are
/// meaningfull for the user of this class.
/// </summary>
public enum SystemIconSize : int
{
Large = 0x000000000,
Small = 0x000000001
}
/// <summary>
/// Options to specify whether folders should be in the open or closed state.
/// </summary>
public enum FolderType
{
/// <summary>
/// Specify open folder.
/// </summary>
Open = 0,
/// <summary>
/// Specify closed folder.
/// </summary>
Closed = 1
}
/// <summary>
/// Returns an icon for a given file - indicated by the name parameter.
/// </summary>
/// <param name="name">Pathname for file.</param>
/// <param name="size">Large or small</param>
/// <param name="linkOverlay">Whether to include the link icon</param>
/// <returns>System.Drawing.Icon</returns>
public static System.Drawing.Icon GetFileIcon(string name, SystemIconSize size, bool linkOverlay)
{
Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;
if (true == linkOverlay) flags += Shell32.SHGFI_LINKOVERLAY;
/* Check the size specified for return. */
if (SystemIconSize.Small == size)
{
flags += Shell32.SHGFI_SMALLICON ;
}
else
{
flags += Shell32.SHGFI_LARGEICON ;
}
Shell32.SHGetFileInfo( name,
Shell32.FILE_ATTRIBUTE_NORMAL,
ref shfi,
(uint) System.Runtime.InteropServices.Marshal.SizeOf(shfi),
flags );
if (shfi.hIcon != IntPtr.Zero)
{
// Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly
System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
User32.DestroyIcon(shfi.hIcon); // Cleanup
return icon;
}
else
return null;
}
/// <summary>
/// Used to access system folder icons.
/// </summary>
/// <param name="size">Specify large or small icons.</param>
/// <param name="folderType">Specify open or closed FolderType.</param>
/// <returns>System.Drawing.Icon</returns>
public static System.Drawing.Icon GetFolderIcon( SystemIconSize size, FolderType folderType )
{
// Need to add size check, although errors generated at present!
uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;
if (FolderType.Open == folderType)
{
flags += Shell32.SHGFI_OPENICON;
}
if (SystemIconSize.Small == size)
{
flags += Shell32.SHGFI_SMALLICON;
}
else
{
flags += Shell32.SHGFI_LARGEICON;
}
// Get the folder icon
Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
Shell32.SHGetFileInfo( "dummy", // Windows 7 needs a string passed to this regardless. Previous versions of windows could handle null
Shell32.FILE_ATTRIBUTE_DIRECTORY,
ref shfi,
(uint) System.Runtime.InteropServices.Marshal.SizeOf(shfi),
flags );
if (shfi.hIcon != IntPtr.Zero)
{
System.Drawing.Icon.FromHandle(shfi.hIcon); // Load the icon from an HICON handle
// Now clone the icon, so that it can be successfully stored in an ImageList
System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
User32.DestroyIcon(shfi.hIcon); // Cleanup
return icon;
}
else
return null;
}
#endregion
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#region IconFromExtension methods (sourced elsewhere from above code)
#region Custom exceptions class
public class IconNotFoundException : Exception
{
public IconNotFoundException( string fileName, int index )
: base( string.Format( "Icon with Id = {0} wasn't found in file {1}", index, fileName ) )
{
}
}
public class UnableToExtractIconsException : Exception
{
public UnableToExtractIconsException( string fileName, int firstIconIndex, int iconCount )
: base( string.Format( "Tryed to extract {2} icons starting from the one with id {1} from the \"{0}\" file but failed", fileName, firstIconIndex, iconCount ) )
{
}
}
#endregion
#region DllImports
/// <summary>
/// Contains information about a file object.
/// </summary>
struct SHFILEINFO
{
/// <summary>
/// Handle to the icon that represents the file. You are responsible for
/// destroying this handle with DestroyIcon when you no longer need it.
/// </summary>
public IntPtr hIcon;
/// <summary>
/// Index of the icon image within the system image list.
/// </summary>
public IntPtr iIcon;
/// <summary>
/// Array of values that indicates the attributes of the file object.
/// For information about these values, see the IShellFolder::GetAttributesOf
/// method.
/// </summary>
public uint dwAttributes;
/// <summary>
/// String that contains the name of the file as it appears in the Microsoft
/// Windows Shell, or the path and file name of the file that contains the
/// icon representing the file.
/// </summary>
[MarshalAs( UnmanagedType.ByValTStr, SizeConst = 260 )]
public string szDisplayName;
/// <summary>
/// String that describes the type of file.
/// </summary>
[MarshalAs( UnmanagedType.ByValTStr, SizeConst = 80 )]
public string szTypeName;
};
[Flags]
enum FileInfoFlags : int
{
/// <summary>
/// Retrieve the handle to the icon that represents the file and the index
/// of the icon within the system image list. The handle is copied to the
/// hIcon member of the structure specified by psfi, and the index is copied
/// to the iIcon member.
/// </summary>
SHGFI_ICON = 0x000000100,
/// <summary>
/// Indicates that the function should not attempt to access the file
/// specified by pszPath. Rather, it should act as if the file specified by
/// pszPath exists with the file attributes passed in dwFileAttributes.
/// </summary>
SHGFI_USEFILEATTRIBUTES = 0x000000010
}
/// <summary>
/// Creates an array of handles to large or small icons extracted from
/// the specified executable file, dynamic-link library (DLL), or icon
/// file.
/// </summary>
/// <param name="lpszFile">
/// Name of an executable file, DLL, or icon file from which icons will
/// be extracted.
/// </param>
/// <param name="nIconIndex">
/// <para>
/// Specifies the zero-based index of the first icon to extract. For
/// example, if this value is zero, the function extracts the first
/// icon in the specified file.
/// </para>
/// <para>
/// If this value is ?1 and <paramref name="phiconLarge"/> and
/// <paramref name="phiconSmall"/> are both NULL, the function returns
/// the total number of icons in the specified file. If the file is an
/// executable file or DLL, the return value is the number of
/// RT_GROUP_ICON resources. If the file is an .ico file, the return
/// value is 1.
/// </para>
/// <para>
/// Windows 95/98/Me, Windows NT 4.0 and later: If this value is a
/// negative number and either <paramref name="phiconLarge"/> or
/// <paramref name="phiconSmall"/> is not NULL, the function begins by
/// extracting the icon whose resource identifier is equal to the
/// absolute value of <paramref name="nIconIndex"/>. For example, use -3
/// to extract the icon whose resource identifier is 3.
/// </para>
/// </param>
/// <param name="phIconLarge">
/// An array of icon handles that receives handles to the large icons
/// extracted from the file. If this parameter is NULL, no large icons
/// are extracted from the file.
/// </param>
/// <param name="phIconSmall">
/// An array of icon handles that receives handles to the small icons
/// extracted from the file. If this parameter is NULL, no small icons
/// are extracted from the file.
/// </param>
/// <param name="nIcons">
/// Specifies the number of icons to extract from the file.
/// </param>
/// <returns>
/// If the <paramref name="nIconIndex"/> parameter is -1, the
/// <paramref name="phIconLarge"/> parameter is NULL, and the
/// <paramref name="phiconSmall"/> parameter is NULL, then the return
/// value is the number of icons contained in the specified file.
/// Otherwise, the return value is the number of icons successfully
/// extracted from the file.
/// </returns>
[DllImport( "Shell32.dll", CharSet = CharSet.Auto )]
extern static int ExtractIconEx(
[MarshalAs( UnmanagedType.LPTStr )]
string lpszFile,
int nIconIndex,
IntPtr[] phIconLarge,
IntPtr[] phIconSmall,
int nIcons );
[DllImport( "Shell32.dll", CharSet = CharSet.Auto )]
extern static IntPtr SHGetFileInfo(
string pszPath,
int dwFileAttributes,
ref SHFILEINFO psfi,
int cbFileInfo,
FileInfoFlags uFlags );
#endregion
/// <summary>
/// Get the number of icons in the specified file.
/// </summary>
/// <param name="fileName">Full path of the file to look for.</param>
/// <returns></returns>
static int GetIconsCountInFile( string fileName )
{
return ExtractIconEx( fileName, -1, null, null, 0 );
}
#region ExtractIcon-like functions
public static void ExtractEx( string fileName, List<Icon> largeIcons,
List<Icon> smallIcons, int firstIconIndex, int iconCount )
{
/*
* Memory allocations
*/
IntPtr[] smallIconsPtrs = null;
IntPtr[] largeIconsPtrs = null;
if ( smallIcons != null )
{
smallIconsPtrs = new IntPtr[ iconCount ];
}
if ( largeIcons != null )
{
largeIconsPtrs = new IntPtr[ iconCount ];
}
/*
* Call to native Win32 API
*/
int apiResult = ExtractIconEx( fileName, firstIconIndex, largeIconsPtrs, smallIconsPtrs, iconCount );
if ( apiResult != iconCount )
{
throw new UnableToExtractIconsException( fileName, firstIconIndex, iconCount );
}
/*
* Fill lists
*/
if ( smallIcons != null )
{
smallIcons.Clear();
foreach ( IntPtr actualIconPtr in smallIconsPtrs )
{
smallIcons.Add( Icon.FromHandle( actualIconPtr ) );
}
}
if ( largeIcons != null )
{
largeIcons.Clear();
foreach ( IntPtr actualIconPtr in largeIconsPtrs )
{
largeIcons.Add( Icon.FromHandle( actualIconPtr ) );
}
}
}
public static List<Icon> ExtractEx( string fileName, SystemIconSize size,
int firstIconIndex, int iconCount )
{
List<Icon> iconList = new List<Icon>();
switch ( size )
{
case SystemIconSize.Large:
ExtractEx( fileName, iconList, null, firstIconIndex, iconCount );
break;
case SystemIconSize.Small:
ExtractEx( fileName, null, iconList, firstIconIndex, iconCount );
break;
default:
throw new ArgumentOutOfRangeException( "size" );
}
return iconList;
}
public static void Extract( string fileName, List<Icon> largeIcons, List<Icon> smallIcons )
{
int iconCount = GetIconsCountInFile( fileName );
ExtractEx( fileName, largeIcons, smallIcons, 0, iconCount );
}
public static List<Icon> Extract( string fileName, SystemIconSize size )
{
int iconCount = GetIconsCountInFile( fileName );
return ExtractEx( fileName, size, 0, iconCount );
}
public static Icon ExtractOne( string fileName, int index, SystemIconSize size )
{
try
{
List<Icon> iconList = ExtractEx( fileName, size, index, 1 );
return iconList[ 0 ];
}
catch ( UnableToExtractIconsException )
{
throw new IconNotFoundException( fileName, index );
}
}
public static void ExtractOne( string fileName, int index,
out Icon largeIcon, out Icon smallIcon )
{
List<Icon> smallIconList = new List<Icon>();
List<Icon> largeIconList = new List<Icon>();
try
{
ExtractEx( fileName, largeIconList, smallIconList, index, 1 );
largeIcon = largeIconList[ 0 ];
smallIcon = smallIconList[ 0 ];
}
catch ( UnableToExtractIconsException )
{
throw new IconNotFoundException( fileName, index );
}
}
#endregion
//this will look throw the registry
//to find if the Extension have an icon.
public static Icon IconFromExtension( string extension,
SystemIconSize size )
{
// Add the '.' to the extension if needed
if ( extension[ 0 ] != '.' ) extension = '.' + extension;
//opens the registry for the wanted key.
RegistryKey Root = Registry.ClassesRoot;
RegistryKey ExtensionKey = Root.OpenSubKey( extension );
ExtensionKey.GetValueNames();
RegistryKey ApplicationKey = Root.OpenSubKey( ExtensionKey.GetValue( "" ).ToString() );
//gets the name of the file that have the icon.
string IconLocation = ApplicationKey.OpenSubKey( "DefaultIcon" ).GetValue( "" ).ToString();
string[] IconPath = IconLocation.Split( ',' );
if ( IconPath[ 1 ] == null ) IconPath[ 1 ] = "0";
IntPtr[] Large = new IntPtr[ 1 ], Small = new IntPtr[ 1 ];
//extracts the icon from the file.
ExtractIconEx( IconPath[ 0 ],
Convert.ToInt16( IconPath[ 1 ] ), Large, Small, 1 );
if (size == SystemIconSize.Large)
{
return Large[0] == IntPtr.Zero ? null : Icon.FromHandle(Large[0]);
}
else
{
return Small[0] == IntPtr.Zero ? null : Icon.FromHandle(Small[0]);
}
}
public static Icon IconFromExtensionShell( string extension, SystemIconSize size )
{
//add '.' if nessesry
if ( extension[ 0 ] != '.' ) extension = '.' + extension;
//temp struct for getting file shell info
SHFILEINFO fileInfo = new SHFILEINFO();
SHGetFileInfo(
extension,
0,
ref fileInfo,
Marshal.SizeOf( fileInfo ),
FileInfoFlags.SHGFI_ICON | FileInfoFlags.SHGFI_USEFILEATTRIBUTES | (FileInfoFlags)size );
return fileInfo.hIcon == IntPtr.Zero ? null : Icon.FromHandle( fileInfo.hIcon );
}
public static Icon IconFromResource( string resourceName )
{
Assembly assembly = Assembly.GetCallingAssembly();
return new Icon( assembly.GetManifestResourceStream( resourceName ) );
}
/// <summary>
/// Parse strings in registry who contains the name of the icon and
/// the index of the icon an return both parts.
/// </summary>
/// <param name="regString">The full string in the form "path,index" as found in registry.</param>
/// <param name="fileName">The "path" part of the string.</param>
/// <param name="index">The "index" part of the string.</param>
public static void ExtractInformationsFromRegistryString(
string regString, out string fileName, out int index )
{
if ( regString == null )
{
throw new ArgumentNullException( "regString" );
}
if ( regString.Length == 0 )
{
throw new ArgumentException( "The string should not be empty.", "regString" );
}
index = 0;
string[] strArr = regString.Replace( "\"", "" ).Split( ',' );
fileName = strArr[ 0 ].Trim();
if ( strArr.Length > 1 )
{
int.TryParse( strArr[ 1 ].Trim(), out index );
}
}
public static Icon ExtractFromRegistryString( string regString, SystemIconSize size )
{
string fileName;
int index;
ExtractInformationsFromRegistryString( regString, out fileName, out index );
return ExtractOne( fileName, index, size );
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using BTDB.Buffer;
using BTDB.FieldHandler;
using BTDB.KVDBLayer;
using BTDB.StreamLayer;
namespace BTDB.ODBLayer
{
public class ODBSet<TKey> : IOrderedSet<TKey>, IQuerySizeDictionary<TKey>
{
readonly IInternalObjectDBTransaction _tr;
readonly IFieldHandler _keyHandler;
readonly Func<AbstractBufferedReader, IReaderCtx, TKey> _keyReader;
readonly Action<TKey, AbstractBufferedWriter, IWriterCtx> _keyWriter;
readonly IKeyValueDBTransaction _keyValueTr;
readonly KeyValueDBTransactionProtector _keyValueTrProtector;
readonly ulong _id;
readonly byte[] _prefix;
int _count;
int _modificationCounter;
public ODBSet(IInternalObjectDBTransaction tr, ODBDictionaryConfiguration config, ulong id)
{
_tr = tr;
_keyHandler = config.KeyHandler;
_id = id;
var o = ObjectDB.AllDictionariesPrefix.Length;
_prefix = new byte[o + PackUnpack.LengthVUInt(_id)];
Array.Copy(ObjectDB.AllDictionariesPrefix, _prefix, o);
PackUnpack.PackVUInt(_prefix, ref o, _id);
_keyReader = ((Func<AbstractBufferedReader, IReaderCtx, TKey>) config.KeyReader)!;
_keyWriter = ((Action<TKey, AbstractBufferedWriter, IWriterCtx>) config.KeyWriter)!;
_keyValueTr = _tr.KeyValueDBTransaction;
_keyValueTrProtector = _tr.TransactionProtector;
_count = -1;
}
// ReSharper disable once UnusedMember.Global
public ODBSet(IInternalObjectDBTransaction tr, ODBDictionaryConfiguration config) : this(tr, config,
tr.AllocateDictionaryId())
{
}
static void ThrowModifiedDuringEnum()
{
throw new InvalidOperationException("DB modified during iteration");
}
// ReSharper disable once UnusedMember.Global
public static void DoSave(IWriterCtx ctx, IOrderedSet<TKey>? dictionary, int cfgId)
{
var writerCtx = (IDBWriterCtx) ctx;
if (!(dictionary is ODBSet<TKey> goodDict))
{
var tr = writerCtx.GetTransaction();
var id = tr.AllocateDictionaryId();
goodDict = new ODBSet<TKey>(tr, ODBDictionaryConfiguration.Get(cfgId), id);
if (dictionary != null)
foreach (var pair in dictionary)
goodDict.Add(pair);
}
ctx.Writer().WriteVUInt64(goodDict._id);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
void ICollection<TKey>.Add(TKey item)
{
Add(item!);
}
public void ExceptWith(IEnumerable<TKey> other)
{
foreach (var key in other)
{
Remove(key);
}
}
public void IntersectWith(IEnumerable<TKey> other)
{
throw new NotSupportedException();
}
public bool IsProperSubsetOf(IEnumerable<TKey> other)
{
throw new NotSupportedException();
}
public bool IsProperSupersetOf(IEnumerable<TKey> other)
{
throw new NotSupportedException();
}
public bool IsSubsetOf(IEnumerable<TKey> other)
{
throw new NotSupportedException();
}
public bool IsSupersetOf(IEnumerable<TKey> other)
{
throw new NotSupportedException();
}
public bool Overlaps(IEnumerable<TKey> other)
{
throw new NotSupportedException();
}
public bool SetEquals(IEnumerable<TKey> other)
{
throw new NotSupportedException();
}
public void SymmetricExceptWith(IEnumerable<TKey> other)
{
throw new NotSupportedException();
}
public void UnionWith(IEnumerable<TKey> other)
{
foreach (var key in other)
{
Add(key);
}
}
public void Clear()
{
_keyValueTrProtector.Start();
_modificationCounter++;
_keyValueTr.SetKeyPrefix(_prefix);
_keyValueTr.EraseAll();
_count = 0;
}
public bool Contains(TKey item)
{
var keyBytes = KeyToByteArray(item);
_keyValueTrProtector.Start();
_keyValueTr.SetKeyPrefix(_prefix);
return _keyValueTr.Find(keyBytes) == FindResult.Exact;
}
public void CopyTo(TKey[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException(nameof(array));
if ((arrayIndex < 0) || (arrayIndex > array.Length))
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, "Needs to be nonnegative ");
}
if ((array.Length - arrayIndex) < Count)
{
throw new ArgumentException("Array too small");
}
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
public int Count
{
get
{
if (_count == -1)
{
_keyValueTrProtector.Start();
_keyValueTr.SetKeyPrefix(_prefix);
_count = (int) Math.Min(_keyValueTr.GetKeyValueCount(), int.MaxValue);
}
return _count;
}
}
public bool IsReadOnly => false;
ByteBuffer KeyToByteArray(TKey key)
{
var writer = new ByteBufferWriter();
IWriterCtx ctx = null;
if (_keyHandler.NeedsCtx()) ctx = new DBWriterCtx(_tr, writer);
_keyWriter(key, writer, ctx);
return writer.Data;
}
TKey ByteArrayToKey(ByteBuffer data)
{
var reader = new ByteBufferReader(data);
IReaderCtx ctx = null;
if (_keyHandler.NeedsCtx()) ctx = new DBReaderCtx(_tr, reader);
return _keyReader(reader, ctx);
}
public bool Add(TKey key)
{
var keyBytes = KeyToByteArray(key);
_keyValueTrProtector.Start();
_modificationCounter++;
_keyValueTr.SetKeyPrefix(_prefix);
var created = _keyValueTr.CreateOrUpdateKeyValue(keyBytes, ByteBuffer.NewEmpty());
if (created) NotifyAdded();
return created;
}
public bool Remove(TKey key)
{
var keyBytes = KeyToByteArray(key);
_keyValueTrProtector.Start();
_modificationCounter++;
_keyValueTr.SetKeyPrefix(_prefix);
if (_keyValueTr.Find(keyBytes) != FindResult.Exact) return false;
_keyValueTr.EraseCurrent();
NotifyRemoved();
return true;
}
void NotifyAdded()
{
if (_count != -1)
{
if (_count != int.MaxValue) _count++;
}
}
void NotifyRemoved()
{
if (_count != -1)
{
if (_count == int.MaxValue)
{
_count = (int) Math.Min(_keyValueTr.GetKeyValueCount(), int.MaxValue);
}
else
{
_count--;
}
}
}
public IEnumerator<TKey> GetEnumerator()
{
long prevProtectionCounter = 0;
var prevModificationCounter = 0;
long pos = 0;
while (true)
{
_keyValueTrProtector.Start();
if (pos == 0)
{
prevModificationCounter = _modificationCounter;
_keyValueTr.SetKeyPrefix(_prefix);
if (!_keyValueTr.FindFirstKey()) break;
}
else
{
if (_keyValueTrProtector.WasInterupted(prevProtectionCounter))
{
if (prevModificationCounter != _modificationCounter)
ThrowModifiedDuringEnum();
_keyValueTr.SetKeyPrefix(_prefix);
if (!_keyValueTr.SetKeyIndex(pos)) break;
}
else
{
if (!_keyValueTr.FindNextKey()) break;
}
}
prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
var keyBytes = _keyValueTr.GetKey();
var key = ByteArrayToKey(keyBytes);
yield return key;
pos++;
}
}
public IEnumerable<TKey> GetReverseEnumerator()
{
long prevProtectionCounter = 0;
var prevModificationCounter = 0;
var pos = long.MaxValue;
while (true)
{
_keyValueTrProtector.Start();
if (pos == long.MaxValue)
{
prevModificationCounter = _modificationCounter;
_keyValueTr.SetKeyPrefix(_prefix);
if (!_keyValueTr.FindLastKey()) break;
pos = _keyValueTr.GetKeyIndex();
}
else
{
if (_keyValueTrProtector.WasInterupted(prevProtectionCounter))
{
if (prevModificationCounter != _modificationCounter)
ThrowModifiedDuringEnum();
_keyValueTr.SetKeyPrefix(_prefix);
if (!_keyValueTr.SetKeyIndex(pos)) break;
}
else
{
if (!_keyValueTr.FindPreviousKey()) break;
}
}
prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
var keyBytes = _keyValueTr.GetKey();
var key = ByteArrayToKey(keyBytes);
yield return key;
pos--;
}
}
public IEnumerable<TKey> GetIncreasingEnumerator(TKey start)
{
var startKeyBytes = KeyToByteArray(start);
long prevProtectionCounter = 0;
var prevModificationCounter = 0;
long pos = 0;
while (true)
{
_keyValueTrProtector.Start();
if (pos == 0)
{
prevModificationCounter = _modificationCounter;
_keyValueTr.SetKeyPrefix(_prefix);
bool startOk;
switch (_keyValueTr.Find(startKeyBytes))
{
case FindResult.Exact:
case FindResult.Next:
startOk = true;
break;
case FindResult.Previous:
startOk = _keyValueTr.FindNextKey();
break;
case FindResult.NotFound:
startOk = false;
break;
default:
throw new ArgumentOutOfRangeException();
}
if (!startOk) break;
pos = _keyValueTr.GetKeyIndex();
}
else
{
if (_keyValueTrProtector.WasInterupted(prevProtectionCounter))
{
if (prevModificationCounter != _modificationCounter)
ThrowModifiedDuringEnum();
_keyValueTr.SetKeyPrefix(_prefix);
if (!_keyValueTr.SetKeyIndex(pos)) break;
}
else
{
if (!_keyValueTr.FindNextKey()) break;
}
}
prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
var keyBytes = _keyValueTr.GetKey();
var key = ByteArrayToKey(keyBytes);
yield return key;
pos++;
}
}
public IEnumerable<TKey> GetDecreasingEnumerator(TKey start)
{
var startKeyBytes = KeyToByteArray(start);
long prevProtectionCounter = 0;
var prevModificationCounter = 0;
var pos = long.MaxValue;
while (true)
{
_keyValueTrProtector.Start();
if (pos == long.MaxValue)
{
prevModificationCounter = _modificationCounter;
_keyValueTr.SetKeyPrefix(_prefix);
bool startOk;
switch (_keyValueTr.Find(startKeyBytes))
{
case FindResult.Exact:
case FindResult.Previous:
startOk = true;
break;
case FindResult.Next:
startOk = _keyValueTr.FindPreviousKey();
break;
case FindResult.NotFound:
startOk = false;
break;
default:
throw new ArgumentOutOfRangeException();
}
if (!startOk) break;
pos = _keyValueTr.GetKeyIndex();
}
else
{
if (_keyValueTrProtector.WasInterupted(prevProtectionCounter))
{
if (prevModificationCounter != _modificationCounter)
ThrowModifiedDuringEnum();
_keyValueTr.SetKeyPrefix(_prefix);
if (!_keyValueTr.SetKeyIndex(pos)) break;
}
else
{
if (!_keyValueTr.FindPreviousKey()) break;
}
}
prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
var keyBytes = _keyValueTr.GetKey();
var key = ByteArrayToKey(keyBytes);
yield return key;
pos--;
}
}
public long RemoveRange(AdvancedEnumeratorParam<TKey> param)
{
_keyValueTrProtector.Start();
_modificationCounter++;
_keyValueTr.SetKeyPrefix(_prefix);
long startIndex;
long endIndex;
if (param.EndProposition == KeyProposition.Ignored)
{
endIndex = _keyValueTr.GetKeyValueCount() - 1;
}
else
{
var keyBytes = KeyToByteArray(param.End);
switch (_keyValueTr.Find(keyBytes))
{
case FindResult.Exact:
endIndex = _keyValueTr.GetKeyIndex();
if (param.EndProposition == KeyProposition.Excluded)
{
endIndex--;
}
break;
case FindResult.Previous:
endIndex = _keyValueTr.GetKeyIndex();
break;
case FindResult.Next:
endIndex = _keyValueTr.GetKeyIndex() - 1;
break;
case FindResult.NotFound:
endIndex = -1;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
if (param.StartProposition == KeyProposition.Ignored)
{
startIndex = 0;
}
else
{
var keyBytes = KeyToByteArray(param.Start);
switch (_keyValueTr.Find(keyBytes))
{
case FindResult.Exact:
startIndex = _keyValueTr.GetKeyIndex();
if (param.StartProposition == KeyProposition.Excluded)
{
startIndex++;
}
break;
case FindResult.Previous:
startIndex = _keyValueTr.GetKeyIndex() + 1;
break;
case FindResult.Next:
startIndex = _keyValueTr.GetKeyIndex();
break;
case FindResult.NotFound:
startIndex = 0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
_keyValueTr.EraseRange(startIndex, endIndex);
_count = -1;
return Math.Max(0, endIndex - startIndex + 1);
}
public IEnumerable<KeyValuePair<uint, uint>> QuerySizeEnumerator()
{
long prevProtectionCounter = 0;
var prevModificationCounter = 0;
long pos = 0;
while (true)
{
_keyValueTrProtector.Start();
if (pos == 0)
{
prevModificationCounter = _modificationCounter;
_keyValueTr.SetKeyPrefix(_prefix);
if (!_keyValueTr.FindFirstKey()) break;
}
else
{
if (_keyValueTrProtector.WasInterupted(prevProtectionCounter))
{
if (prevModificationCounter != _modificationCounter)
ThrowModifiedDuringEnum();
_keyValueTr.SetKeyPrefix(_prefix);
if (!_keyValueTr.SetKeyIndex(pos)) break;
}
else
{
if (!_keyValueTr.FindNextKey()) break;
}
}
prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
var size = _keyValueTr.GetStorageSizeOfCurrentKey();
yield return size;
pos++;
}
}
public KeyValuePair<uint, uint> QuerySizeByKey(TKey key)
{
var keyBytes = KeyToByteArray(key);
_keyValueTrProtector.Start();
_keyValueTr.SetKeyPrefix(_prefix);
var found = _keyValueTr.Find(keyBytes) == FindResult.Exact;
if (!found)
{
throw new ArgumentException("Key not found in Set");
}
var size = _keyValueTr.GetStorageSizeOfCurrentKey();
return size;
}
class AdvancedEnumerator : IEnumerable<TKey>, IEnumerator<TKey>
{
readonly ODBSet<TKey> _owner;
readonly KeyValueDBTransactionProtector _keyValueTrProtector;
readonly IKeyValueDBTransaction _keyValueTr;
long _prevProtectionCounter;
readonly int _prevModificationCounter;
readonly uint _startPos;
readonly uint _count;
uint _pos;
SeekState _seekState;
readonly bool _ascending;
public AdvancedEnumerator(ODBSet<TKey> owner, AdvancedEnumeratorParam<TKey> param)
{
_owner = owner;
_keyValueTrProtector = _owner._keyValueTrProtector;
_keyValueTr = _owner._keyValueTr;
_ascending = param.Order == EnumerationOrder.Ascending;
_keyValueTrProtector.Start();
_prevModificationCounter = _owner._modificationCounter;
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
_keyValueTr.SetKeyPrefix(_owner._prefix);
long startIndex;
long endIndex;
if (param.EndProposition == KeyProposition.Ignored)
{
endIndex = _keyValueTr.GetKeyValueCount() - 1;
}
else
{
var keyBytes = _owner.KeyToByteArray(param.End);
switch (_keyValueTr.Find(keyBytes))
{
case FindResult.Exact:
endIndex = _keyValueTr.GetKeyIndex();
if (param.EndProposition == KeyProposition.Excluded)
{
endIndex--;
}
break;
case FindResult.Previous:
endIndex = _keyValueTr.GetKeyIndex();
break;
case FindResult.Next:
endIndex = _keyValueTr.GetKeyIndex() - 1;
break;
case FindResult.NotFound:
endIndex = -1;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
if (param.StartProposition == KeyProposition.Ignored)
{
startIndex = 0;
}
else
{
var keyBytes = _owner.KeyToByteArray(param.Start);
switch (_keyValueTr.Find(keyBytes))
{
case FindResult.Exact:
startIndex = _keyValueTr.GetKeyIndex();
if (param.StartProposition == KeyProposition.Excluded)
{
startIndex++;
}
break;
case FindResult.Previous:
startIndex = _keyValueTr.GetKeyIndex() + 1;
break;
case FindResult.Next:
startIndex = _keyValueTr.GetKeyIndex();
break;
case FindResult.NotFound:
startIndex = 0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
_count = (uint) Math.Max(0, endIndex - startIndex + 1);
_startPos = (uint) (_ascending ? startIndex : endIndex);
_pos = 0;
_seekState = SeekState.Undefined;
}
void Seek()
{
if (_ascending)
_keyValueTr.SetKeyIndex(_startPos + _pos);
else
_keyValueTr.SetKeyIndex(_startPos - _pos);
_seekState = SeekState.Ready;
}
public IEnumerator<TKey> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
public bool MoveNext()
{
if (_seekState == SeekState.Ready)
_pos++;
if (_pos >= _count)
{
Current = default;
return false;
}
_keyValueTrProtector.Start();
if (_keyValueTrProtector.WasInterupted(_prevProtectionCounter))
{
if (_prevModificationCounter != _owner._modificationCounter)
ThrowModifiedDuringEnum();
_keyValueTr.SetKeyPrefix(_owner._prefix);
Seek();
}
else if (_seekState != SeekState.Ready)
{
Seek();
}
else
{
if (_ascending)
{
_keyValueTr.FindNextKey();
}
else
{
_keyValueTr.FindPreviousKey();
}
}
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
Current = _owner.ByteArrayToKey(_keyValueTr.GetKey());
return true;
}
public void Reset()
{
throw new NotSupportedException();
}
public TKey Current { get; private set; }
object? IEnumerator.Current => Current;
public void Dispose()
{
}
}
public IEnumerable<TKey> GetAdvancedEnumerator(AdvancedEnumeratorParam<TKey> param)
{
return new AdvancedEnumerator(this, param);
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
public class Triangulator {
private List<Vector2> m_points = new List<Vector2> ();
public Triangulator (Vector2[] points)
{
m_points = new List<Vector2> (points);
}
public int[] Triangulate ()
{
List<int> indices = new List<int> ();
int n = m_points.Count;
if (n < 3)
return indices.ToArray ();
int[] V = new int[n];
if (Area () > 0) {
for (int v = 0; v < n; v++)
V [v] = v;
} else {
for (int v = 0; v < n; v++)
V [v] = (n - 1) - v;
}
int nv = n;
int count = 2 * nv;
for (int m = 0, v = nv - 1; nv > 2;) {
if ((count--) <= 0)
return indices.ToArray ();
int u = v;
if (nv <= u)
u = 0;
v = u + 1;
if (nv <= v)
v = 0;
int w = v + 1;
if (nv <= w)
w = 0;
if (Snip (u, v, w, nv, V)) {
int a, b, c, s, t;
a = V [u];
b = V [v];
c = V [w];
indices.Add (a);
indices.Add (b);
indices.Add (c);
m++;
for (s = v, t = v + 1; t < nv; s++, t++)
V [s] = V [t];
nv--;
count = 2 * nv;
}
}
indices.Reverse ();
return indices.ToArray ();
}
private float Area ()
{
int n = m_points.Count;
float A = 0.0f;
for (int p = n - 1, q = 0; q < n; p = q++) {
Vector2 pval = m_points [p];
Vector2 qval = m_points [q];
A += pval.x * qval.y - qval.x * pval.y;
}
return (A * 0.5f);
}
private bool Snip (int u, int v, int w, int n, int[] V)
{
int p;
Vector2 A = m_points [V [u]];
Vector2 B = m_points [V [v]];
Vector2 C = m_points [V [w]];
if (Mathf.Epsilon > (((B.x - A.x) * (C.y - A.y)) - ((B.y - A.y) * (C.x - A.x))))
return false;
for (p = 0; p < n; p++) {
if ((p == u) || (p == v) || (p == w))
continue;
Vector2 P = m_points [V [p]];
if (InsideTriangle (A, B, C, P))
return false;
}
return true;
}
private bool InsideTriangle (Vector2 A, Vector2 B, Vector2 C, Vector2 P)
{
float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
float cCROSSap, bCROSScp, aCROSSbp;
ax = C.x - B.x;
ay = C.y - B.y;
bx = A.x - C.x;
by = A.y - C.y;
cx = B.x - A.x;
cy = B.y - A.y;
apx = P.x - A.x;
apy = P.y - A.y;
bpx = P.x - B.x;
bpy = P.y - B.y;
cpx = P.x - C.x;
cpy = P.y - C.y;
aCROSSbp = ax * bpy - ay * bpx;
cCROSSap = cx * apy - cy * apx;
bCROSScp = bx * cpy - by * cpx;
return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f));
}
public static Mesh CreateMesh3D (Vector2[] poly, float extrusion)
{
// convert polygon to triangles
Triangulator triangulator = new Triangulator (poly);
int[] traingulatedTris = triangulator.Triangulate ();
Mesh m = new Mesh ();
Vector3[] vertices;
if (extrusion == 0f) vertices = new Vector3[poly.Length];
else vertices = new Vector3[poly.Length * 2];
for (int i = 0; i < poly.Length; i++) {
vertices [i].x = poly [i].x;
vertices [i].y = poly [i].y;
vertices [i].z = -extrusion; // front vertex
if (extrusion != 0f) {
vertices [i + poly.Length].x = poly [i].x;
vertices [i + poly.Length].y = poly [i].y;
vertices [i + poly.Length].z = extrusion; // back vertex
}
}
int[] triangles;
if (extrusion == 0f) triangles = new int[traingulatedTris.Length];
else triangles = new int[traingulatedTris.Length * 2 + poly.Length * 6];
int count_tris = 0;
for (int i = 0; i < traingulatedTris.Length; i += 3) {
triangles [i] = traingulatedTris [i];
triangles [i + 1] = traingulatedTris [i + 1];
triangles [i + 2] = traingulatedTris [i + 2];
} // front vertices
if (extrusion != 0f) {
count_tris += traingulatedTris.Length;
for (int i = 0; i < traingulatedTris.Length; i += 3) {
triangles [count_tris + i] = traingulatedTris [i + 2] + poly.Length;
triangles [count_tris + i + 1] = traingulatedTris [i + 1] + poly.Length;
triangles [count_tris + i + 2] = traingulatedTris [i] + poly.Length;
} // back vertices
}
//texture coordinate
Vector2[] uvs = new Vector2[vertices.Length];
for (int i=0,c=uvs.Length; i < c; ++i) {
uvs[i].x = vertices[i].x;
uvs[i].y = vertices[i].y;
}
m.vertices = vertices;
m.triangles = triangles;
m.uv = uvs;
if (extrusion != 0f)
m = Triangulator.SideExtrusion (m);
m.RecalculateNormals ();
m.RecalculateBounds ();
m.Optimize ();
return m;
}
private static Mesh SideExtrusion (Mesh mesh)
{
List<int> indices = new List<int> (mesh.triangles);
int count = (mesh.vertices.Length / 2);
for (int i = 0; i < count; i++) {
int i1 = i;
int i2 = (i1 + 1) % count;
int i3 = i1 + count;
int i4 = i2 + count;
indices.Add (i4);
indices.Add (i3);
indices.Add (i1);
indices.Add (i2);
indices.Add (i4);
indices.Add (i1);
}
mesh.triangles = indices.ToArray ();
return mesh;
}
}
| |
/*
* 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.Collections.Generic;
/// <summary>
/// Represents a simple property bag.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
internal class SimplePropertyBag<TKey> : IEnumerable<KeyValuePair<TKey, object>>
{
private Dictionary<TKey, object> items = new Dictionary<TKey, object>();
private List<TKey> removedItems = new List<TKey>();
private List<TKey> addedItems = new List<TKey>();
private List<TKey> modifiedItems = new List<TKey>();
/// <summary>
/// Add item to change list.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="changeList">The change list.</param>
private static void InternalAddItemToChangeList(TKey key, List<TKey> changeList)
{
if (!changeList.Contains(key))
{
changeList.Add(key);
}
}
/// <summary>
/// Triggers dispatch of the change event.
/// </summary>
private void Changed()
{
if (this.OnChange != null)
{
this.OnChange();
}
}
/// <summary>
/// Remove item.
/// </summary>
/// <param name="key">The key.</param>
private void InternalRemoveItem(TKey key)
{
object value;
if (this.TryGetValue(key, out value))
{
this.items.Remove(key);
this.removedItems.Add(key);
this.Changed();
}
}
/// <summary>
/// Gets the added items.
/// </summary>
/// <value>The added items.</value>
internal IEnumerable<TKey> AddedItems
{
get { return this.addedItems; }
}
/// <summary>
/// Gets the removed items.
/// </summary>
/// <value>The removed items.</value>
internal IEnumerable<TKey> RemovedItems
{
get { return this.removedItems; }
}
/// <summary>
/// Gets the modified items.
/// </summary>
/// <value>The modified items.</value>
internal IEnumerable<TKey> ModifiedItems
{
get { return this.modifiedItems; }
}
/// <summary>
/// Initializes a new instance of the <see cref="SimplePropertyBag<TKey>"/> class.
/// </summary>
public SimplePropertyBag()
{
}
/// <summary>
/// Clears the change log.
/// </summary>
public void ClearChangeLog()
{
this.removedItems.Clear();
this.addedItems.Clear();
this.modifiedItems.Clear();
}
/// <summary>
/// Determines whether the specified key is in the property bag.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key exists; otherwise, <c>false</c>.
/// </returns>
public bool ContainsKey(TKey key)
{
return this.items.ContainsKey(key);
}
/// <summary>
/// Tries to get value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>True if value exists in property bag.</returns>
public bool TryGetValue(TKey key, out object value)
{
return this.items.TryGetValue(key, out value);
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <param name="key">Key.</param>
/// <value>Value associated with key.</value>
public object this[TKey key]
{
get
{
object value;
if (this.TryGetValue(key, out value))
{
return value;
}
else
{
return null;
}
}
set
{
if (value == null)
{
this.InternalRemoveItem(key);
}
else
{
// If the item was to be deleted, the deletion becomes an update.
if (this.removedItems.Remove(key))
{
InternalAddItemToChangeList(key, this.modifiedItems);
}
else
{
// If the property value was not set, we have a newly set property.
if (!this.ContainsKey(key))
{
InternalAddItemToChangeList(key, this.addedItems);
}
else
{
// The last case is that we have a modified property.
if (!this.modifiedItems.Contains(key))
{
InternalAddItemToChangeList(key, this.modifiedItems);
}
}
}
this.items[key] = value;
this.Changed();
}
}
}
/// <summary>
/// Occurs when Changed.
/// </summary>
public event PropertyBagChangedDelegate OnChange;
#region IEnumerable<KeyValuePair<TKey,object>> Members
/// <summary>
/// Gets an enumerator that iterates through the elements of the collection.
/// </summary>
/// <returns>An IEnumerator for the collection.</returns>
public IEnumerator<KeyValuePair<TKey, object>> GetEnumerator()
{
return this.items.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Gets an enumerator that iterates through the elements of the collection.
/// </summary>
/// <returns>An IEnumerator for the collection.</returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.items.GetEnumerator();
}
#endregion
}
}
| |
using System;
using System.Configuration;
using NUnit.Framework;
using StructureMap.Pipeline;
using StructureMap.Testing.Widget;
namespace StructureMap.Testing.Configuration.DSL
{
[TestFixture]
public class AddInstanceTester
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
container = new Container(registry =>
{
registry.Scan(x => x.AssemblyContainingType<ColorWidget>());
// Add an instance with properties
registry.For<IWidget>()
.Add<ColorWidget>()
.WithName("DarkGreen")
.WithProperty("color").EqualTo("DarkGreen");
// Add an instance by specifying the ConcreteKey
registry.For<IWidget>()
.Add<ColorWidget>()
.WithName("Purple")
.WithProperty("color").EqualTo("Purple");
// Pull a property from the App config
registry.For<IWidget>()
.Add<ColorWidget>()
.WithName("AppSetting")
.WithProperty("color").EqualToAppSetting("Color");
// Pull a property from the App config
registry.For<IWidget>()
.Add<NotPluggableWidget>()
.WithName("UsesDefaultValue")
.WithProperty("name").EqualToAppSetting("WidgetName", "TheDefaultValue");
registry.For<IWidget>().Add<AWidget>();
});
}
#endregion
private IContainer container;
[Test]
public void AddAnInstanceWithANameAndAPropertySpecifyingConcreteKey()
{
var widget = (ColorWidget) container.GetInstance<IWidget>("Purple");
Assert.AreEqual("Purple", widget.Color);
}
[Test]
public void AddAnInstanceWithANameAndAPropertySpecifyingConcreteType()
{
var widget = (ColorWidget) container.GetInstance<IWidget>("DarkGreen");
Assert.AreEqual("DarkGreen", widget.Color);
}
[Test]
public void AddInstanceAndOverrideTheConcreteTypeForADependency()
{
IContainer container = new Container(x =>
{
x.For<Rule>().Add<WidgetRule>()
.WithName("AWidgetRule")
.CtorDependency<IWidget>().Is(i => i.OfConcreteType<AWidget>());
});
container.GetInstance<Rule>("AWidgetRule")
.IsType<WidgetRule>()
.Widget.IsType<AWidget>();
}
[Test]
public void CreateAnInstancePullAPropertyFromTheApplicationConfig()
{
Assert.AreEqual("Blue", ConfigurationManager.AppSettings["Color"]);
var widget = (ColorWidget) container.GetInstance<IWidget>("AppSetting");
Assert.AreEqual("Blue", widget.Color);
}
[Test]
public void CreateAnInstanceUsingDefaultPropertyValueWhenSettingDoesNotExistInApplicationConfig()
{
Assert.AreEqual(null, ConfigurationManager.AppSettings["WidgetName"]);
var widget = (NotPluggableWidget) container.GetInstance<IWidget>("UsesDefaultValue");
Assert.AreEqual("TheDefaultValue", widget.Name);
}
[Test]
public void SimpleCaseWithNamedInstance()
{
container = new Container(x =>
{
x.For<IWidget>().Add<AWidget>().WithName("MyInstance");
});
var widget = (AWidget) container.GetInstance<IWidget>("MyInstance");
Assert.IsNotNull(widget);
}
[Test]
public void SpecifyANewInstanceOverrideADependencyWithANamedInstance()
{
container = new Container(registry =>
{
registry.For<Rule>().Add<ARule>().WithName("Alias");
// Add an instance by specifying the ConcreteKey
registry.For<IWidget>()
.Add<ColorWidget>()
.WithName("Purple")
.WithProperty("color").EqualTo("Purple");
// Specify a new Instance, override a dependency with a named instance
registry.For<Rule>().Add<WidgetRule>().WithName("RuleThatUsesMyInstance")
.CtorDependency<IWidget>("widget").Is(x => x.TheInstanceNamed("Purple"));
});
Assert.IsInstanceOfType(typeof (ARule), container.GetInstance<Rule>("Alias"));
var rule = (WidgetRule) container.GetInstance<Rule>("RuleThatUsesMyInstance");
var widget = (ColorWidget) rule.Widget;
Assert.AreEqual("Purple", widget.Color);
}
[Test]
public void SpecifyANewInstanceWithADependency()
{
// Specify a new Instance, create an instance for a dependency on the fly
string instanceKey = "OrangeWidgetRule";
var theContainer = new Container(registry =>
{
registry.For<Rule>().Add<WidgetRule>().WithName(instanceKey)
.CtorDependency<IWidget>().Is(
i => { i.Type<ColorWidget>().WithCtorArg("color").EqualTo("Orange").WithName("Orange"); });
});
var rule = (WidgetRule) theContainer.GetInstance<Rule>(instanceKey);
var widget = (ColorWidget) rule.Widget;
Assert.AreEqual("Orange", widget.Color);
}
[Test]
public void UseAPreBuiltObjectForAnInstanceAsAPrototype()
{
// Build an instance for IWidget, then setup StructureMap to return cloned instances of the
// "Prototype" (GoF pattern) whenever someone asks for IWidget named "Jeremy"
var theWidget = new CloneableWidget("Jeremy");
container = new Container(x =>
{
x.For<IWidget>().Add(new PrototypeInstance(theWidget).Named("Jeremy"));
});
var widget1 = (CloneableWidget) container.GetInstance<IWidget>("Jeremy");
var widget2 = (CloneableWidget) container.GetInstance<IWidget>("Jeremy");
var widget3 = (CloneableWidget) container.GetInstance<IWidget>("Jeremy");
Assert.AreEqual("Jeremy", widget1.Name);
Assert.AreEqual("Jeremy", widget2.Name);
Assert.AreEqual("Jeremy", widget3.Name);
Assert.AreNotSame(widget1, widget2);
Assert.AreNotSame(widget1, widget3);
Assert.AreNotSame(widget2, widget3);
}
[Test]
public void UseAPreBuiltObjectForAnInstanceAsASerializedCopy()
{
// Build an instance for IWidget, then setup StructureMap to return cloned instances of the
// "Prototype" (GoF pattern) whenever someone asks for IWidget named "Jeremy"
var theWidget = new CloneableWidget("Jeremy");
container =
new Container(x =>
{
x.For<IWidget>().Add(new SerializedInstance(theWidget).Named("Jeremy"));
});
var widget1 = (CloneableWidget) container.GetInstance<IWidget>("Jeremy");
var widget2 = (CloneableWidget) container.GetInstance<IWidget>("Jeremy");
var widget3 = (CloneableWidget) container.GetInstance<IWidget>("Jeremy");
Assert.AreEqual("Jeremy", widget1.Name);
Assert.AreEqual("Jeremy", widget2.Name);
Assert.AreEqual("Jeremy", widget3.Name);
Assert.AreNotSame(widget1, widget2);
Assert.AreNotSame(widget1, widget3);
Assert.AreNotSame(widget2, widget3);
}
[Test]
public void UseAPreBuiltObjectWithAName()
{
// Return the specific instance when an IWidget named "Julia" is requested
var julia = new CloneableWidget("Julia");
container =
new Container(x => x.For<IWidget>().Add(julia).WithName("Julia"));
var widget1 = (CloneableWidget) container.GetInstance<IWidget>("Julia");
var widget2 = (CloneableWidget) container.GetInstance<IWidget>("Julia");
var widget3 = (CloneableWidget) container.GetInstance<IWidget>("Julia");
Assert.AreSame(julia, widget1);
Assert.AreSame(julia, widget2);
Assert.AreSame(julia, widget3);
}
}
public class WidgetRule : Rule
{
private readonly IWidget _widget;
public WidgetRule(IWidget widget)
{
_widget = widget;
}
public IWidget Widget { get { return _widget; } }
public override bool Equals(object obj)
{
if (this == obj) return true;
var widgetRule = obj as WidgetRule;
if (widgetRule == null) return false;
return Equals(_widget, widgetRule._widget);
}
public override int GetHashCode()
{
return _widget != null ? _widget.GetHashCode() : 0;
}
}
public class WidgetThing : IWidget
{
#region IWidget Members
public void DoSomething()
{
throw new NotImplementedException();
}
#endregion
}
[Serializable]
public class CloneableWidget : IWidget, ICloneable
{
private readonly string _name;
public CloneableWidget(string name)
{
_name = name;
}
public string Name { get { return _name; } }
#region ICloneable Members
public object Clone()
{
return MemberwiseClone();
}
#endregion
#region IWidget Members
public void DoSomething()
{
throw new NotImplementedException();
}
#endregion
}
public class ARule : Rule
{
}
}
| |
using System;
using System.IO;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
namespace Org.BouncyCastle.Crypto.Tls
{
public class DefaultTlsCipherFactory
: AbstractTlsCipherFactory
{
/// <exception cref="IOException"></exception>
public override TlsCipher CreateCipher(TlsContext context, int encryptionAlgorithm, int macAlgorithm)
{
switch (encryptionAlgorithm)
{
case EncryptionAlgorithm.cls_3DES_EDE_CBC:
return CreateDesEdeCipher(context, macAlgorithm);
case EncryptionAlgorithm.AEAD_CHACHA20_POLY1305:
// NOTE: Ignores macAlgorithm
return CreateChaCha20Poly1305(context);
case EncryptionAlgorithm.AES_128_CBC:
return CreateAESCipher(context, 16, macAlgorithm);
case EncryptionAlgorithm.AES_128_CCM:
// NOTE: Ignores macAlgorithm
return CreateCipher_Aes_Ccm(context, 16, 16);
case EncryptionAlgorithm.AES_128_CCM_8:
// NOTE: Ignores macAlgorithm
return CreateCipher_Aes_Ccm(context, 16, 8);
case EncryptionAlgorithm.AES_256_CCM:
// NOTE: Ignores macAlgorithm
return CreateCipher_Aes_Ccm(context, 32, 16);
case EncryptionAlgorithm.AES_256_CCM_8:
// NOTE: Ignores macAlgorithm
return CreateCipher_Aes_Ccm(context, 32, 8);
case EncryptionAlgorithm.AES_128_GCM:
// NOTE: Ignores macAlgorithm
return CreateCipher_Aes_Gcm(context, 16, 16);
case EncryptionAlgorithm.AES_256_CBC:
return CreateAESCipher(context, 32, macAlgorithm);
case EncryptionAlgorithm.AES_256_GCM:
// NOTE: Ignores macAlgorithm
return CreateCipher_Aes_Gcm(context, 32, 16);
case EncryptionAlgorithm.CAMELLIA_128_CBC:
return CreateCamelliaCipher(context, 16, macAlgorithm);
case EncryptionAlgorithm.CAMELLIA_128_GCM:
// NOTE: Ignores macAlgorithm
return CreateCipher_Camellia_Gcm(context, 16, 16);
case EncryptionAlgorithm.CAMELLIA_256_CBC:
return CreateCamelliaCipher(context, 32, macAlgorithm);
case EncryptionAlgorithm.CAMELLIA_256_GCM:
// NOTE: Ignores macAlgorithm
return CreateCipher_Camellia_Gcm(context, 32, 16);
case EncryptionAlgorithm.ESTREAM_SALSA20:
return CreateSalsa20Cipher(context, 12, 32, macAlgorithm);
case EncryptionAlgorithm.NULL:
return CreateNullCipher(context, macAlgorithm);
case EncryptionAlgorithm.RC4_128:
return CreateRC4Cipher(context, 16, macAlgorithm);
case EncryptionAlgorithm.SALSA20:
return CreateSalsa20Cipher(context, 20, 32, macAlgorithm);
case EncryptionAlgorithm.SEED_CBC:
return CreateSeedCipher(context, macAlgorithm);
default:
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
/// <exception cref="IOException"></exception>
protected virtual TlsBlockCipher CreateAESCipher(TlsContext context, int cipherKeySize, int macAlgorithm)
{
return new TlsBlockCipher(context, CreateAesBlockCipher(), CreateAesBlockCipher(),
CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), cipherKeySize);
}
/// <exception cref="IOException"></exception>
protected virtual TlsBlockCipher CreateCamelliaCipher(TlsContext context, int cipherKeySize, int macAlgorithm)
{
return new TlsBlockCipher(context, CreateCamelliaBlockCipher(),
CreateCamelliaBlockCipher(), CreateHMacDigest(macAlgorithm),
CreateHMacDigest(macAlgorithm), cipherKeySize);
}
/// <exception cref="IOException"></exception>
protected virtual TlsCipher CreateChaCha20Poly1305(TlsContext context)
{
return new Chacha20Poly1305(context);
}
/// <exception cref="IOException"></exception>
protected virtual TlsAeadCipher CreateCipher_Aes_Ccm(TlsContext context, int cipherKeySize, int macSize)
{
return new TlsAeadCipher(context, CreateAeadBlockCipher_Aes_Ccm(),
CreateAeadBlockCipher_Aes_Ccm(), cipherKeySize, macSize);
}
/// <exception cref="IOException"></exception>
protected virtual TlsAeadCipher CreateCipher_Aes_Gcm(TlsContext context, int cipherKeySize, int macSize)
{
return new TlsAeadCipher(context, CreateAeadBlockCipher_Aes_Gcm(),
CreateAeadBlockCipher_Aes_Gcm(), cipherKeySize, macSize);
}
/// <exception cref="IOException"></exception>
protected virtual TlsAeadCipher CreateCipher_Camellia_Gcm(TlsContext context, int cipherKeySize, int macSize)
{
return new TlsAeadCipher(context, CreateAeadBlockCipher_Camellia_Gcm(),
CreateAeadBlockCipher_Camellia_Gcm(), cipherKeySize, macSize);
}
/// <exception cref="IOException"></exception>
protected virtual TlsBlockCipher CreateDesEdeCipher(TlsContext context, int macAlgorithm)
{
return new TlsBlockCipher(context, CreateDesEdeBlockCipher(), CreateDesEdeBlockCipher(),
CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), 24);
}
/// <exception cref="IOException"></exception>
protected virtual TlsNullCipher CreateNullCipher(TlsContext context, int macAlgorithm)
{
return new TlsNullCipher(context, CreateHMacDigest(macAlgorithm),
CreateHMacDigest(macAlgorithm));
}
/// <exception cref="IOException"></exception>
protected virtual TlsStreamCipher CreateRC4Cipher(TlsContext context, int cipherKeySize, int macAlgorithm)
{
return new TlsStreamCipher(context, CreateRC4StreamCipher(), CreateRC4StreamCipher(),
CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), cipherKeySize, false);
}
/// <exception cref="IOException"></exception>
protected virtual TlsStreamCipher CreateSalsa20Cipher(TlsContext context, int rounds, int cipherKeySize, int macAlgorithm)
{
return new TlsStreamCipher(context, CreateSalsa20StreamCipher(rounds), CreateSalsa20StreamCipher(rounds),
CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), cipherKeySize, true);
}
/// <exception cref="IOException"></exception>
protected virtual TlsBlockCipher CreateSeedCipher(TlsContext context, int macAlgorithm)
{
return new TlsBlockCipher(context, CreateSeedBlockCipher(), CreateSeedBlockCipher(),
CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), 16);
}
protected virtual IBlockCipher CreateAesEngine()
{
return new AesEngine();
}
protected virtual IBlockCipher CreateCamelliaEngine()
{
return new CamelliaEngine();
}
protected virtual IBlockCipher CreateAesBlockCipher()
{
return new CbcBlockCipher(CreateAesEngine());
}
protected virtual IAeadBlockCipher CreateAeadBlockCipher_Aes_Ccm()
{
return new CcmBlockCipher(CreateAesEngine());
}
protected virtual IAeadBlockCipher CreateAeadBlockCipher_Aes_Gcm()
{
// TODO Consider allowing custom configuration of multiplier
return new GcmBlockCipher(CreateAesEngine());
}
protected virtual IAeadBlockCipher CreateAeadBlockCipher_Camellia_Gcm()
{
// TODO Consider allowing custom configuration of multiplier
return new GcmBlockCipher(CreateCamelliaEngine());
}
protected virtual IBlockCipher CreateCamelliaBlockCipher()
{
return new CbcBlockCipher(CreateCamelliaEngine());
}
protected virtual IBlockCipher CreateDesEdeBlockCipher()
{
return new CbcBlockCipher(new DesEdeEngine());
}
protected virtual IStreamCipher CreateRC4StreamCipher()
{
return new RC4Engine();
}
protected virtual IStreamCipher CreateSalsa20StreamCipher(int rounds)
{
return new Salsa20Engine(rounds);
}
protected virtual IBlockCipher CreateSeedBlockCipher()
{
return new CbcBlockCipher(new SeedEngine());
}
/// <exception cref="IOException"></exception>
protected virtual IDigest CreateHMacDigest(int macAlgorithm)
{
switch (macAlgorithm)
{
case MacAlgorithm.cls_null:
return null;
case MacAlgorithm.hmac_md5:
return TlsUtilities.CreateHash(HashAlgorithm.md5);
case MacAlgorithm.hmac_sha1:
return TlsUtilities.CreateHash(HashAlgorithm.sha1);
case MacAlgorithm.hmac_sha256:
return TlsUtilities.CreateHash(HashAlgorithm.sha256);
case MacAlgorithm.hmac_sha384:
return TlsUtilities.CreateHash(HashAlgorithm.sha384);
case MacAlgorithm.hmac_sha512:
return TlsUtilities.CreateHash(HashAlgorithm.sha512);
default:
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lambda-2015-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lambda.Model
{
/// <summary>
/// A complex type that describes function metadata.
/// </summary>
public partial class UpdateFunctionConfigurationResponse : AmazonWebServiceResponse
{
private long? _codeSize;
private string _description;
private string _functionArn;
private string _functionName;
private string _handler;
private string _lastModified;
private int? _memorySize;
private string _role;
private Runtime _runtime;
private int? _timeout;
/// <summary>
/// Gets and sets the property CodeSize.
/// <para>
/// The size, in bytes, of the function .zip file you uploaded.
/// </para>
/// </summary>
public long CodeSize
{
get { return this._codeSize.GetValueOrDefault(); }
set { this._codeSize = value; }
}
// Check to see if CodeSize property is set
internal bool IsSetCodeSize()
{
return this._codeSize.HasValue;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The user-provided description.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property FunctionArn.
/// <para>
/// The Amazon Resource Name (ARN) assigned to the function.
/// </para>
/// </summary>
public string FunctionArn
{
get { return this._functionArn; }
set { this._functionArn = value; }
}
// Check to see if FunctionArn property is set
internal bool IsSetFunctionArn()
{
return this._functionArn != null;
}
/// <summary>
/// Gets and sets the property FunctionName.
/// <para>
/// The name of the function.
/// </para>
/// </summary>
public string FunctionName
{
get { return this._functionName; }
set { this._functionName = value; }
}
// Check to see if FunctionName property is set
internal bool IsSetFunctionName()
{
return this._functionName != null;
}
/// <summary>
/// Gets and sets the property Handler.
/// <para>
/// The function Lambda calls to begin executing your function.
/// </para>
/// </summary>
public string Handler
{
get { return this._handler; }
set { this._handler = value; }
}
// Check to see if Handler property is set
internal bool IsSetHandler()
{
return this._handler != null;
}
/// <summary>
/// Gets and sets the property LastModified.
/// <para>
/// The timestamp of the last time you updated the function.
/// </para>
/// </summary>
public string LastModified
{
get { return this._lastModified; }
set { this._lastModified = value; }
}
// Check to see if LastModified property is set
internal bool IsSetLastModified()
{
return this._lastModified != null;
}
/// <summary>
/// Gets and sets the property MemorySize.
/// <para>
/// The memory size, in MB, you configured for the function. Must be a multiple of 64
/// MB.
/// </para>
/// </summary>
public int MemorySize
{
get { return this._memorySize.GetValueOrDefault(); }
set { this._memorySize = value; }
}
// Check to see if MemorySize property is set
internal bool IsSetMemorySize()
{
return this._memorySize.HasValue;
}
/// <summary>
/// Gets and sets the property Role.
/// <para>
/// The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes
/// your function to access any other Amazon Web Services (AWS) resources.
/// </para>
/// </summary>
public string Role
{
get { return this._role; }
set { this._role = value; }
}
// Check to see if Role property is set
internal bool IsSetRole()
{
return this._role != null;
}
/// <summary>
/// Gets and sets the property Runtime.
/// <para>
/// The runtime environment for the Lambda function.
/// </para>
/// </summary>
public Runtime Runtime
{
get { return this._runtime; }
set { this._runtime = value; }
}
// Check to see if Runtime property is set
internal bool IsSetRuntime()
{
return this._runtime != null;
}
/// <summary>
/// Gets and sets the property Timeout.
/// <para>
/// The function execution time at which Lambda should terminate the function. Because
/// the execution time has cost implications, we recommend you set this value based on
/// your expected execution time. The default is 3 seconds.
/// </para>
/// </summary>
public int Timeout
{
get { return this._timeout.GetValueOrDefault(); }
set { this._timeout = value; }
}
// Check to see if Timeout property is set
internal bool IsSetTimeout()
{
return this._timeout.HasValue;
}
}
}
| |
// Copyright (c) The Mapsui authors.
// The Mapsui authors licensed this file under the MIT license.
// See the LICENSE file in the project root for full license information.
// This file was originally created by Morten Nielsen (www.iter.dk) as part of SharpMap
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Mapsui.Fetcher;
using Mapsui.Layers;
using Mapsui.Styles;
using Mapsui.UI;
using Mapsui.Widgets;
namespace Mapsui
{
/// <summary>
/// Map class
/// </summary>
/// <remarks>
/// Map holds all map related infos like the target CRS, layers, widgets and so on.
/// </remarks>
public class Map : INotifyPropertyChanged, IMap, IDisposable
{
private LayerCollection _layers = new();
private Color _backColor = Color.White;
private IViewportLimiter _limiter = new ViewportLimiter();
/// <summary>
/// Initializes a new map
/// </summary>
public Map()
{
BackColor = Color.White;
Layers = new LayerCollection();
}
/// <summary>
/// To register if the initial Home call has been done.
/// </summary>
public bool Initialized { get; set; }
/// <summary>
/// When true the user can not pan (move) the map.
/// </summary>
public bool PanLock { get; set; }
/// <summary>
/// When true the user an not rotate the map
/// </summary>
public bool ZoomLock { get; set; }
/// <summary>
/// When true the user can not zoom into the map
/// </summary>
public bool RotationLock { get; set; }
/// <summary>
/// List of Widgets belonging to map
/// </summary>
public ConcurrentQueue<IWidget> Widgets { get; } = new();
/// <summary>
/// Limit the extent to which the user can navigate
/// </summary>
public IViewportLimiter Limiter
{
get => _limiter;
set
{
if (!_limiter.Equals(value))
{
_limiter = value;
OnPropertyChanged(nameof(Limiter));
}
}
}
/// <summary>
/// Projection type of Map. Normally in format like "EPSG:3857"
/// </summary>
public string? CRS { get; set; }
/// <summary>
/// A collection of layers. The first layer in the list is drawn first, the last one on top.
/// </summary>
public LayerCollection Layers
{
get => _layers;
private set
{
var tempLayers = _layers;
if (tempLayers != null)
_layers.Changed -= LayersCollectionChanged;
_layers = value;
_layers.Changed += LayersCollectionChanged;
}
}
[Obsolete("Use ILayer.IsMapInfoLayer instead", true)]
public IList<ILayer> InfoLayers { get; } = new List<ILayer>();
[Obsolete("Use your own hover event and call MapControl.GetMapInfo", true)]
public IList<ILayer> HoverLayers { get; } = new List<ILayer>();
/// <summary>
/// Map background color (defaults to transparent)
/// </summary>
public Color BackColor
{
get => _backColor;
set
{
if (_backColor == value) return;
_backColor = value;
OnPropertyChanged(nameof(BackColor));
}
}
/// <summary>
/// Gets the extent of the map based on the extent of all the layers in the layers collection
/// </summary>
/// <returns>Full map extent</returns>
public MRect? Extent
{
get
{
if (_layers.Count == 0) return null;
MRect? extent = null;
foreach (var layer in _layers)
{
extent = extent == null ? layer.Extent : extent.Join(layer.Extent);
}
return extent;
}
}
/// <summary>
/// List of all native resolutions of this map
/// </summary>
public IReadOnlyList<double> Resolutions { get; private set; } = new List<double>();
/// <summary>
/// Called whenever a property changed
/// </summary>
public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>
/// DataChanged should be triggered by any data changes of any of the child layers
/// </summary>
public event DataChangedEventHandler? DataChanged;
#pragma warning disable 67
[Obsolete("Use PropertyChanged instead", true)]
public event EventHandler? RefreshGraphics;
#pragma warning restore 67
/// <summary>
/// Called whenever the map is clicked. The MapInfoEventArgs contain the features that were hit in
/// the layers that have IsMapInfoLayer set to true.
/// </summary>
public event EventHandler<MapInfoEventArgs>? Info;
[Obsolete("Use your own hover event instead and call MapControl.GetMapInfo", true)]
#pragma warning disable 67
public event EventHandler<MapInfoEventArgs>? Hover;
#pragma warning restore 67
/// <summary>
/// Abort fetching of all layers
/// </summary>
public void AbortFetch()
{
foreach (var layer in _layers.ToList())
{
if (layer is IAsyncDataFetcher asyncLayer) asyncLayer.AbortFetch();
}
}
/// <summary>
/// Clear cache of all layers
/// </summary>
public void ClearCache()
{
foreach (var layer in _layers)
{
if (layer is IAsyncDataFetcher asyncLayer) asyncLayer.ClearCache();
}
}
public void RefreshData(FetchInfo fetchInfo)
{
foreach (var layer in _layers.ToList())
{
layer.RefreshData(fetchInfo);
}
}
private void LayersCollectionChanged(object sender, LayerCollectionChangedEventArgs args)
{
foreach (var layer in args.RemovedLayers ?? Enumerable.Empty<ILayer>())
LayerRemoved(layer);
foreach (var layer in args.AddedLayers ?? Enumerable.Empty<ILayer>())
LayerAdded(layer);
LayersChanged();
}
private void LayerAdded(ILayer layer)
{
layer.DataChanged += LayerDataChanged;
layer.PropertyChanged += LayerPropertyChanged;
}
private void LayerRemoved(ILayer layer)
{
if (layer is IAsyncDataFetcher asyncLayer)
asyncLayer.AbortFetch();
layer.DataChanged -= LayerDataChanged;
layer.PropertyChanged -= LayerPropertyChanged;
}
private void LayersChanged()
{
Resolutions = DetermineResolutions(Layers);
OnPropertyChanged(nameof(Layers));
}
private static IReadOnlyList<double> DetermineResolutions(IEnumerable<ILayer> layers)
{
var items = new Dictionary<double, double>();
const float normalizedDistanceThreshold = 0.75f;
foreach (var layer in layers)
{
if (!layer.Enabled || layer.Resolutions == null) continue;
foreach (var resolution in layer.Resolutions)
{
// About normalization:
// Resolutions don't have equal distances because they
// are multiplied by two at every step. Distances on the
// lower zoom levels have very different meaning than on the
// higher zoom levels. So we work with a normalized resolution
// to determine if another resolution adds value. If a resolution
// is a factor of 2 of another resolution. The normalized distance
// is one.
var normalized = Math.Log(resolution, 2);
if (items.Count == 0)
{
items[normalized] = resolution;
}
else
{
var normalizedDistance = items.Keys.Min(k => Math.Abs(k - normalized));
if (normalizedDistance > normalizedDistanceThreshold) items[normalized] = resolution;
}
}
}
return items.Select(i => i.Value).OrderByDescending(i => i).ToList();
}
private void LayerPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnPropertyChanged(sender, e.PropertyName);
}
private void OnPropertyChanged(object sender, string propertyName)
{
PropertyChanged?.Invoke(sender, new PropertyChangedEventArgs(propertyName));
}
private void OnPropertyChanged(string name)
{
OnPropertyChanged(this, name);
}
private void LayerDataChanged(object sender, DataChangedEventArgs e)
{
OnDataChanged(sender, e);
}
private void OnDataChanged(object sender, DataChangedEventArgs e)
{
DataChanged?.Invoke(sender, e);
}
public Action<INavigator> Home { get; set; } = n => n.NavigateToFullEnvelope();
public IEnumerable<IWidget> GetWidgetsOfMapAndLayers()
{
return Widgets.Concat(Layers.Where(l => l.Enabled).Select(l => l.Attribution))
.Where(a => a != null && a.Enabled).ToList();
}
/// <summary>
/// This method is to invoke the Info event from the Map. This method is called
/// by the MapControl/MapView and should usually not be called from user code.
/// </summary>
public void OnInfo(MapInfoEventArgs? mapInfoEventArgs)
{
if (mapInfoEventArgs == null) return;
Info?.Invoke(this, mapInfoEventArgs);
}
public virtual void Dispose()
{
foreach (var layer in Layers)
{
// remove Event so that no memory leaks occour
LayerRemoved(layer);
}
// clear the layers
Layers.Clear();
}
public bool UpdateAnimations()
{
var areAnimationsRunning = false;
foreach (var layer in Layers)
{
if (layer.UpdateAnimations())
areAnimationsRunning = true;
}
return areAnimationsRunning;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.Remoting.Messaging;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Table;
using MvcWebRole.Models;
using SendGridMail;
using WorkerRoleB.Telemetry;
namespace WorkerRoleB
{
public class WorkerRoleB : RoleEntryPoint
{
private CloudQueue sendEmailQueue;
private CloudQueue subscribeQueue;
private CloudBlobContainer blobContainer;
private CloudTable mailingListTable;
private CloudTable messageTable;
private CloudTable messagearchiveTable;
private volatile bool onStopCalled = false;
private volatile bool returnedFromRunMethod = false;
private TelemetryClient aiClient = new TelemetryClient();
private static string CORRELATION_SLOT = "CORRELATION-ID";
public override void Run()
{
CloudQueueMessage msg = null;
Trace.TraceInformation("WorkerRoleB start of Run()");
while (true)
{
try
{
var loopStart = DateTimeOffset.UtcNow;
bool messageFound = false;
// If OnStop has been called, return to do a graceful shutdown.
if (onStopCalled == true)
{
Trace.TraceInformation("onStopCalled WorkerRoleB");
returnedFromRunMethod = true;
return;
}
// Retrieve and process a new message from the send-email-to-list queue.
msg = sendEmailQueue.GetMessage();
if (msg != null)
{
ProcessQueueMessage(msg);
messageFound = true;
}
// Retrieve and process a new message from the subscribe queue.
msg = subscribeQueue.GetMessage();
if (msg != null)
{
ProcessSubscribeQueueMessage(msg);
messageFound = true;
}
if (messageFound == false)
{
System.Threading.Thread.Sleep(1000 * 30);
}
else
{
aiClient.TrackMetric("LoopWithMessagesTimeMs", ((TimeSpan)(DateTimeOffset.Now - loopStart)).Milliseconds);
}
}
catch (Exception ex)
{
string err = ex.Message;
if (ex.InnerException != null)
{
err += " Inner Exception: " + ex.InnerException.Message;
}
if (msg != null)
{
err += " Last queue message retrieved: " + msg.AsString;
}
Trace.TraceError(err, ex);
}
}
}
private int GetRoleInstance()
{
string instanceId = RoleEnvironment.CurrentRoleInstance.Id;
int instanceIndex = -3;
int.TryParse(instanceId.Substring(instanceId.LastIndexOf("_") + 1), out instanceIndex);
// The instanceIndex of the first instance is 0.
return instanceIndex;
}
private void ProcessQueueMessage(CloudQueueMessage msg)
{
Stopwatch requestTimer = Stopwatch.StartNew();
var request = RequestTelemetryHelper.StartNewRequest("ProcessEmailQueueMessage", DateTimeOffset.UtcNow);
CallContext.LogicalSetData(CORRELATION_SLOT, request.Id);
//Thread.SetData(Thread.GetNamedDataSlot(CORRELATION_SLOT), request.Id);
try
{
// Log and delete if this is a "poison" queue message (repeatedly processed
// and always causes an error that prevents processing from completing).
// Production applications should move the "poison" message to a "dead message"
// queue for analysis rather than deleting the message.
if (msg.DequeueCount > 5)
{
Trace.TraceError("Deleting poison message: message {0} Role Instance {1}.",
msg.ToString(), GetRoleInstance());
sendEmailQueue.DeleteMessage(msg);
request.Properties.Add(new KeyValuePair<string,string>("FailureCode","PoisonMessage"));
request.Properties.Add(new KeyValuePair<string, string>("DequeueCount", msg.DequeueCount.ToString()));
if (msg.InsertionTime != null)
{
request.Metrics.Add(new KeyValuePair<string, double>("EmailProcessingTimeMs", ((TimeSpan)(DateTimeOffset.Now - msg.InsertionTime)).Milliseconds));
}
RequestTelemetryHelper.DispatchRequest(request, requestTimer.Elapsed, false);
return;
}
// Parse message retrieved from queue.
// Example: 2012-01-01,0123456789email@domain.com,0
var messageParts = msg.AsString.Split(new char[] { ',' });
var partitionKey = messageParts[0];
var rowKey = messageParts[1];
var restartFlag = messageParts[2];
Trace.TraceInformation("ProcessQueueMessage start: partitionKey {0} rowKey {1} Role Instance {2}.", partitionKey, rowKey, GetRoleInstance());
// If this is a restart, verify that the email hasn't already been sent.
if (restartFlag == "1")
{
var retrieveOperationForRestart = TableOperation.Retrieve<SendEmail>(partitionKey, rowKey);
var retrievedResultForRestart = messagearchiveTable.Execute(retrieveOperationForRestart);
var messagearchiveRow = retrievedResultForRestart.Result as SendEmail;
if (messagearchiveRow != null)
{
// SendEmail row is in archive, so email is already sent.
// If there's a SendEmail Row in message table, delete it,
// and delete the queue message.
Trace.TraceInformation("Email already sent: partitionKey=" + partitionKey + " rowKey= " + rowKey);
var deleteOperation = TableOperation.Delete(new SendEmail { PartitionKey = partitionKey, RowKey = rowKey, ETag = "*" });
try
{
messageTable.Execute(deleteOperation);
}
catch(Exception ex)
{
aiClient.TrackException(ex);
}
sendEmailQueue.DeleteMessage(msg);
request.Properties.Add(new KeyValuePair<string, string>("SuccessCode", "NoOp-MessageAlreadySent"));
if (msg.InsertionTime != null)
{
request.Metrics.Add(new KeyValuePair<string, double>("EmailProcessingTimeMs", ((TimeSpan)(DateTimeOffset.Now - msg.InsertionTime)).Milliseconds));
}
RequestTelemetryHelper.DispatchRequest(request, requestTimer.Elapsed, true);
return;
}
}
// Get the row in the Message table that has data we need to send the email.
var retrieveOperation = TableOperation.Retrieve<SendEmail>(partitionKey, rowKey);
var retrievedResult = messageTable.Execute(retrieveOperation);
var emailRowInMessageTable = retrievedResult.Result as SendEmail;
if (emailRowInMessageTable == null)
{
Trace.TraceError("SendEmail row not found: partitionKey {0} rowKey {1} Role Instance {2}.",partitionKey, rowKey, GetRoleInstance());
request.Properties.Add(new KeyValuePair<string, string>("FailureCode", "SendEmailRowNotFound"));
if (msg.InsertionTime != null)
{
request.Metrics.Add(new KeyValuePair<string, double>("EmailProcessingTimeMs", ((TimeSpan)(DateTimeOffset.Now - msg.InsertionTime)).Milliseconds));
}
RequestTelemetryHelper.DispatchRequest(request, requestTimer.Elapsed, false);
return;
}
// Derive blob names from the MessageRef.
var htmlMessageBodyRef = emailRowInMessageTable.MessageRef + ".htm";
var textMessageBodyRef = emailRowInMessageTable.MessageRef + ".txt";
// If the email hasn't already been sent, send email and archive the table row.
if (emailRowInMessageTable.EmailSent != true)
{
SendEmailToList(emailRowInMessageTable, htmlMessageBodyRef, textMessageBodyRef);
var emailRowToDelete = new SendEmail { PartitionKey = partitionKey, RowKey = rowKey, ETag = "*" };
emailRowInMessageTable.EmailSent = true;
var upsertOperation = TableOperation.InsertOrReplace(emailRowInMessageTable);
messagearchiveTable.Execute(upsertOperation);
var deleteOperation = TableOperation.Delete(emailRowToDelete);
messageTable.Execute(deleteOperation);
}
// Delete the queue message.
sendEmailQueue.DeleteMessage(msg);
Trace.TraceInformation("ProcessQueueMessage complete: partitionKey {0} rowKey {1} Role Instance {2}.", partitionKey, rowKey, GetRoleInstance());
request.Properties.Add(new KeyValuePair<string, string>("SuccessCode", "EmailSent"));
if (msg.InsertionTime != null)
{
request.Metrics.Add(new KeyValuePair<string, double>("EmailProcessingTimeMs", ((TimeSpan)(DateTimeOffset.Now - msg.InsertionTime)).Milliseconds));
}
RequestTelemetryHelper.DispatchRequest(request, requestTimer.Elapsed, true);
}
catch (Exception ex)
{
request.Properties.Add(new KeyValuePair<string, string>("FailureCode", "Exception"));
if (msg.InsertionTime != null)
{
request.Metrics.Add(new KeyValuePair<string, double>("FailedEmailProcessingTimeMs", ((TimeSpan)(DateTimeOffset.Now - msg.InsertionTime)).Milliseconds));
}
RequestTelemetryHelper.DispatchRequest(request, requestTimer.Elapsed, false);
throw ex;
}
}
private void SendEmailToList(SendEmail emailRowInMessageTable, string htmlMessageBodyRef, string textMessageBodyRef)
{
var email = SendGrid.GetInstance();
email.From = new MailAddress(emailRowInMessageTable.FromEmailAddress);
email.AddTo(emailRowInMessageTable.EmailAddress);
email.Html = GetBlobText(htmlMessageBodyRef) + GetHTMLUnsubscribeLink(emailRowInMessageTable);
email.Text = GetBlobText(textMessageBodyRef) + GetPlainTextUnsubscribeLink(emailRowInMessageTable);
email.Subject = emailRowInMessageTable.SubjectLine;
var credentials = new NetworkCredential(RoleEnvironment.GetConfigurationSettingValue("SendGridUserName"),
RoleEnvironment.GetConfigurationSettingValue("SendGridPassword"));
var transportREST = Web.GetInstance(credentials);
transportREST.Deliver(email);
}
private string GetBlobText(string blogRef)
{
var blob = blobContainer.GetBlockBlobReference(blogRef);
blob.FetchAttributes();
var blobSize = blob.Properties.Length;
using (var memoryStream = new MemoryStream((int)blobSize))
{
blob.DownloadToStream(memoryStream);
return System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
private string GetHTMLUnsubscribeLink(SendEmail emailRowInMessageTable)
{
return String.Format("<p>Click the following link to unsubscribe. <a href=\"{0}/unsubscribe?id={1}&listName={2}\">Unsubscribe</a></p>",
RoleEnvironment.GetConfigurationSettingValue("AzureMailServiceURL"),
emailRowInMessageTable.SubscriberGUID,
emailRowInMessageTable.ListName);
}
private string GetPlainTextUnsubscribeLink(SendEmail emailRowInMessageTable)
{
return String.Format("\nCopy the following URL into your browser unsubscribe.\n{0}/unsubscribe?id={1}&listName={2}",
RoleEnvironment.GetConfigurationSettingValue("AzureMailServiceURL"),
emailRowInMessageTable.SubscriberGUID,
emailRowInMessageTable.ListName);
}
private void ProcessSubscribeQueueMessage(CloudQueueMessage msg)
{
Stopwatch requestTimer = Stopwatch.StartNew();
var request = RequestTelemetryHelper.StartNewRequest("ProcessSubscribeQueueMessage", DateTimeOffset.UtcNow);
CallContext.LogicalSetData(CORRELATION_SLOT, request.Id);
//Thread.SetData(Thread.GetNamedDataSlot(CORRELATION_SLOT), request.Id);
try
{
// Log and delete if this is a "poison" queue message (repeatedly processed
// and always causes an error that prevents processing from completing).
// Production applications should move the "poison" message to a "dead message"
// queue for analysis rather than deleting the message.
if (msg.DequeueCount > 5)
{
Trace.TraceError("Deleting poison subscribe message: message {0}.",
msg.AsString, GetRoleInstance());
subscribeQueue.DeleteMessage(msg);
request.Properties.Add(new KeyValuePair<string, string>("FailureCode", "PoisonMessage"));
request.Properties.Add(new KeyValuePair<string, string>("DequeueCount", msg.DequeueCount.ToString()));
if (msg.InsertionTime != null)
{
request.Metrics.Add(new KeyValuePair<string, double>("SubscribeProcessingTimeMs", ((TimeSpan)(DateTimeOffset.Now - msg.InsertionTime)).Milliseconds));
}
RequestTelemetryHelper.DispatchRequest(request, requestTimer.Elapsed, false);
return;
}
// Parse message retrieved from queue. Message consists of
// subscriber GUID and list name.
// Example: 57ab4c4b-d564-40e3-9a3f-81835b3e102e,contoso1
var messageParts = msg.AsString.Split(new char[] { ',' });
var subscriberGUID = messageParts[0];
var listName = messageParts[1];
Trace.TraceInformation("ProcessSubscribeQueueMessage start: subscriber GUID {0} listName {1} Role Instance {2}.",
subscriberGUID, listName, GetRoleInstance());
// Get subscriber info.
string filter = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, listName),
TableOperators.And,
TableQuery.GenerateFilterCondition("SubscriberGUID", QueryComparisons.Equal, subscriberGUID));
var query = new TableQuery<Subscriber>().Where(filter);
var subscriber = mailingListTable.ExecuteQuery(query).ToList().Single();
// Get mailing list info.
var retrieveOperation = TableOperation.Retrieve<MailingList>(subscriber.ListName, "mailinglist");
var retrievedResult = mailingListTable.Execute(retrieveOperation);
var mailingList = retrievedResult.Result as MailingList;
SendSubscribeEmail(subscriberGUID, subscriber, mailingList);
subscribeQueue.DeleteMessage(msg);
Trace.TraceInformation("ProcessSubscribeQueueMessage complete: subscriber GUID {0} Role Instance {1}.", subscriberGUID, GetRoleInstance());
if (msg.InsertionTime != null)
{
request.Metrics.Add(new KeyValuePair<string, double>("SubscribeProcessingTimeMs", ((TimeSpan)(DateTimeOffset.Now - msg.InsertionTime)).Milliseconds));
}
RequestTelemetryHelper.DispatchRequest(request, requestTimer.Elapsed, true);
}
catch (Exception ex)
{
request.Properties.Add(new KeyValuePair<string, string>("FailureCode", "Exception"));
if (msg.InsertionTime != null)
{
request.Metrics.Add(new KeyValuePair<string, double>("FailedSubscribeProcessingTimeMs", ((TimeSpan)(DateTimeOffset.Now - msg.InsertionTime)).Milliseconds));
}
RequestTelemetryHelper.DispatchRequest(request, requestTimer.Elapsed, false);
throw ex;
}
}
private static void SendSubscribeEmail(string subscriberGUID, Subscriber subscriber, MailingList mailingList)
{
var email = SendGrid.GetInstance();
email.From = new MailAddress(mailingList.FromEmailAddress);
email.AddTo(subscriber.EmailAddress);
string subscribeURL = RoleEnvironment.GetConfigurationSettingValue("AzureMailServiceURL") +
"/subscribe?id=" + subscriberGUID + "&listName=" + subscriber.ListName;
email.Html = String.Format("<p>Click the link below to subscribe to {0}. " +
"If you don't confirm your subscription, you won't be subscribed to the list.</p>" +
"<a href=\"{1}\">Confirm Subscription</a>", mailingList.Description, subscribeURL);
email.Text = String.Format("Copy and paste the following URL into your browser in order to subscribe to {0}. " +
"If you don't confirm your subscription, you won't be subscribed to the list.\n" +
"{1}", mailingList.Description, subscribeURL);
email.Subject = "Subscribe to " + mailingList.Description;
var credentials = new NetworkCredential(RoleEnvironment.GetConfigurationSettingValue("SendGridUserName"), RoleEnvironment.GetConfigurationSettingValue("SendGridPassword"));
var transportREST = Web.GetInstance(credentials);
transportREST.Deliver(email);
}
public override void OnStop()
{
onStopCalled = true;
while (returnedFromRunMethod == false)
{
System.Threading.Thread.Sleep(1000);
}
}
public override bool OnStart()
{
TelemetryConfiguration.Active.InstrumentationKey = RoleEnvironment.GetConfigurationSettingValue("Telemetry.AI.InstrumentationKey");
TelemetryConfiguration.Active.TelemetryInitializers.Add(new ItemCorrelationTelemetryInitializer());
ServicePointManager.DefaultConnectionLimit = Environment.ProcessorCount * 12;
Trace.TraceInformation("Initializing storage account in worker role B");
var storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
// Initialize queue storage
Trace.TraceInformation("Creating queue client.");
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
sendEmailQueue = queueClient.GetQueueReference("azuremailqueue");
subscribeQueue = queueClient.GetQueueReference("azuremailsubscribequeue");
// Initialize blob storage
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
blobContainer = blobClient.GetContainerReference("azuremailblobcontainer");
// Initialize table storage
var tableClient = storageAccount.CreateCloudTableClient();
mailingListTable = tableClient.GetTableReference("mailinglist");
messageTable = tableClient.GetTableReference("message");
messagearchiveTable = tableClient.GetTableReference("messagearchive");
Trace.TraceInformation("WorkerB: Creating blob container, queue, tables, if they don't exist.");
blobContainer.CreateIfNotExists();
sendEmailQueue.CreateIfNotExists();
subscribeQueue.CreateIfNotExists();
this.messageTable.CreateIfNotExists();
this.mailingListTable.CreateIfNotExists();
this.messagearchiveTable.CreateIfNotExists();
return base.OnStart();
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace OAuthAddinDemoWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an add-in event
/// </summary>
/// <param name="properties">Properties of an add-in event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted add-in. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust add-in.
/// </summary>
/// <returns>True if this is a high trust add-in.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted add-in configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Copyright (c) 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.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
public abstract class AbstractCodeType : AbstractCodeMember, EnvDTE.CodeType
{
internal AbstractCodeType(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
: base(state, fileCodeModel, nodeKey, nodeKind)
{
}
internal AbstractCodeType(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
: base(state, fileCodeModel, nodeKind, name)
{
}
private SyntaxNode GetNamespaceOrTypeNode()
{
return LookupNode().Ancestors()
.Where(n => CodeModelService.IsNamespace(n) || CodeModelService.IsType(n))
.FirstOrDefault();
}
private SyntaxNode GetNamespaceNode()
{
return LookupNode().Ancestors()
.Where(n => CodeModelService.IsNamespace(n))
.FirstOrDefault();
}
internal INamedTypeSymbol LookupTypeSymbol()
{
return (INamedTypeSymbol)LookupSymbol();
}
protected override object GetExtenderNames()
{
return CodeModelService.GetTypeExtenderNames();
}
protected override object GetExtender(string name)
{
return CodeModelService.GetTypeExtender(name, this);
}
public override object Parent
{
get
{
var containingNamespaceOrType = GetNamespaceOrTypeNode();
return containingNamespaceOrType != null
? (object)FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingNamespaceOrType)
: this.FileCodeModel;
}
}
public override EnvDTE.CodeElements Children
{
get
{
return UnionCollection.Create(this.State, this,
(ICodeElements)this.Attributes,
(ICodeElements)InheritsImplementsCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey),
(ICodeElements)this.Members);
}
}
public EnvDTE.CodeElements Bases
{
get
{
return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: false);
}
}
public EnvDTE80.vsCMDataTypeKind DataTypeKind
{
get
{
return CodeModelService.GetDataTypeKind(LookupNode(), (INamedTypeSymbol)LookupSymbol());
}
set
{
UpdateNode(FileCodeModel.UpdateDataTypeKind, value);
}
}
public EnvDTE.CodeElements DerivedTypes
{
get { throw new NotImplementedException(); }
}
public EnvDTE.CodeElements ImplementedInterfaces
{
get
{
return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: true);
}
}
public EnvDTE.CodeElements Members
{
get
{
return TypeCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey);
}
}
public EnvDTE.CodeNamespace Namespace
{
get
{
var namespaceNode = GetNamespaceNode();
return namespaceNode != null
? FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeNamespace>(namespaceNode)
: null;
}
}
/// <returns>True if the current type inherits from or equals the type described by the
/// given full name.</returns>
/// <remarks>Equality is included in the check as per Dev10 Bug #725630</remarks>
public bool get_IsDerivedFrom(string fullName)
{
var currentType = LookupTypeSymbol();
if (currentType == null)
{
return false;
}
var baseType = GetSemanticModel().Compilation.GetTypeByMetadataName(fullName);
if (baseType == null)
{
return false;
}
return currentType.InheritsFromOrEquals(baseType);
}
public override bool IsCodeType
{
get { return true; }
}
public void RemoveMember(object element)
{
// Is this an EnvDTE.CodeElement that we created? If so, try to get the underlying code element object.
var abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element);
if (abstractCodeElement == null)
{
var codeElement = element as EnvDTE.CodeElement;
if (codeElement != null)
{
// Is at least an EnvDTE.CodeElement? If so, try to retrieve it from the Members collection by name.
// Note: This might throw an ArgumentException if the name isn't found in the collection.
abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(codeElement.Name));
}
else if (element is string || element is int)
{
// Is this a string or int? If so, try to retrieve it from the Members collection. Again, this will
// throw an ArgumentException if the name or index isn't found in the collection.
abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(element));
}
}
if (abstractCodeElement == null)
{
throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element));
}
abstractCodeElement.Delete();
}
public EnvDTE.CodeElement AddBase(object @base, object position)
{
return FileCodeModel.EnsureEditor(() =>
{
FileCodeModel.AddBase(LookupNode(), @base, position);
var codeElements = this.Bases as ICodeElements;
var hr = codeElements.Item(1, out var element);
if (ErrorHandler.Succeeded(hr))
{
return element;
}
return null;
});
}
public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position)
{
return FileCodeModel.EnsureEditor(() =>
{
var name = FileCodeModel.AddImplementedInterface(LookupNode(), @base, position);
var codeElements = this.ImplementedInterfaces as ICodeElements;
var hr = codeElements.Item(name, out var element);
if (ErrorHandler.Succeeded(hr))
{
return element as EnvDTE.CodeInterface;
}
return null;
});
}
public void RemoveBase(object element)
{
FileCodeModel.EnsureEditor(() =>
{
FileCodeModel.RemoveBase(LookupNode(), element);
});
}
public void RemoveInterface(object element)
{
FileCodeModel.EnsureEditor(() =>
{
FileCodeModel.RemoveImplementedInterface(LookupNode(), element);
});
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: CompositionAdorner.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Composition adorner to render the composition display attribute.
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents
{
using System.Collections; // ArrayList
using System.Diagnostics;
using System.Windows.Media; // Brush, Transform
using System.Windows.Controls; // TextBox
using System.Windows.Controls.Primitives; // TextBoxBase
using System.Windows.Input; // InputLanguageManager
using System.Windows.Threading; // Dispatcher
using MS.Win32; // TextServices
using MS.Internal; // Invariant
internal class CompositionAdorner : Adorner
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
static CompositionAdorner()
{
// Provide a new default value for the composition adorner so that it is not hit-testable.
IsEnabledProperty.OverrideMetadata(typeof(CompositionAdorner), new FrameworkPropertyMetadata(false));
}
/// <summary>
/// Creates new instance of CompositionAdorner.
/// </summary>
/// <param name="textView">
/// TextView to which this CompositionAdorner is attached as adorner.
/// </param>
internal CompositionAdorner(ITextView textView) : this(textView, new ArrayList())
{
}
/// <summary>
/// Creates new instance of CompositionAdorner.
/// </summary>
/// <param name="textView">
/// TextView to which this CompositionAdorner is attached as adorner.
/// </param>
/// <param name="attributeRanges">
/// Attribute ranges
/// </param>
internal CompositionAdorner(ITextView textView, ArrayList attributeRanges)
: base(textView.RenderScope)
{
Debug.Assert(textView != null && textView.RenderScope != null);
// TextView to which this CompositionAdorner is attached as adorner and it will
// als be used for GetRectangleFromTextPosition/GetLineRange
_textView = textView;
// Create ArrayList for the composition attribute ranges and composition lines
_attributeRanges = attributeRanges;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Add a transform so that the composition adorner gets positioned at the correct spot within the text being edited
/// </summary>
/// <param name="transform">
/// The transform applied to the object the adorner adorns
/// </param>
/// <returns>
/// Transform to apply to the adorner
/// </returns>
public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
{
TranslateTransform translation;
GeneralTransformGroup group = new GeneralTransformGroup();
// Get the matrix transform out, skip all non affine transforms
Transform t = transform.AffineTransform;
if (t == null)
{
t = Transform.Identity;
}
// Translate the adorner to (0, 0) point
translation = new TranslateTransform(-(t.Value.OffsetX), -(t.Value.OffsetY));
group.Children.Add(translation);
if (transform != null)
{
group.Children.Add(transform);
}
return group;
}
#endregion Public Methods
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Render override to render the composition adorner here.
/// </summary>
protected override void OnRender(DrawingContext drawingContext)
{
// Get the matrix from AdornedElement to the visual parent to get the transformed
// start/end point
Visual parent2d = VisualTreeHelper.GetParent(this.AdornedElement) as Visual;
if (parent2d == null)
{
return;
}
GeneralTransform transform = AdornedElement.TransformToAncestor(parent2d);
if (transform == null)
{
return;
}
// Please note that we do the highlight adornment for the CONVERTED text only
// for Simplified Chinese IMEs. Doing this uniformly across all IMEs wasnt possible
// because it was noted that some of them (viz. Japanese) werent being consistent
// about this attribute.
bool isChinesePinyin = chinesePinyin.Equals(InputLanguageManager.Current.CurrentInputLanguage.IetfLanguageTag);
// Render the each of the composition string attribute from the attribute ranges.
for (int i = 0; i < _attributeRanges.Count; i++)
{
DoubleCollection dashArray;
// Get the composition attribute range from the attribute range lists
AttributeRange attributeRange = (AttributeRange)_attributeRanges[i];
// Skip the rendering composition lines if the composition line doesn't exist.
if (attributeRange.CompositionLines.Count == 0)
{
continue;
}
// Set the line bold and squiggle
bool lineBold = attributeRange.TextServicesDisplayAttribute.IsBoldLine ? true : false;
bool squiggle = false;
bool hasVirtualSelection = (attributeRange.TextServicesDisplayAttribute.AttrInfo & UnsafeNativeMethods.TF_DA_ATTR_INFO.TF_ATTR_TARGET_CONVERTED) != 0;
Brush selectionBrush = null;
double selectionOpacity = -1;
Pen selectionPen = null;
if (isChinesePinyin && hasVirtualSelection)
{
DependencyObject owner = _textView.TextContainer.Parent;
selectionBrush = (Brush)owner.GetValue(TextBoxBase.SelectionBrushProperty);
selectionOpacity = (double)owner.GetValue(TextBoxBase.SelectionOpacityProperty);
}
// Set the line height and cluse gap value that base on the ratio of text height
double height = attributeRange.Height;
double lineHeight = height * (lineBold ? BoldLineHeightRatio : NormalLineHeightRatio);
double clauseGap = height * ClauseGapRatio;
// Create Pen for drawing the composition lines with the specified line color
Pen pen = new Pen(new SolidColorBrush(Colors.Black), lineHeight);
// Set the pen style that based on IME's composition line style
switch (attributeRange.TextServicesDisplayAttribute.LineStyle)
{
case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_DOT:
// Add the dot length and specify the start/end line cap as the round
dashArray = new DoubleCollection();
dashArray.Add(DotLength);
dashArray.Add(DotLength);
pen.DashStyle = new DashStyle(dashArray, 0);
pen.DashCap = System.Windows.Media.PenLineCap.Round;
pen.StartLineCap = System.Windows.Media.PenLineCap.Round;
pen.EndLineCap = System.Windows.Media.PenLineCap.Round;
// Update the line height for the dot line. Dot line will be more thickness than
// other line to show it clearly.
lineHeight = height * (lineBold ? BoldDotLineHeightRatio : NormalDotLineHeightRatio);
break;
case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_DASH:
double dashLength = height * (lineBold ? BoldDashRatio : NormalDashRatio);
double dashGapLength = height * (lineBold ? BoldDashGapRatio : NormalDashGapRatio);
// Add the dash and dash gap legth
dashArray = new DoubleCollection();
dashArray.Add(dashLength);
dashArray.Add(dashGapLength);
pen.DashStyle = new DashStyle(dashArray, 0);
pen.DashCap = System.Windows.Media.PenLineCap.Round;
pen.StartLineCap = System.Windows.Media.PenLineCap.Round;
pen.EndLineCap = System.Windows.Media.PenLineCap.Round;
break;
case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_SOLID:
pen.StartLineCap = System.Windows.Media.PenLineCap.Round;
pen.EndLineCap = System.Windows.Media.PenLineCap.Round;
break;
case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_SQUIGGLE:
squiggle = true;
break;
}
double halfLineHeight = lineHeight / 2;
// Draw the each of the composition line
for (int j = 0; j < attributeRange.CompositionLines.Count; j++)
{
CompositionLine compositionLine = (CompositionLine)attributeRange.CompositionLines[j];
// Get the start/end point for composition adorner.
// Currently Text doesn't aware of the spaceroom for the drawing of the composition
// adorner(like as normal/bold dot/line/squggle), so we should draw the composition adorners
// to the closest area of the bottom text.
Point startPoint = new Point(compositionLine.StartPoint.X + clauseGap, compositionLine.StartPoint.Y - halfLineHeight);
Point endPoint = new Point(compositionLine.EndPoint.X - clauseGap, compositionLine.EndPoint.Y - halfLineHeight);
// Apply composition line color which is actually the foreground of text as well
pen.Brush = new SolidColorBrush(compositionLine.LineColor);
// Apply matrix to start/end point
//
transform.TryTransform(startPoint, out startPoint);
transform.TryTransform(endPoint, out endPoint);
if (isChinesePinyin && hasVirtualSelection)
{
Rect rect = Rect.Union(compositionLine.StartRect, compositionLine.EndRect);
rect = transform.TransformBounds(rect);
drawingContext.PushOpacity(selectionOpacity);
drawingContext.DrawRectangle(selectionBrush, selectionPen, rect);
drawingContext.Pop();
}
if (squiggle)
{
// Draw the squiggle line with using of the PathFigure and DrawGemetry.
// We may revisit this logic to render the smooth squiggle line.
Point pathPoint = new Point(startPoint.X, startPoint.Y - halfLineHeight);
double squiggleGap = halfLineHeight;
PathFigure pathFigure = new PathFigure();
pathFigure.StartPoint = pathPoint;
int indexPoint = 0;
while (indexPoint < ((endPoint.X - startPoint.X) / (squiggleGap)))
{
if (indexPoint % 4 == 0 || indexPoint % 4 == 3)
{
pathPoint = new Point(pathPoint.X + squiggleGap, pathPoint.Y + halfLineHeight);
pathFigure.Segments.Add(new LineSegment(pathPoint, true));
}
else if (indexPoint % 4 == 1 || indexPoint % 4 == 2)
{
pathPoint = new Point(pathPoint.X + squiggleGap, pathPoint.Y - halfLineHeight);
pathFigure.Segments.Add(new LineSegment(pathPoint, true));
}
indexPoint++;
}
PathGeometry pathGeometry = new PathGeometry();
pathGeometry.Figures.Add(pathFigure);
// Draw the composition line with the squiggle
drawingContext.DrawGeometry(null, pen, pathGeometry);
}
else
{
drawingContext.DrawLine(pen, startPoint, endPoint);
}
}
}
}
#endregion Protected Events
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <summary>
/// Add the composition attribute range that will be rendered.
/// Used in TextServicesDisplayAttributePropertyRanges (for composition display attribute)
/// </summary>
internal void AddAttributeRange(ITextPointer start, ITextPointer end, TextServicesDisplayAttribute textServiceDisplayAttribute)
{
// Set the range start/end point's logical direction
ITextPointer rangeStart = start.CreatePointer(LogicalDirection.Forward);
ITextPointer rangeEnd = end.CreatePointer(LogicalDirection.Backward);
// Add the composition attribute range
_attributeRanges.Add(new AttributeRange(_textView, rangeStart, rangeEnd, textServiceDisplayAttribute));
}
/// <summary>
/// Invalidates the CompositionAdorner render.
/// Used in TextServicesDisplayAttributePropertyRanges (for composition display attribute)
/// </summary>
internal void InvalidateAdorner()
{
for (int i = 0; i < _attributeRanges.Count; i++)
{
// Get the composition attribute range from the attribute range lists
AttributeRange attributeRange = (AttributeRange)_attributeRanges[i];
// Add the composition lines for rendering the composition lines
attributeRange.AddCompositionLines();
}
// Invalidate the CompositionAdorner to update the rendering.
AdornerLayer adornerLayer = VisualTreeHelper.GetParent(this) as AdornerLayer;
if (adornerLayer != null)
{
adornerLayer.Update(AdornedElement);
adornerLayer.InvalidateArrange();
}
}
/// <summary>
/// Add CompositionAdorner to the scoping AdornerLayer.
/// </summary>
internal void Initialize(ITextView textView)
{
Debug.Assert(_adornerLayer == null, "Attempt to overwrite existing AdornerLayer!");
_adornerLayer = AdornerLayer.GetAdornerLayer(textView.RenderScope);
if (_adornerLayer != null)
{
// Add the CompositionAdorner to the scoping of AdornerLayer
_adornerLayer.Add(this);
}
}
/// <summary>
/// Remove this CompositionAdorner from its AdornerLayer.
/// </summary>
internal void Uninitialize()
{
if (_adornerLayer != null)
{
// Remove CompositionAdorner form the socping of AdornerLayer
_adornerLayer.Remove(this);
_adornerLayer = null;
}
}
#endregion Internal methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// AdornerLayer holding this CompositionAdorner visual
private AdornerLayer _adornerLayer;
// TextView to which this CompositionAdorner is attached as adorner
private ITextView _textView;
// ArrayList for the composition attribute ranges
private readonly ArrayList _attributeRanges;
// Composition line's dot length
private const double DotLength = 1.2;
// Ratio of the composition line
private const double NormalLineHeightRatio = 0.06;
// Ratio of the bold composition line
private const double BoldLineHeightRatio = 0.08;
// Ratio of the composition line of dot
private const double NormalDotLineHeightRatio = 0.08;
// Ratio of the bold composition line of dot
private const double BoldDotLineHeightRatio = 0.10;
// Ratio of the composition line's dash
private const double NormalDashRatio = 0.27;
// Ratio of the bold composition line's dash
private const double BoldDashRatio = 0.39;
// Ratio of the composition line's clause gap
private const double ClauseGapRatio = 0.09;
// Ratio of the composition line's dash gap
private const double NormalDashGapRatio = 0.04;
// Ratio of the bold composition line's dash gap
private const double BoldDashGapRatio = 0.06;
// The culture name for Chinese Pinyin
private const string chinesePinyin = "zh-CN";
#endregion Private Fields
//------------------------------------------------------
//
// Private Class
//
//------------------------------------------------------
private class AttributeRange
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
internal AttributeRange(ITextView textView, ITextPointer start, ITextPointer end, TextServicesDisplayAttribute textServicesDisplayAttribute)
{
_textView = textView;
_startOffset = start.Offset;
_endOffset = end.Offset;
_textServicesDisplayAttribute = textServicesDisplayAttribute;
_compositionLines = new ArrayList(1);
}
#endregion Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Add the composition lines for rendering the composition lines.
internal void AddCompositionLines()
{
// Erase any current lines.
_compositionLines.Clear();
ITextPointer start = _textView.TextContainer.Start.CreatePointer(_startOffset, LogicalDirection.Forward);
ITextPointer end = _textView.TextContainer.Start.CreatePointer(_endOffset, LogicalDirection.Backward);
while (start.CompareTo(end) < 0 && start.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
{
start.MoveToNextContextPosition(LogicalDirection.Forward);
}
Invariant.Assert(start.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text);
if (end.HasValidLayout)
{
// Get the rectangle for start/end position
_startRect = _textView.GetRectangleFromTextPosition(start);
_endRect = _textView.GetRectangleFromTextPosition(end);
// Check whether the composition line is single or multiple lines
if (_startRect.Top != _endRect.Top)
{
// Add the composition lines to be rendered for the composition string
AddMultipleCompositionLines(start, end);
}
else
{
// Set the start/end pointer to draw the line
Color lineColor = _textServicesDisplayAttribute.GetLineColor(start);
// Add the composition line to be rendered
_compositionLines.Add(new CompositionLine(_startRect, _endRect, lineColor));
}
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Height of the composition attribute range.
/// </summary>
internal double Height
{
get
{
return _startRect.Bottom - _startRect.Top;
}
}
/// <summary>
/// CompositionLines of the composition attribute range.
/// </summary>
internal ArrayList CompositionLines
{
get
{
return _compositionLines;
}
}
/// <summary>
/// Composition attribute information.
/// </summary>
internal TextServicesDisplayAttribute TextServicesDisplayAttribute
{
get
{
return _textServicesDisplayAttribute;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
private void AddMultipleCompositionLines(ITextPointer start, ITextPointer end)
{
// Initalize the start/end line pointer
ITextPointer startLinePointer = start;
ITextPointer endLinePointer = startLinePointer;
// Get all composition lines that includes the start/end pointer
while (endLinePointer.CompareTo(end) < 0)
{
TextSegment textSegment = _textView.GetLineRange(endLinePointer);
if (textSegment.IsNull)
{
// endLinePointer is not within the TextView's definition of a line.
// Skip ahead to text on the next iteration.
startLinePointer = endLinePointer;
}
else
{
Debug.Assert(start.CompareTo(startLinePointer) <= 0, "The start pointer is positioned after the composition start line pointer!");
if (startLinePointer.CompareTo(textSegment.Start) < 0)
{
// Update the start line pointer
startLinePointer = textSegment.Start;
}
if (endLinePointer.CompareTo(textSegment.End) < 0)
{
if (end.CompareTo(textSegment.End) < 0)
{
// Update the end line pointer
endLinePointer = end.CreatePointer();
}
else
{
// Update the end line pointer
endLinePointer = textSegment.End.CreatePointer(LogicalDirection.Backward);
}
}
else
{
Debug.Assert(endLinePointer.CompareTo(textSegment.End) == 0, "The end line pointer is positioned after the composition text range end pointer!");
}
// Get the rectangle for start/end position
Rect startRect = _textView.GetRectangleFromTextPosition(startLinePointer);
Rect endRect = _textView.GetRectangleFromTextPosition(endLinePointer);
// Add the composition line to be rendered
_compositionLines.Add(new CompositionLine(startRect, endRect, _textServicesDisplayAttribute.GetLineColor(startLinePointer)));
startLinePointer = textSegment.End.CreatePointer(LogicalDirection.Forward);
}
// Move the start pointer to the next text line. startLinePointer must be a pointer to start
// text.
while ((startLinePointer.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.None) &&
(startLinePointer.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text))
{
startLinePointer.MoveToNextContextPosition(LogicalDirection.Forward);
}
endLinePointer = startLinePointer;
}
}
#endregion Private methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// TextView to which this CompositionAdorner is attached as adorner
private ITextView _textView;
// Start rect of the composition attribute range
private Rect _startRect;
// End rect of the composition attribute range
private Rect _endRect;
// Start position offset of the composition attribute range
private readonly int _startOffset;
// End position offset of the composition attribute range
private readonly int _endOffset;
// Composition display attribute that is specified from IME
private readonly TextServicesDisplayAttribute _textServicesDisplayAttribute;
// ArrayList for the composition lines
private readonly ArrayList _compositionLines;
#endregion Private Fields
}
private class CompositionLine
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
internal CompositionLine(Rect startRect, Rect endRect, Color lineColor)
{
_startRect = startRect;
_endRect = endRect;
_color = lineColor;
}
#endregion Constructors
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Start point of the composition line draw
/// </summary>
internal Point StartPoint
{
get
{
return _startRect.BottomLeft;
}
}
/// <summary>
/// End point of the composition line draw
/// </summary>
internal Point EndPoint
{
get
{
return _endRect.BottomRight;
}
}
/// <summary>
/// Start rect of the composition line draw
/// </summary>
internal Rect StartRect
{
get
{
return _startRect;
}
}
/// <summary>
/// End rect of the composition line draw
/// </summary>
internal Rect EndRect
{
get
{
return _endRect;
}
}
/// <summary>
/// Color of the composition line draw
/// </summary>
internal Color LineColor
{
get
{
return _color;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Start point of the composition line draw
private Rect _startRect;
// End point of the composition line draw
private Rect _endRect;
// Color of the composition line draw
private Color _color;
#endregion Private Fields
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Threading
{
public sealed partial class Semaphore : WaitHandle
{
[SecuritySafeCritical]
public Semaphore(int initialCount, int maximumCount) : this(initialCount, maximumCount, null) { }
[SecurityCritical]
public Semaphore(int initialCount, int maximumCount, string name)
{
if (initialCount < 0)
{
throw new ArgumentOutOfRangeException("initialCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (maximumCount < 1)
{
throw new ArgumentOutOfRangeException("maximumCount", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if (initialCount > maximumCount)
{
throw new ArgumentException(Environment.GetResourceString("Argument_SemaphoreInitialMaximum"));
}
SafeWaitHandle myHandle = CreateSemaphone(initialCount, maximumCount, name);
if (myHandle.IsInvalid)
{
int errorCode = Marshal.GetLastWin32Error();
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(
Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
__Error.WinIOError();
}
this.SafeWaitHandle = myHandle;
}
[SecurityCritical]
public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew)
{
if (initialCount < 0)
{
throw new ArgumentOutOfRangeException("initialCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (maximumCount < 1)
{
throw new ArgumentOutOfRangeException("maximumCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (initialCount > maximumCount)
{
throw new ArgumentException(Environment.GetResourceString("Argument_SemaphoreInitialMaximum"));
}
SafeWaitHandle myHandle = CreateSemaphone(initialCount, maximumCount, name);
int errorCode = Marshal.GetLastWin32Error();
if (myHandle.IsInvalid)
{
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(
Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
__Error.WinIOError();
}
createdNew = errorCode != Win32Native.ERROR_ALREADY_EXISTS;
this.SafeWaitHandle = myHandle;
}
[SecurityCritical]
private Semaphore(SafeWaitHandle handle)
{
this.SafeWaitHandle = handle;
}
[SecurityCritical]
private static SafeWaitHandle CreateSemaphone(int initialCount, int maximumCount, string name)
{
if (name != null)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
#else
if (name.Length > Path.MAX_PATH)
throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", name));
#endif
}
Contract.Assert(initialCount >= 0);
Contract.Assert(maximumCount >= 1);
Contract.Assert(initialCount <= maximumCount);
return Win32Native.CreateSemaphore(null, initialCount, maximumCount, name);
}
[SecurityCritical]
public static Semaphore OpenExisting(string name)
{
Semaphore result;
switch (OpenExistingWorker(name, out result))
{
case OpenExistingResult.NameNotFound:
throw new WaitHandleCannotBeOpenedException();
case OpenExistingResult.NameInvalid:
throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
case OpenExistingResult.PathNotFound:
throw new IOException(Win32Native.GetMessage(Win32Native.ERROR_PATH_NOT_FOUND));
default:
return result;
}
}
[SecurityCritical]
public static bool TryOpenExisting(string name, out Semaphore result)
{
return OpenExistingWorker(name, out result) == OpenExistingResult.Success;
}
[SecurityCritical]
private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
#else
if (name == null)
throw new ArgumentNullException("name", Environment.GetResourceString("ArgumentNull_WithParamName"));
if (name.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
if (name.Length > Path.MAX_PATH)
throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", name));
const int SYNCHRONIZE = 0x00100000;
const int SEMAPHORE_MODIFY_STATE = 0x00000002;
//Pass false to OpenSemaphore to prevent inheritedHandles
SafeWaitHandle myHandle = Win32Native.OpenSemaphore(SEMAPHORE_MODIFY_STATE | SYNCHRONIZE, false, name);
if (myHandle.IsInvalid)
{
result = null;
int errorCode = Marshal.GetLastWin32Error();
if (Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode)
return OpenExistingResult.NameNotFound;
if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode)
return OpenExistingResult.PathNotFound;
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
return OpenExistingResult.NameInvalid;
//this is for passed through NativeMethods Errors
__Error.WinIOError();
}
result = new Semaphore(myHandle);
return OpenExistingResult.Success;
#endif
}
public int Release()
{
return Release(1);
}
// increase the count on a semaphore, returns previous count
[SecuritySafeCritical]
public int Release(int releaseCount)
{
if (releaseCount < 1)
{
throw new ArgumentOutOfRangeException("releaseCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
//If ReleaseSempahore returns false when the specified value would cause
// the semaphore's count to exceed the maximum count set when Semaphore was created
//Non-Zero return
int previousCount;
if (!Win32Native.ReleaseSemaphore(SafeWaitHandle, releaseCount, out previousCount))
{
throw new SemaphoreFullException();
}
return previousCount;
}
}
}
| |
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 DataSetScatterPlotControl : UserControl, INotifyPropertyChanged
{
public event EventHandler DataSetChanged;
private DataSet _DataSet;
[Bindable(true)]
public DataSet DataSet
{
get { return _DataSet; }
set
{
_DataSet = value;
OnDataSetChanged(EventArgs.Empty);
NotifyPropertyChanged("DataSet");
}
}
public event EventHandler TableChanged;
private string _Table;
[Bindable(true)]
public string Table
{
get { return _Table; }
set
{
_Table = value;
OnTableChanged(EventArgs.Empty);
NotifyPropertyChanged("Table");
}
}
public event EventHandler XColumnChanged;
private string _XColumn;
[Bindable(true)]
public string XColumn
{
get { return _XColumn; }
set
{
_XColumn = value;
OnXColumnChanged(EventArgs.Empty);
NotifyPropertyChanged("XColumn");
}
}
public event EventHandler YColumnChanged;
private string _YColumn;
[Bindable(true)]
public string YColumn
{
get { return _YColumn; }
set
{
_YColumn = value;
OnXColumnChanged(EventArgs.Empty);
NotifyPropertyChanged("YColumn");
}
}
public event EventHandler TagColumnChanged;
private string _TagColumn;
[Bindable(true)]
public string TagColumn
{
get { return _TagColumn; }
set
{
_TagColumn = value;
OnXColumnChanged(EventArgs.Empty);
NotifyPropertyChanged("TagColumn");
}
}
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");
}
}
public event EventHandler GraphColorChanged;
private Color _GraphColor = Color.LightGoldenrodYellow;
[SettingsBindable(true)]
[Bindable(true)]
public Color GraphColor
{
get { return _GraphColor; }
set {
_GraphColor = value;
if(GraphColorChanged != null)
try
{
GraphColorChanged(this, EventArgs.Empty);
}
catch (Exception x) { ; }
NotifyPropertyChanged("GraphColor");
}
}
public event EventHandler PointsColorChanged;
private Color _PointsColor = Color.Crimson;
[SettingsBindable(true)]
[Bindable(true)]
public Color PointsColor
{
get { return _PointsColor; }
set {
_PointsColor = value;
if(PointsColorChanged != null)
try
{
PointsColorChanged(this, EventArgs.Empty);
}
catch (Exception x) { ; }
NotifyPropertyChanged("PointsColor");
}
}
private ZedGraph.LineItem _ScatterPlot;
protected ZedGraph.LineItem ScatterPlot
{
get { return _ScatterPlot; }
set
{
_ScatterPlot = value;
}
}
public event EventHandler SymbolTypeChanged;
private ZedGraph.SymbolType _SymbolType = ZedGraph.SymbolType.Circle;
[Bindable(true)]
[SettingsBindable(true)]
[DefaultValue(ZedGraph.SymbolType.Circle)]
public ZedGraph.SymbolType SymbolType
{
get { return _SymbolType; }
set
{
_SymbolType = value;
if (SymbolTypeChanged != null)
try
{
SymbolTypeChanged(this, EventArgs.Empty);
}
catch (Exception x) { ; }
NotifyPropertyChanged("SymbolType");
}
}
private ZedGraph.DataSourcePointList _Points;
protected ZedGraph.DataSourcePointList Points
{
get { return _Points; }
set { _Points = value; }
}
public DataSetScatterPlotControl()
{
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 OnXColumnChanged(EventArgs e)
{
RefreshGraph();
if (XColumnChanged != null) XColumnChanged(this, e);
}
protected virtual void OnYColumnChanged(EventArgs e)
{
RefreshGraph();
if (YColumnChanged != null) YColumnChanged(this, e);
}
protected virtual void OnTagColumnChanged(EventArgs e)
{
RefreshGraph();
if (TagColumnChanged != null) TagColumnChanged(this, e);
}
protected virtual void OnFilterChanged(EventArgs e)
{
DataSetBindingSource.Filter = Filter;
RefreshGraph();
if (FilterChanged != null) FilterChanged(this, e);
}
protected virtual void OnTableChanged(EventArgs e)
{
try
{
DataSetBindingSource.DataMember = Table;
}
catch (Exception x) { ; }
RefreshGraph();
if (TableChanged != null) TableChanged(this, e);
}
protected virtual void OnDataSetChanged(EventArgs e)
{
if (DataSet != null) DataSetBindingSource.DataSource = DataSet;
else DataSetBindingSource.DataSource = typeof(DataSet);
OnTableChanged(e);
RefreshGraph();
if (DataSetChanged != null) DataSetChanged(this, e);
}
public virtual void RefreshGraph()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(RefreshGraph));
return;
}
ConfigureGraph();
ConfigureAxes();
ConfigurePlots();
ConfigureCurves();
try
{
GraphControl.AxisChange();
}
catch (Exception e) { ; }
GraphControl.Invalidate();
}
protected virtual void ResetGraph()
{
Points = null;
ScatterPlot = null;
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;
GraphControl.IsShowPointValues = true;
}
protected virtual void ConfigureAxes()
{
if (DataSet == null || Table == null || XColumn == null || YColumn == null
|| Table == "" || XColumn == "" || YColumn == "") return;
GraphControl.GraphPane.XAxis.Type = DetermineAxisType(XColumn);
if (GraphControl.GraphPane.XAxis.Type == ZedGraph.AxisType.Date)
GraphControl.GraphPane.XAxis.Scale.Format = GetDateTimeFormat(XColumn);
GraphControl.GraphPane.XAxis.Title.Text = DataSet.Tables[Table].Columns[XColumn].Caption ?? XColumn;
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.Type = DetermineAxisType(YColumn);
if (GraphControl.GraphPane.YAxis.Type == ZedGraph.AxisType.Date)
GraphControl.GraphPane.YAxis.Scale.Format = GetDateTimeFormat(YColumn);
GraphControl.GraphPane.YAxis.Title.Text = DataSet.Tables[Table].Columns[YColumn].Caption ?? YColumn;
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;
}
protected virtual string GetDateTimeFormat(string column)
{
if (DataSet == null || Table == null || Table == "" || column == null || column == "")
return "d";
if (DataSet.Tables[Table].Columns[column].DataType == typeof(DateTime))
return "d";
if (DataSet.Tables[Table].Columns[column].DataType == typeof(TimeSpan))
return "hh:mm:ss";
return "d";
}
protected virtual ZedGraph.AxisType DetermineAxisType(string column)
{
if (DataSet == null || Table == null || Table == "" || column == null || column == "")
return ZedGraph.AxisType.Linear;
if (DataSet.Tables[Table].Columns[column].DataType == typeof(DateTime))
return ZedGraph.AxisType.Date;
if (DataSet.Tables[Table].Columns[column].DataType == typeof(TimeSpan))
return ZedGraph.AxisType.Linear;
return ZedGraph.AxisType.Linear;
}
protected virtual void ConfigurePlots()
{
if (Points == null) Points = new ZedGraph.DataSourcePointList();
Points.DataSource = DataSetBindingSource;
Points.XDataMember = XColumn;
Points.YDataMember = YColumn;
Points.TagDataMember = TagColumn;
}
protected virtual void ConfigureCurves()
{
if (ScatterPlot == null)
ScatterPlot = GraphControl.GraphPane.AddCurve(
String.Format("{0} vs. {1}", YColumn, XColumn),
Points, PointsColor, SymbolType);
else
{
ScatterPlot.Points = Points;
ScatterPlot.Label.Text = String.Format("{0} vs. {1}", YColumn, XColumn);
ScatterPlot.Color = PointsColor;
}
ScatterPlot.Symbol.Fill.IsVisible = true;
ScatterPlot.Line.IsVisible = false;
ScatterPlot.Symbol.IsAntiAlias = true;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Rest.Generator.Azure.NodeJS.Properties;
using Microsoft.Rest.Generator.Azure.NodeJS.Templates;
using Microsoft.Rest.Generator.ClientModel;
using Microsoft.Rest.Generator.NodeJS;
using Microsoft.Rest.Generator.NodeJS.Templates;
using Microsoft.Rest.Generator.Utilities;
using System.Collections.Generic;
namespace Microsoft.Rest.Generator.Azure.NodeJS
{
public class AzureNodeJSCodeGenerator : NodeJSCodeGenerator
{
private const string ClientRuntimePackage = "ms-rest-azure version 1.8.0";
// List of models with paging extensions.
private IList<PageTemplateModel> pageModels;
public AzureNodeJSCodeGenerator(Settings settings)
: base(settings)
{
pageModels = new List<PageTemplateModel>();
}
public override string Name
{
get { return "Azure.NodeJS"; }
}
public override string Description
{
// TODO resource string.
get { return "Azure NodeJS for Http Client Libraries"; }
}
public override string UsageInstructions
{
get
{
return string.Format(CultureInfo.InvariantCulture,
Resources.UsageInformation, ClientRuntimePackage);
}
}
public override string ImplementationFileExtension
{
get { return ".js"; }
}
/// <summary>
/// Normalizes client model by updating names and types to be language specific.
/// </summary>
/// <param name="serviceClient"></param>
public override void NormalizeClientModel(ServiceClient serviceClient)
{
// MethodNames are normalized explicitly to provide a consitent method name while
// generating cloned methods for long running operations with reserved words. For
// example - beginDeleteMethod() insteadof beginDelete() as delete is a reserved word.
Namer.NormalizeMethodNames(serviceClient);
AzureExtensions.NormalizeAzureClientModel(serviceClient, Settings, Namer);
base.NormalizeClientModel(serviceClient);
NormalizeApiVersion(serviceClient);
NormalizePaginatedMethods(serviceClient);
ExtendAllResourcesToBaseResource(serviceClient);
}
private static void ExtendAllResourcesToBaseResource(ServiceClient serviceClient)
{
if (serviceClient != null)
{
foreach (var model in serviceClient.ModelTypes)
{
if (model.Extensions.ContainsKey(AzureExtensions.AzureResourceExtension) &&
(bool)model.Extensions[AzureExtensions.AzureResourceExtension])
{
model.BaseModelType = new CompositeType { Name = "BaseResource", SerializedName = "BaseResource" };
}
}
}
}
private static void NormalizeApiVersion(ServiceClient serviceClient)
{
serviceClient.Properties.Where(
p => p.SerializedName.Equals(AzureExtensions.ApiVersion, StringComparison.OrdinalIgnoreCase))
.ForEach(p => p.DefaultValue = p.DefaultValue.Replace("\"", "'"));
serviceClient.Properties.Where(
p => p.SerializedName.Equals(AzureExtensions.AcceptLanguage, StringComparison.OrdinalIgnoreCase))
.ForEach(p => p.DefaultValue = p.DefaultValue.Replace("\"", "'"));
}
/// <summary>
/// Changes paginated method signatures to return Page type.
/// </summary>
/// <param name="serviceClient"></param>
public virtual void NormalizePaginatedMethods(ServiceClient serviceClient)
{
if (serviceClient == null)
{
throw new ArgumentNullException("serviceClient");
}
foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension)))
{
string nextLinkName = null;
var ext = method.Extensions[AzureExtensions.PageableExtension] as Newtonsoft.Json.Linq.JContainer;
if (ext == null)
{
continue;
}
nextLinkName = (string)ext["nextLinkName"];
string itemName = (string)ext["itemName"] ?? "value";
foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeType).Select(s => s.Key).ToArray())
{
var compositType = (CompositeType)method.Responses[responseStatus].Body;
var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType;
// if the type is a wrapper over page-able response
if (sequenceType != null)
{
compositType.Extensions[AzureExtensions.PageableExtension] = true;
var pageTemplateModel = new PageTemplateModel(compositType, serviceClient, nextLinkName, itemName);
if (!pageModels.Contains(pageTemplateModel))
{
pageModels.Add(pageTemplateModel);
}
}
}
}
}
/// <summary>
/// Generate Azure NodeJS client code for given ServiceClient.
/// </summary>
/// <param name="serviceClient"></param>
/// <returns></returns>
public override async Task Generate(ServiceClient serviceClient)
{
var serviceClientTemplateModel = new AzureServiceClientTemplateModel(serviceClient);
// Service client
var serviceClientTemplate = new Microsoft.Rest.Generator.Azure.NodeJS.Templates.AzureServiceClientTemplate
{
Model = serviceClientTemplateModel
};
await Write(serviceClientTemplate, serviceClient.Name.ToCamelCase() + ".js");
if (!DisableTypeScriptGeneration)
{
var serviceClientTemplateTS = new AzureServiceClientTemplateTS
{
Model = serviceClientTemplateModel,
};
await Write(serviceClientTemplateTS, serviceClient.Name.ToCamelCase() + ".d.ts");
}
//Models
if (serviceClient.ModelTypes.Any())
{
// Paged Models
foreach (var pageModel in pageModels)
{
//Add the PageTemplateModel to AzureServiceClientTemplateModel
if (!serviceClientTemplateModel.PageTemplateModels.Contains(pageModel))
{
serviceClientTemplateModel.PageTemplateModels.Add(pageModel);
}
var pageTemplate = new PageModelTemplate
{
Model = pageModel
};
await Write(pageTemplate, Path.Combine("models", pageModel.Name.ToCamelCase() + ".js"));
}
var modelIndexTemplate = new AzureModelIndexTemplate
{
Model = serviceClientTemplateModel
};
await Write(modelIndexTemplate, Path.Combine("models", "index.js"));
if (!DisableTypeScriptGeneration)
{
var modelIndexTemplateTS = new AzureModelIndexTemplateTS
{
Model = serviceClientTemplateModel
};
await Write(modelIndexTemplateTS, Path.Combine("models", "index.d.ts"));
}
foreach (var modelType in serviceClientTemplateModel.ModelTemplateModels)
{
var modelTemplate = new ModelTemplate
{
Model = modelType
};
await Write(modelTemplate, Path.Combine("models", modelType.Name.ToCamelCase() + ".js"));
}
}
//MethodGroups
if (serviceClientTemplateModel.MethodGroupModels.Any())
{
var methodGroupIndexTemplate = new MethodGroupIndexTemplate
{
Model = serviceClientTemplateModel
};
await Write(methodGroupIndexTemplate, Path.Combine("operations", "index.js"));
if (!DisableTypeScriptGeneration)
{
var methodGroupIndexTemplateTS = new MethodGroupIndexTemplateTS
{
Model = serviceClientTemplateModel
};
await Write(methodGroupIndexTemplateTS, Path.Combine("operations", "index.d.ts"));
}
foreach (var methodGroupModel in serviceClientTemplateModel.MethodGroupModels)
{
var methodGroupTemplate = new AzureMethodGroupTemplate
{
Model = methodGroupModel as AzureMethodGroupTemplateModel
};
await Write(methodGroupTemplate, Path.Combine("operations", methodGroupModel.MethodGroupType.ToCamelCase() + ".js"));
}
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.PythonTools.Django;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;
using TestUtilities;
using TestUtilities.UI;
using TestUtilities.UI.Python;
using TestUtilities.UI.Python.Django;
using PythonConstants = Microsoft.PythonTools.PythonConstants;
namespace DjangoUITests {
public class DjangoProjectUITests {
public void NewDjangoProject(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) {
var project = app.CreateProject(
PythonVisualStudioApp.TemplateLanguageName,
PythonVisualStudioApp.DjangoWebProjectTemplate,
TestData.GetTempPath(),
"NewDjangoProject"
);
var folder = project.ProjectItems.Item(project.Name);
Assert.IsNotNull(project.ProjectItems.Item("manage.py"));
Assert.IsNotNull(folder.ProjectItems.Item("settings.py"));
Assert.IsNotNull(folder.ProjectItems.Item("urls.py"));
Assert.IsNotNull(folder.ProjectItems.Item("__init__.py"));
Assert.IsNotNull(folder.ProjectItems.Item("wsgi.py"));
}
public void NewDjangoProjectSafeProjectName(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) {
var project = app.CreateProject(
PythonVisualStudioApp.TemplateLanguageName,
PythonVisualStudioApp.DjangoWebProjectTemplate,
TestData.GetTempPath(),
"Django Project $100"
);
var folder = project.ProjectItems.Item("Django_Project__100");
Assert.IsNotNull(project.ProjectItems.Item("manage.py"));
Assert.IsNotNull(folder.ProjectItems.Item("settings.py"));
Assert.IsNotNull(folder.ProjectItems.Item("urls.py"));
Assert.IsNotNull(folder.ProjectItems.Item("__init__.py"));
Assert.IsNotNull(folder.ProjectItems.Item("wsgi.py"));
var settings = app.ServiceProvider.GetUIThread().Invoke(() => project.GetPythonProject().GetProperty("DjangoSettingsModule"));
Assert.AreEqual("Django_Project__100.settings", settings);
}
public void DjangoCollectStaticFilesCommand(PythonVisualStudioApp app, DjangoInterpreterSetter interpreterSetter) {
var sln = app.CopyProjectForTest(@"TestData\DjangoApplication.sln");
var project = app.OpenProject(sln);
app.SolutionExplorerTreeView.SelectProject(project);
app.Dte.ExecuteCommand("Project.CollectStaticFiles");
using (var console = app.GetInteractiveWindow("Django Management Console - " + project.Name)) {
Assert.IsNotNull(console);
console.WaitForTextEnd("The interactive Python process has exited.", ">");
Assert.IsTrue(console.TextView.TextSnapshot.GetText().Contains("0 static files copied"));
}
}
public void DjangoShellCommand(PythonVisualStudioApp app, DjangoInterpreterSetter interpreterSetter) {
// Open a project that has some models defined, and make sure they can be imported without errors
var sln = app.CopyProjectForTest(@"TestData\DjangoAnalysisTestApp.sln");
var project = app.OpenProject(sln);
app.SolutionExplorerTreeView.SelectProject(project);
app.Dte.ExecuteCommand("Project.OpenDjangoShell");
using (var console = app.GetInteractiveWindow("Django Management Console - " + project.Name)) {
Assert.IsNotNull(console);
bool started = false;
for (int i = 0; i < 20; i++) {
if (console.TextView.TextSnapshot.GetText().Contains("Starting Django")) {
started = true;
break;
}
Thread.Sleep(250);
}
Assert.IsTrue(started, "Did not see 'Starting Django <ver> shell' message");
console.WaitForTextEnd(">");
console.SubmitCode("import myapp.models");
console.WaitForTextEnd(">import myapp.models", ">");
}
}
public void DjangoCommandsNonDjangoApp(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) {
var project = app.CreateProject(
PythonVisualStudioApp.TemplateLanguageName,
PythonVisualStudioApp.PythonApplicationTemplate,
TestData.GetTempPath(),
"DjangoCommandsNoDjangoApp"
);
app.SolutionExplorerTreeView.SelectProject(project);
try {
app.Dte.ExecuteCommand("Project.ValidateDjangoApp");
Assert.Fail("Expected COMException");
} catch (COMException e) {
// requires a Django project
Assert.IsTrue(e.Message.Contains("is not valid"), e.ToString());
}
try {
app.Dte.ExecuteCommand("Project.DjangoSyncDB");
Assert.Fail("Expected COMException");
} catch (COMException e) {
// requires a Django project
Assert.IsTrue(e.Message.Contains("is not valid"), e.ToString());
}
}
public void StartNewApp(PythonVisualStudioApp app, DjangoInterpreterSetter interpreterSetter) {
var project = app.CreateProject(
PythonVisualStudioApp.TemplateLanguageName,
PythonVisualStudioApp.DjangoWebProjectTemplate,
TestData.GetTempPath(),
"StartNewApp"
);
app.SolutionExplorerTreeView.SelectProject(project);
using (var newAppDialog = NewAppDialog.FromDte(app)) {
newAppDialog.AppName = "Fob";
newAppDialog.OK();
}
app.SolutionExplorerTreeView.WaitForItem(
app.Dte.Solution.FullName,
app.Dte.Solution.Projects.Item(1).Name,
"Fob",
"models.py"
);
var appFolder = project.ProjectItems.Item("Fob");
Assert.IsNotNull(appFolder.ProjectItems.Item("models.py"));
Assert.IsNotNull(appFolder.ProjectItems.Item("tests.py"));
Assert.IsNotNull(appFolder.ProjectItems.Item("views.py"));
Assert.IsNotNull(appFolder.ProjectItems.Item("__init__.py"));
var templatesFolder = appFolder.ProjectItems.Item("templates");
var templatesAppFolder = templatesFolder.ProjectItems.Item("Fob");
Assert.IsNotNull(templatesAppFolder.ProjectItems.Item("index.html"));
app.SolutionExplorerTreeView.SelectProject(project);
app.Dte.ExecuteCommand("Project.DjangoCheckDjango17");
using (var console = app.GetInteractiveWindow("Django Management Console - " + project.Name)) {
Assert.IsNotNull(console);
console.WaitForTextEnd("The interactive Python process has exited.", ">");
var consoleText = console.TextView.TextSnapshot.GetText();
AssertUtil.Contains(consoleText, "Executing manage.py check");
AssertUtil.Contains(consoleText, "System check identified no issues (0 silenced).");
}
app.SolutionExplorerTreeView.SelectProject(project);
using (var newItem = NewItemDialog.FromDte(app)) {
var htmlPage = newItem.ProjectTypes.FindItem("HTML Page");
htmlPage.Select();
newItem.FileName = "NewPage.html";
newItem.OK();
}
System.Threading.Thread.Sleep(1000);
Assert.IsNotNull(project.ProjectItems.Item("NewPage.html"));
}
public void StartNewAppDuplicateName(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) {
var project = app.CreateProject(
PythonVisualStudioApp.TemplateLanguageName,
PythonVisualStudioApp.DjangoWebProjectTemplate,
TestData.GetTempPath(),
"StartNewAppDuplicateName"
);
app.SolutionExplorerTreeView.SelectProject(project);
using (var newAppDialog = NewAppDialog.FromDte(app)) {
newAppDialog.AppName = "Fob";
newAppDialog.OK();
}
app.SolutionExplorerTreeView.WaitForItem(
app.Dte.Solution.FullName,
app.Dte.Solution.Projects.Item(1).Name,
"Fob",
"models.py"
);
app.Dte.Documents.CloseAll(EnvDTE.vsSaveChanges.vsSaveChangesNo);
app.SolutionExplorerTreeView.SelectProject(project);
using (var newAppDialog = NewAppDialog.FromDte(app)) {
newAppDialog.AppName = "Fob";
newAppDialog.OK();
}
using (var dlg = AutomationDialog.WaitForDialog(app)) { }
}
public void StartNewAppSameAsProjectName(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) {
var project = app.CreateProject(
PythonVisualStudioApp.TemplateLanguageName,
PythonVisualStudioApp.DjangoWebProjectTemplate,
TestData.GetTempPath(),
"StartNewAppSameAsProjectName"
);
app.SolutionExplorerTreeView.SelectProject(project);
using (var newAppDialog = NewAppDialog.FromDte(app)) {
newAppDialog.AppName = app.Dte.Solution.Projects.Item(1).Name;
newAppDialog.OK();
}
using (var dlg = AutomationDialog.WaitForDialog(app)) { }
}
public void DebugProjectProperties(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) {
var project = app.CreateProject(
PythonVisualStudioApp.TemplateLanguageName,
PythonVisualStudioApp.DjangoWebProjectTemplate,
TestData.GetTempPath(),
"DebugProjectProperties"
);
app.SolutionExplorerTreeView.SelectProject(project);
app.Dte.ExecuteCommand("Project.Properties");
var window = app.Dte.Windows.OfType<EnvDTE.Window>().FirstOrDefault(w => w.Caption == project.Name);
Assert.IsNotNull(window);
window.Activate();
var hwnd = window.HWnd;
var projProps = new ProjectPropertiesWindow(new IntPtr(hwnd));
// FYI This is broken on Dev15 (15.0 up to latest build as of now 15.3 build 26507)
// Active page can't be changed via UI automation.
// Bug 433488 has been filed.
// - InvokePattern is not available
// - SelectionItemPattern is available (according to Inspect) but does not work
// - Default action does nothing
var debugPage = projProps[new Guid(PythonConstants.DebugPropertyPageGuid)];
Assert.IsNotNull(debugPage);
var dbgProps = new PythonProjectDebugProperties(debugPage);
Assert.AreEqual("Django Web launcher", dbgProps.LaunchMode);
dbgProps.AssertMatchesProject(project.GetPythonProject());
}
public void DjangoProjectWithSubdirectory(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) {
var sln = app.CopyProjectForTest(@"TestData\DjangoProjectWithSubDirectory.sln");
var slnDir = PathUtils.GetParent(sln);
var project = app.OpenProject(sln);
var pyProj = project.GetPythonProject();
var dsm = pyProj.Site.GetUIThread().Invoke(() => pyProj.GetProperty("DjangoSettingsModule"));
Assert.AreEqual("config.settings", dsm);
var workDir = pyProj.Site.GetUIThread().Invoke(() => pyProj.GetWorkingDirectory()).TrimEnd('\\');
Assert.AreEqual(Path.Combine(slnDir, "DjangoProjectWithSubDirectory", "project"), workDir, true);
var cmd = pyProj.FindCommand("DjangoCollectStaticCommand");
pyProj.Site.GetUIThread().Invoke(() => {
Assert.IsTrue(cmd.CanExecute(pyProj), "Cannot execute DjangoCollectStaticCommand");
cmd.Execute(pyProj);
});
// The static dir is 'test_static', check that the admin files
// are copied into there.
Assert.IsTrue(Directory.Exists(Path.Combine(workDir, "test_static", "admin")), "admin static directory was not created");
Assert.IsTrue(File.Exists(Path.Combine(workDir, "test_static", "admin", "css", "base.css")), "admin static files were not copied");
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
[System.Serializable]
public class MegaBindInf
{
public float dist;
public int face;
public int i0;
public int i1;
public int i2;
public Vector3 bary;
public float weight;
public float area;
}
[System.Serializable]
public class MegaBindVert
{
public float weight;
public List<MegaBindInf> verts = new List<MegaBindInf>();
}
public struct MegaCloseFace
{
public int face;
public float dist;
}
[ExecuteInEditMode]
public class MegaWrap : MonoBehaviour
{
public float gap = 0.0f;
public float shrink = 1.0f;
public List<int> neededVerts = new List<int>();
public Vector3[] skinnedVerts;
public Mesh mesh = null;
public Vector3 offset = Vector3.zero;
public bool targetIsSkin = false;
public bool sourceIsSkin = false;
public int nomapcount = 0;
public Matrix4x4[] bindposes;
public BoneWeight[] boneweights;
public Transform[] bones;
public float size = 0.01f;
public int vertindex = 0;
public Vector3[] freeverts; // position for any vert with no attachments
public Vector3[] startverts;
public Vector3[] verts;
public MegaBindVert[] bindverts;
public MegaModifyObject target;
public float maxdist = 0.25f;
public int maxpoints = 4;
public bool WrapEnabled = true;
public MegaNormalMethod NormalMethod = MegaNormalMethod.Unity;
#if UNITY_5 || UNITY_6
public bool UseBakedMesh = true;
#endif
[ContextMenu("Help")]
public void Help()
{
Application.OpenURL("http://www.west-racing.com/mf/?page_id=3709");
}
Vector4 Plane(Vector3 v1, Vector3 v2, Vector3 v3)
{
Vector3 normal = Vector4.zero;
normal.x = (v2.y - v1.y) * (v3.z - v1.z) - (v2.z - v1.z) * (v3.y - v1.y);
normal.y = (v2.z - v1.z) * (v3.x - v1.x) - (v2.x - v1.x) * (v3.z - v1.z);
normal.z = (v2.x - v1.x) * (v3.y - v1.y) - (v2.y - v1.y) * (v3.x - v1.x);
normal = normal.normalized;
return new Vector4(normal.x, normal.y, normal.z, -Vector3.Dot(v2, normal));
}
float PlaneDist(Vector3 p, Vector4 plane)
{
Vector3 n = plane;
return Vector3.Dot(n, p) + plane.w;
}
public float GetDistance(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
return MegaNearestPointTest.DistPoint3Triangle3Dbl(p, p0, p1, p2);
}
public float GetPlaneDistance(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector4 pl = Plane(p0, p1, p2);
return PlaneDist(p, pl);
}
public Vector3 MyBary(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector3 bary = Vector3.zero;
Vector3 normal = FaceNormal(p0, p1, p2);
float areaABC = Vector3.Dot(normal, Vector3.Cross((p1 - p0), (p2 - p0)));
float areaPBC = Vector3.Dot(normal, Vector3.Cross((p1 - p), (p2 - p)));
float areaPCA = Vector3.Dot(normal, Vector3.Cross((p2 - p), (p0 - p)));
bary.x = areaPBC / areaABC; // alpha
bary.y = areaPCA / areaABC; // beta
bary.z = 1.0f - bary.x - bary.y; // gamma
return bary;
}
public Vector3 MyBary1(Vector3 p, Vector3 a, Vector3 b, Vector3 c)
{
Vector3 v0 = b - a, v1 = c - a, v2 = p - a;
float d00 = Vector3.Dot(v0, v0);
float d01 = Vector3.Dot(v0, v1);
float d11 = Vector3.Dot(v1, v1);
float d20 = Vector3.Dot(v2, v0);
float d21 = Vector3.Dot(v2, v1);
float denom = d00 * d11 - d01 * d01;
float w = (d11 * d20 - d01 * d21) / denom;
float v = (d00 * d21 - d01 * d20) / denom;
float u = 1.0f - v - w;
return new Vector3(u, v, w);
}
public Vector3 CalcBary(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
return MyBary(p, p0, p1, p2);
}
public float CalcArea(Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector3 e1 = p1 - p0;
Vector3 e2 = p2 - p0;
Vector3 e3 = Vector3.Cross(e1, e2);
return 0.5f * e3.magnitude;
}
Vector3 e11 = Vector3.zero;
Vector3 e22 = Vector3.zero;
Vector3 cr = Vector3.zero;
public Vector3 FaceNormal(Vector3 p0, Vector3 p1, Vector3 p2)
{
//Vector3 e1 = p1 - p0;
//Vector3 e2 = p2 - p0;
e11.x = p1.x - p0.x;
e11.y = p1.y - p0.y;
e11.z = p1.z - p0.z;
e22.x = p2.x - p0.x;
e22.y = p2.y - p0.y;
e22.z = p2.z - p0.z;
//Vector3 e2 = p2 - p0;
cr.x = e11.y * e22.z - e22.y * e11.z;
cr.y = -(e11.x * e22.z - e22.x * e11.z); // * -1;
cr.z = e11.x * e22.y - e22.x * e11.y;
return cr; //Vector3.Cross(e11, e22);
}
static void CopyBlendShapes(Mesh mesh1, Mesh clonemesh)
{
#if UNITY_5_3 || UNITY_5_4 || UNITY_6
int bcount = mesh1.blendShapeCount; //GetBlendShapeFrameCount();
Vector3[] deltaverts = new Vector3[mesh1.vertexCount];
Vector3[] deltanorms = new Vector3[mesh1.vertexCount];
Vector3[] deltatans = new Vector3[mesh1.vertexCount];
for ( int j = 0; j < bcount; j++ )
{
int frames = mesh1.GetBlendShapeFrameCount(j);
string bname = mesh1.GetBlendShapeName(j);
for ( int f = 0; f < frames; f++ )
{
mesh1.GetBlendShapeFrameVertices(j, f, deltaverts, deltanorms, deltatans);
float weight = mesh1.GetBlendShapeFrameWeight(j, f);
clonemesh.AddBlendShapeFrame(bname, weight, deltaverts, deltanorms, deltatans);
}
}
#endif
}
public Mesh CloneMesh(Mesh m)
{
Mesh clonemesh = new Mesh();
clonemesh.vertices = m.vertices;
#if UNITY_5_0 || UNITY_5_1 || UNITY_5
clonemesh.uv2 = m.uv2;
clonemesh.uv3 = m.uv3;
clonemesh.uv4 = m.uv4;
#else
clonemesh.uv1 = m.uv1;
clonemesh.uv2 = m.uv2;
#endif
clonemesh.uv = m.uv;
clonemesh.normals = m.normals;
clonemesh.tangents = m.tangents;
clonemesh.colors = m.colors;
clonemesh.subMeshCount = m.subMeshCount;
for ( int s = 0; s < m.subMeshCount; s++ )
clonemesh.SetTriangles(m.GetTriangles(s), s);
CopyBlendShapes(m, clonemesh);
clonemesh.boneWeights = m.boneWeights;
clonemesh.bindposes = m.bindposes;
clonemesh.name = m.name; // + "_copy";
clonemesh.RecalculateBounds();
return clonemesh;
}
[ContextMenu("Reset Mesh")]
public void ResetMesh()
{
if ( mesh )
{
mesh.vertices = startverts;
mesh.RecalculateBounds();
RecalcNormals();
//mesh.RecalculateNormals();
}
target = null;
bindverts = null;
}
public void SetMesh()
{
MeshFilter mf = GetComponent<MeshFilter>();
Mesh srcmesh = null;
if ( mf != null )
srcmesh = mf.sharedMesh;
else
{
SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
if ( smesh != null )
srcmesh = smesh.sharedMesh;
}
if ( srcmesh != null )
{
mesh = CloneMesh(srcmesh);
if ( mf )
mf.sharedMesh = mesh;
else
{
SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
smesh.sharedMesh = mesh;
}
}
}
public void Attach(MegaModifyObject modobj)
{
targetIsSkin = false;
sourceIsSkin = false;
if ( mesh && startverts != null )
mesh.vertices = startverts;
if ( modobj == null )
{
bindverts = null;
return;
}
nomapcount = 0;
if ( mesh )
mesh.vertices = startverts;
MeshFilter mf = GetComponent<MeshFilter>();
Mesh srcmesh = null;
if ( mf != null )
{
//skinned = false;
srcmesh = mf.mesh;
}
else
{
SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
if ( smesh != null )
{
//skinned = true;
srcmesh = smesh.sharedMesh;
sourceIsSkin = true;
}
}
if ( srcmesh == null )
{
Debug.LogWarning("No Mesh found on the target object, make sure target has a mesh and MegaFiers modifier attached!");
return;
}
if ( mesh == null )
mesh = CloneMesh(srcmesh); //mf.mesh);
if ( mf )
mf.mesh = mesh;
else
{
SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
smesh.sharedMesh = mesh;
}
if ( sourceIsSkin == false )
{
SkinnedMeshRenderer tmesh = (SkinnedMeshRenderer)modobj.GetComponent(typeof(SkinnedMeshRenderer));
if ( tmesh != null )
{
targetIsSkin = true;
if ( !sourceIsSkin )
{
Mesh sm = tmesh.sharedMesh;
bindposes = sm.bindposes;
boneweights = sm.boneWeights;
bones = tmesh.bones;
skinnedVerts = sm.vertices; //new Vector3[sm.vertexCount];
}
}
}
if ( targetIsSkin )
{
if ( boneweights == null || boneweights.Length == 0 )
targetIsSkin = false;
}
neededVerts.Clear();
verts = mesh.vertices;
startverts = mesh.vertices;
freeverts = new Vector3[startverts.Length];
Vector3[] baseverts = modobj.verts; //basemesh.vertices;
int[] basefaces = modobj.tris; //basemesh.triangles;
bindverts = new MegaBindVert[verts.Length];
// matrix to get vertex into local space of target
Matrix4x4 tm = transform.localToWorldMatrix * modobj.transform.worldToLocalMatrix;
List<MegaCloseFace> closefaces = new List<MegaCloseFace>();
Vector3 p0 = Vector3.zero;
Vector3 p1 = Vector3.zero;
Vector3 p2 = Vector3.zero;
for ( int i = 0; i < verts.Length; i++ )
{
MegaBindVert bv = new MegaBindVert();
bindverts[i] = bv;
Vector3 p = tm.MultiplyPoint(verts[i]);
p = transform.TransformPoint(verts[i]);
p = modobj.transform.InverseTransformPoint(p);
freeverts[i] = p;
closefaces.Clear();
for ( int t = 0; t < basefaces.Length; t += 3 )
{
if ( targetIsSkin && !sourceIsSkin )
{
p0 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t]));
p1 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t + 1]));
p2 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t + 2]));
}
else
{
p0 = baseverts[basefaces[t]];
p1 = baseverts[basefaces[t + 1]];
p2 = baseverts[basefaces[t + 2]];
}
float dist = GetDistance(p, p0, p1, p2);
if ( Mathf.Abs(dist) < maxdist )
{
MegaCloseFace cf = new MegaCloseFace();
cf.dist = Mathf.Abs(dist);
cf.face = t;
bool inserted = false;
for ( int k = 0; k < closefaces.Count; k++ )
{
if ( cf.dist < closefaces[k].dist )
{
closefaces.Insert(k, cf);
inserted = true;
break;
}
}
if ( !inserted )
closefaces.Add(cf);
}
}
float tweight = 0.0f;
int maxp = maxpoints;
if ( maxp == 0 )
maxp = closefaces.Count;
for ( int j = 0; j < maxp; j++ )
{
if ( j < closefaces.Count )
{
int t = closefaces[j].face;
if ( targetIsSkin && !sourceIsSkin )
{
p0 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t]));
p1 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t + 1]));
p2 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t + 2]));
}
else
{
p0 = baseverts[basefaces[t]];
p1 = baseverts[basefaces[t + 1]];
p2 = baseverts[basefaces[t + 2]];
}
Vector3 normal = FaceNormal(p0, p1, p2);
float dist = closefaces[j].dist; //GetDistance(p, p0, p1, p2);
MegaBindInf bi = new MegaBindInf();
bi.dist = GetPlaneDistance(p, p0, p1, p2); //dist;
bi.face = t;
bi.i0 = basefaces[t];
bi.i1 = basefaces[t + 1];
bi.i2 = basefaces[t + 2];
bi.bary = CalcBary(p, p0, p1, p2);
bi.weight = 1.0f / (1.0f + dist);
bi.area = normal.magnitude * 0.5f; //CalcArea(baseverts[basefaces[t]], baseverts[basefaces[t + 1]], baseverts[basefaces[t + 2]]); // Could calc once at start
tweight += bi.weight;
bv.verts.Add(bi);
}
}
if ( maxpoints > 0 && maxpoints < bv.verts.Count )
bv.verts.RemoveRange(maxpoints, bv.verts.Count - maxpoints);
// Only want to calculate skin vertices we use
if ( !sourceIsSkin && targetIsSkin )
{
for ( int fi = 0; fi < bv.verts.Count; fi++ )
{
if ( !neededVerts.Contains(bv.verts[fi].i0) )
neededVerts.Add(bv.verts[fi].i0);
if ( !neededVerts.Contains(bv.verts[fi].i1) )
neededVerts.Add(bv.verts[fi].i1);
if ( !neededVerts.Contains(bv.verts[fi].i2) )
neededVerts.Add(bv.verts[fi].i2);
}
}
if ( tweight == 0.0f )
nomapcount++;
bv.weight = tweight;
}
}
void LateUpdate()
{
DoUpdate();
}
public Vector3 GetSkinPos(int i)
{
Vector3 pos = target.sverts[i];
Vector3 bpos = bindposes[boneweights[i].boneIndex0].MultiplyPoint(pos);
Vector3 p = bones[boneweights[i].boneIndex0].TransformPoint(bpos) * boneweights[i].weight0;
bpos = bindposes[boneweights[i].boneIndex1].MultiplyPoint(pos);
p += bones[boneweights[i].boneIndex1].TransformPoint(bpos) * boneweights[i].weight1;
bpos = bindposes[boneweights[i].boneIndex2].MultiplyPoint(pos);
p += bones[boneweights[i].boneIndex2].TransformPoint(bpos) * boneweights[i].weight2;
bpos = bindposes[boneweights[i].boneIndex3].MultiplyPoint(pos);
p += bones[boneweights[i].boneIndex3].TransformPoint(bpos) * boneweights[i].weight3;
return p;
}
Vector3 gcp = Vector3.zero;
public Vector3 GetCoordMine(Vector3 A, Vector3 B, Vector3 C, Vector3 bary)
{
//Vector3 p = Vector3.zero;
gcp.x = (bary.x * A.x) + (bary.y * B.x) + (bary.z * C.x);
gcp.y = (bary.x * A.y) + (bary.y * B.y) + (bary.z * C.y);
gcp.z = (bary.x * A.z) + (bary.y * B.z) + (bary.z * C.z);
return gcp;
}
SkinnedMeshRenderer tmesh;
#if UNITY_5 || UNITY_6
Mesh bakedmesh = null;
#endif
void DoUpdate()
{
if ( WrapEnabled == false || target == null || bindverts == null ) //|| bindposes == null )
return;
if ( mesh == null )
SetMesh();
if ( mesh == null )
return;
if ( targetIsSkin && neededVerts != null && neededVerts.Count > 0 ) //|| (targetIsSkin && boneweights == null) )
{
if ( boneweights == null || tmesh == null )
{
tmesh = (SkinnedMeshRenderer)target.GetComponent(typeof(SkinnedMeshRenderer));
if ( tmesh != null )
{
if ( !sourceIsSkin )
{
Mesh sm = tmesh.sharedMesh;
bindposes = sm.bindposes;
bones = tmesh.bones;
boneweights = sm.boneWeights;
}
}
}
#if UNITY_5 || UNITY_6
if ( tmesh == null )
tmesh = (SkinnedMeshRenderer)target.GetComponent(typeof(SkinnedMeshRenderer));
if ( UseBakedMesh )
{
if ( bakedmesh == null )
bakedmesh = new Mesh();
tmesh.BakeMesh(bakedmesh);
skinnedVerts = bakedmesh.vertices;
}
else
{
for ( int i = 0; i < neededVerts.Count; i++ )
skinnedVerts[neededVerts[i]] = GetSkinPos(neededVerts[i]);
}
#else
for ( int i = 0; i < neededVerts.Count; i++ )
skinnedVerts[neededVerts[i]] = GetSkinPos(neededVerts[i]);
#endif
}
Matrix4x4 stm = Matrix4x4.identity;
Vector3 p = Vector3.zero;
if ( targetIsSkin && !sourceIsSkin )
{
#if UNITY_5 || UNITY_6
if ( UseBakedMesh )
stm = transform.worldToLocalMatrix * target.transform.localToWorldMatrix; // * transform.worldToLocalMatrix;
else
stm = transform.worldToLocalMatrix; // * target.transform.localToWorldMatrix; // * transform.worldToLocalMatrix;
#else
stm = transform.worldToLocalMatrix; // * target.transform.localToWorldMatrix; // * transform.worldToLocalMatrix;
#endif
for ( int i = 0; i < bindverts.Length; i++ )
{
if ( bindverts[i].verts.Count > 0 )
{
p = Vector3.zero;
float oow = 1.0f / bindverts[i].weight;
int cnt = bindverts[i].verts.Count;
for ( int j = 0; j < cnt; j++ )
{
MegaBindInf bi = bindverts[i].verts[j];
Vector3 p0 = skinnedVerts[bi.i0];
Vector3 p1 = skinnedVerts[bi.i1];
Vector3 p2 = skinnedVerts[bi.i2];
Vector3 cp = GetCoordMine(p0, p1, p2, bi.bary);
Vector3 norm = FaceNormal(p0, p1, p2);
float sq = 1.0f / Mathf.Sqrt(norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
float d = (bi.dist * shrink) + gap;
//cp += d * norm.x;
cp.x += d * norm.x * sq;
cp.y += d * norm.y * sq;
cp.z += d * norm.z * sq;
float bw = bi.weight * oow;
if ( j == 0 )
{
p.x = cp.x * bw;
p.y = cp.y * bw;
p.z = cp.z * bw;
}
else
{
p.x += cp.x * bw;
p.y += cp.y * bw;
p.z += cp.z * bw;
}
//cp += ((bi.dist * shrink) + gap) * norm.normalized;
//p += cp * (bi.weight / bindverts[i].weight);
}
Vector3 pp = stm.MultiplyPoint3x4(p);
verts[i].x = pp.x + offset.x;
verts[i].y = pp.y + offset.y;
verts[i].z = pp.z + offset.z;
//verts[i] = transform.InverseTransformPoint(p) + offset;
}
}
}
else
{
stm = transform.worldToLocalMatrix; // * target.transform.localToWorldMatrix; // * transform.worldToLocalMatrix;
for ( int i = 0; i < bindverts.Length; i++ )
{
if ( bindverts[i].verts.Count > 0 )
{
p = Vector3.zero;
float oow = 1.0f / bindverts[i].weight;
for ( int j = 0; j < bindverts[i].verts.Count; j++ )
{
MegaBindInf bi = bindverts[i].verts[j];
Vector3 p0 = target.sverts[bi.i0];
Vector3 p1 = target.sverts[bi.i1];
Vector3 p2 = target.sverts[bi.i2];
Vector3 cp = GetCoordMine(p0, p1, p2, bi.bary);
Vector3 norm = FaceNormal(p0, p1, p2);
float sq = 1.0f / Mathf.Sqrt(norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
float d = (bi.dist * shrink) + gap;
//cp += d * norm.x;
cp.x += d * norm.x * sq;
cp.y += d * norm.y * sq;
cp.z += d * norm.z * sq;
float bw = bi.weight * oow;
if ( j == 0 )
{
p.x = cp.x * bw;
p.y = cp.y * bw;
p.z = cp.z * bw;
}
else
{
p.x += cp.x * bw;
p.y += cp.y * bw;
p.z += cp.z * bw;
}
//cp += ((bi.dist * shrink) + gap) * norm.normalized;
//p += cp * (bi.weight / bindverts[i].weight);
}
}
else
p = freeverts[i]; //startverts[i];
Vector3 pp = stm.MultiplyPoint3x4(p);
verts[i].x = pp.x + offset.x;
verts[i].y = pp.y + offset.y;
verts[i].z = pp.z + offset.z;
//p = target.transform.TransformPoint(p);
//verts[i] = transform.InverseTransformPoint(p) + offset;
}
}
mesh.vertices = verts;
RecalcNormals();
mesh.RecalculateBounds();
}
public MegaNormMap[] mapping;
public int[] tris;
public Vector3[] facenorms;
public Vector3[] norms;
int[] FindFacesUsing(Vector3 p, Vector3 n)
{
List<int> faces = new List<int>();
Vector3 v = Vector3.zero;
for ( int i = 0; i < tris.Length; i += 3 )
{
v = verts[tris[i]];
if ( v.x == p.x && v.y == p.y && v.z == p.z )
{
if ( n.Equals(norms[tris[i]]) )
faces.Add(i / 3);
}
else
{
v = verts[tris[i + 1]];
if ( v.x == p.x && v.y == p.y && v.z == p.z )
{
if ( n.Equals(norms[tris[i + 1]]) )
faces.Add(i / 3);
}
else
{
v = verts[tris[i + 2]];
if ( v.x == p.x && v.y == p.y && v.z == p.z )
{
if ( n.Equals(norms[tris[i + 2]]) )
faces.Add(i / 3);
}
}
}
}
return faces.ToArray();
}
// Should call this from inspector when we change to mega
public void BuildNormalMapping(Mesh mesh, bool force)
{
if ( mapping == null || mapping.Length == 0 || force )
{
// so for each normal we have a vertex, so find all faces that share that vertex
tris = mesh.triangles;
norms = mesh.normals;
facenorms = new Vector3[tris.Length / 3];
mapping = new MegaNormMap[verts.Length];
for ( int i = 0; i < verts.Length; i++ )
{
mapping[i] = new MegaNormMap();
mapping[i].faces = FindFacesUsing(verts[i], norms[i]);
}
}
}
public void RecalcNormals()
{
if ( NormalMethod == MegaNormalMethod.Unity ) //|| mapping == null )
mesh.RecalculateNormals();
else
{
if ( mapping == null )
BuildNormalMapping(mesh, false);
RecalcNormals(mesh, verts);
}
}
public void RecalcNormals(Mesh ms, Vector3[] _verts)
{
int index = 0;
Vector3 v30 = Vector3.zero;
Vector3 v31 = Vector3.zero;
Vector3 v32 = Vector3.zero;
Vector3 va = Vector3.zero;
Vector3 vb = Vector3.zero;
for ( int f = 0; f < tris.Length; f += 3 )
{
v30 = _verts[tris[f]];
v31 = _verts[tris[f + 1]];
v32 = _verts[tris[f + 2]];
va.x = v31.x - v30.x;
va.y = v31.y - v30.y;
va.z = v31.z - v30.z;
vb.x = v32.x - v31.x;
vb.y = v32.y - v31.y;
vb.z = v32.z - v31.z;
v30.x = va.y * vb.z - va.z * vb.y;
v30.y = va.z * vb.x - va.x * vb.z;
v30.z = va.x * vb.y - va.y * vb.x;
// Uncomment this if you dont want normals weighted by poly size
//float l = v30.x * v30.x + v30.y * v30.y + v30.z * v30.z;
//l = 1.0f / Mathf.Sqrt(l);
//v30.x *= l;
//v30.y *= l;
//v30.z *= l;
facenorms[index++] = v30;
}
for ( int n = 0; n < norms.Length; n++ )
{
if ( mapping[n].faces.Length > 0 )
{
Vector3 norm = facenorms[mapping[n].faces[0]];
for ( int i = 1; i < mapping[n].faces.Length; i++ )
{
v30 = facenorms[mapping[n].faces[i]];
norm.x += v30.x;
norm.y += v30.y;
norm.z += v30.z;
}
float l = norm.x * norm.x + norm.y * norm.y + norm.z * norm.z;
l = 1.0f / Mathf.Sqrt(l);
norm.x *= l;
norm.y *= l;
norm.z *= l;
norms[n] = norm;
}
else
norms[n] = Vector3.up;
}
ms.normals = norms;
}
}
| |
//---------------------------------------------------------------------
// <copyright file="UpdatableWrapper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Wraps all the calls to IUpdatable interface.
// </summary>
//
// @owner [....]
//---------------------------------------------------------------------
namespace System.Data.Services
{
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Data.Services.Providers;
/// <summary>
/// This class wraps all the calls to IUpdatable interface.
/// </summary>
internal class UpdatableWrapper
{
/// <summary> instance implementation of IUpdatable.</summary>
private IUpdatable updateProvider;
/// <summary> data service instance.</summary>
private IDataService service;
/// <summary>
/// creates an instance of UpdatableWrapper, which wraps all the calls to IUpdatable interface.
/// </summary>
/// <param name="serviceInstance">instance of the data service.</param>
internal UpdatableWrapper(IDataService serviceInstance)
{
this.service = serviceInstance;
}
/// <summary>
/// Get the instance of IUpdatable.
/// </summary>
private IUpdatable UpdateProvider
{
get
{
if (this.updateProvider == null)
{
// We need to call IUpdatable only for V1 providers. For ObjectContextServiceProvider, this always returns null.
// Hence basically, this call is only for reflection service provider.
if (this.service.Provider.IsV1Provider)
{
this.updateProvider = this.service.Provider.GetService<IUpdatable>((IDataService)this.service.Instance);
}
if (this.updateProvider == null)
{
this.updateProvider = this.service.Provider.GetService<IDataServiceUpdateProvider>((IDataService)this.service.Instance);
}
}
if (this.updateProvider == null)
{
if (this.service.Provider.IsV1Provider)
{
throw DataServiceException.CreateMethodNotImplemented(Strings.UpdatableWrapper_MissingIUpdatableForV1Provider);
}
else
{
throw DataServiceException.CreateMethodNotImplemented(Strings.UpdatableWrapper_MissingUpdateProviderInterface);
}
}
return this.updateProvider;
}
}
/// <summary>
/// Creates the resource of the given type and belonging to the given container
/// </summary>
/// <param name="containerName">container name to which the resource needs to be added</param>
/// <param name="fullTypeName">full type name i.e. Namespace qualified type name of the resource</param>
/// <returns>object representing a resource of given type and belonging to the given container</returns>
internal object CreateResource(string containerName, string fullTypeName)
{
// container name can be null for complex types
// type name can be null when we don't know the type - e.g. DELETE /Customers(1)
// In case of inheritance we don't know the actual type of customer instance.
object resource = this.UpdateProvider.CreateResource(containerName, fullTypeName);
if (resource == null)
{
throw new InvalidOperationException(Strings.BadProvider_CreateResourceReturnedNull);
}
return resource;
}
/// <summary>
/// Gets the resource of the given type that the query points to
/// </summary>
/// <param name="query">query pointing to a particular resource</param>
/// <param name="fullTypeName">full type name i.e. Namespace qualified type name of the resource</param>
/// <returns>object representing a resource of given type and as referenced by the query</returns>
internal object GetResource(IQueryable query, string fullTypeName)
{
Debug.Assert(query != null, "query != null");
try
{
// TypeName can be null since for open types, we may not know the type yet.
return this.UpdateProvider.GetResource(query, fullTypeName);
}
catch (ArgumentException e)
{
throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidUriSpecified, e);
}
}
/// <summary>
/// Resets the value of the given resource to its default value
/// </summary>
/// <param name="resource">resource whose value needs to be reset</param>
/// <returns>same resource with its value reset</returns>
internal object ResetResource(object resource)
{
Debug.Assert(resource != null, "resource != null");
object resetResource = this.UpdateProvider.ResetResource(resource);
if (resetResource == null)
{
throw new InvalidOperationException(Strings.BadProvider_ResetResourceReturnedNull);
}
return resetResource;
}
/// <summary>
/// If the provider implements IConcurrencyProvider, then this method passes the etag values
/// to the provider, otherwise compares the etag itself.
/// </summary>
/// <param name="resourceCookie">etag values for the given resource.</param>
/// <param name="container">container for the given resource.</param>
internal void SetETagValues(object resourceCookie, ResourceSetWrapper container)
{
Debug.Assert(resourceCookie != null, "resourceCookie != null");
Debug.Assert(container != null, "container != null");
DataServiceHostWrapper host = this.service.OperationContext.Host;
Debug.Assert(String.IsNullOrEmpty(host.RequestIfNoneMatch), "IfNoneMatch header cannot be specified for Update/Delete operations");
// Resolve the cookie first to the actual resource type
object actualEntity = this.ResolveResource(resourceCookie);
Debug.Assert(actualEntity != null, "actualEntity != null");
ResourceType resourceType = WebUtil.GetNonPrimitiveResourceType(this.service.Provider, actualEntity);
Debug.Assert(resourceType != null, "resourceType != null");
IList<ResourceProperty> etagProperties = this.service.Provider.GetETagProperties(container.Name, resourceType);
if (etagProperties.Count == 0)
{
if (!String.IsNullOrEmpty(host.RequestIfMatch))
{
throw DataServiceException.CreateBadRequestError(Strings.Serializer_NoETagPropertiesForType);
}
// If the type has no etag properties, then we do not need to do any etag checks
return;
}
// If the provider implements IConcurrencyProvider, then we need to call the provider
// and pass the etag values. Else, we need to compare the etag values ourselves.
IDataServiceUpdateProvider concurrencyProvider = this.updateProvider as IDataServiceUpdateProvider;
if (concurrencyProvider != null)
{
bool? checkForEquality = null;
IEnumerable<KeyValuePair<string, object>> etagValues = null;
if (!String.IsNullOrEmpty(host.RequestIfMatch))
{
checkForEquality = true;
etagValues = ParseETagValue(etagProperties, host.RequestIfMatch);
}
else
{
etagValues = new KeyValuePair<string, object>[0];
}
concurrencyProvider.SetConcurrencyValues(resourceCookie, checkForEquality, etagValues);
}
else if (String.IsNullOrEmpty(host.RequestIfMatch))
{
throw DataServiceException.CreateBadRequestError(Strings.DataService_CannotPerformOperationWithoutETag(resourceType.FullName));
}
else if (host.RequestIfMatch != XmlConstants.HttpAnyETag)
{
// Compare If-Match header value with the current etag value, if the If-Match header value is not equal to '*'
string etagValue = WebUtil.GetETagValue(resourceCookie, resourceType, etagProperties, this.service, false /*getMethod*/);
Debug.Assert(!String.IsNullOrEmpty(etagValue), "etag value can never be null");
if (etagValue != host.RequestIfMatch)
{
throw DataServiceException.CreatePreConditionFailedError(Strings.Serializer_ETagValueDoesNotMatch);
}
}
}
/// <summary>
/// Sets the value of the given property on the target object
/// </summary>
/// <param name="targetResource">target object which defines the property</param>
/// <param name="propertyName">name of the property whose value needs to be updated</param>
/// <param name="propertyValue">value of the property</param>
internal void SetValue(object targetResource, string propertyName, object propertyValue)
{
Debug.Assert(targetResource != null, "targetResource != null");
Debug.Assert(!String.IsNullOrEmpty(propertyName), "!String.IsNullOrEmpty(propertyName)");
this.UpdateProvider.SetValue(targetResource, propertyName, propertyValue);
}
/// <summary>
/// Gets the value of the given property on the target object
/// </summary>
/// <param name="targetResource">target object which defines the property</param>
/// <param name="propertyName">name of the property whose value needs to be updated</param>
/// <returns>the value of the property for the given target resource</returns>
internal object GetValue(object targetResource, string propertyName)
{
Debug.Assert(targetResource != null, "targetResource != null");
Debug.Assert(!String.IsNullOrEmpty(propertyName), "!String.IsNullOrEmpty(propertyName)");
return this.UpdateProvider.GetValue(targetResource, propertyName);
}
/// <summary>
/// Sets the value of the given reference property on the target object
/// </summary>
/// <param name="targetResource">target object which defines the property</param>
/// <param name="propertyName">name of the property whose value needs to be updated</param>
/// <param name="propertyValue">value of the property</param>
internal void SetReference(object targetResource, string propertyName, object propertyValue)
{
Debug.Assert(targetResource != null, "targetResource != null");
Debug.Assert(!String.IsNullOrEmpty(propertyName), "!String.IsNullOrEmpty(propertyName)");
this.UpdateProvider.SetReference(targetResource, propertyName, propertyValue);
}
/// <summary>
/// Adds the given value to the collection
/// </summary>
/// <param name="targetResource">target object which defines the property</param>
/// <param name="propertyName">name of the property whose value needs to be updated</param>
/// <param name="resourceToBeAdded">value of the property which needs to be added</param>
internal void AddReferenceToCollection(object targetResource, string propertyName, object resourceToBeAdded)
{
Debug.Assert(targetResource != null, "targetResource != null");
Debug.Assert(!String.IsNullOrEmpty(propertyName), "!String.IsNullOrEmpty(propertyName)");
this.UpdateProvider.AddReferenceToCollection(targetResource, propertyName, resourceToBeAdded);
}
/// <summary>
/// Removes the given value from the collection
/// </summary>
/// <param name="targetResource">target object which defines the property</param>
/// <param name="propertyName">name of the property whose value needs to be updated</param>
/// <param name="resourceToBeRemoved">value of the property which needs to be removed</param>
internal void RemoveReferenceFromCollection(object targetResource, string propertyName, object resourceToBeRemoved)
{
Debug.Assert(targetResource != null, "targetResource != null");
Debug.Assert(!String.IsNullOrEmpty(propertyName), "!String.IsNullOrEmpty(propertyName)");
this.UpdateProvider.RemoveReferenceFromCollection(targetResource, propertyName, resourceToBeRemoved);
}
/// <summary>
/// Delete the given resource
/// </summary>
/// <param name="targetResource">resource that needs to be deleted</param>
internal void DeleteResource(object targetResource)
{
Debug.Assert(targetResource != null, "targetResource != null");
this.UpdateProvider.DeleteResource(targetResource);
}
/// <summary>
/// Saves all the pending changes made till now
/// </summary>
internal void SaveChanges()
{
this.UpdateProvider.SaveChanges();
}
/// <summary>
/// Returns the actual instance of the resource represented by the given resource object
/// </summary>
/// <param name="resource">object representing the resource whose instance needs to be fetched</param>
/// <returns>The actual instance of the resource represented by the given resource object</returns>
internal object ResolveResource(object resource)
{
Debug.Assert(resource != null, "resource != null");
object resolvedResource = this.UpdateProvider.ResolveResource(resource);
if (resolvedResource == null)
{
throw new InvalidOperationException(Strings.BadProvider_ResolveResourceReturnedNull);
}
return resolvedResource;
}
/// <summary>
/// Revert all the pending changes.
/// </summary>
internal void ClearChanges()
{
this.UpdateProvider.ClearChanges();
}
/// <summary>
/// Dispose the update provider instance
/// </summary>
internal void DisposeProvider()
{
if (this.updateProvider != null)
{
WebUtil.Dispose(this.updateProvider);
this.updateProvider = null;
}
}
/// <summary>
/// Parse the given etag value in the If-Match request header.
/// </summary>
/// <param name="etagProperties">List of etag properties for the type whose etag values we are parsing.</param>
/// <param name="ifMatchHeaderValue">value of the If-Match header as specified in the request.</param>
/// <returns>returns the etag value as a list containing the property name and its corresponding value. If the If-Match header value is '*', then returns an empty collection.</returns>
private static IEnumerable<KeyValuePair<string, object>> ParseETagValue(IList<ResourceProperty> etagProperties, string ifMatchHeaderValue)
{
Debug.Assert(etagProperties != null && etagProperties.Count != 0, "There must be atleast one etag property specified");
Debug.Assert(!String.IsNullOrEmpty(ifMatchHeaderValue), "IfMatch header cannot be null");
if (ifMatchHeaderValue == XmlConstants.HttpAnyETag)
{
// if the value is '*', then we return an empty IEnumerable.
return new KeyValuePair<string, object>[0];
}
Debug.Assert(ifMatchHeaderValue.StartsWith(XmlConstants.HttpWeakETagPrefix, StringComparison.Ordinal), "If-Match header must be properly formatted - this check is done in DataService.CheckETagValues method");
Debug.Assert(ifMatchHeaderValue.Length >= XmlConstants.HttpWeakETagPrefix.Length + 1, "If-Match header must be properly formatted - this check is done in DataService.CheckETagValues method");
// Just get the etag value - we need to ignore the 'W/"' and the last '"' character from the etag
string strippedETag = ifMatchHeaderValue.Substring(XmlConstants.HttpWeakETagPrefix.Length, ifMatchHeaderValue.Length - XmlConstants.HttpWeakETagPrefix.Length - 1);
KeyInstance keyInstance = null;
bool success;
Exception innerException = null;
// In V1, when we didn't have IConcurrencyProvider interface, we always used to compute the
// latest etag from the entity instance we got from IUpdatable.GetResource and then comparing
// it with the If-Match request header. Hence all invalid cases always used to throw
// DataServiceException with 412, since the etags didn't match.
// In V1.5, we have added the support for IConcurrencyProvider, which means we need to parse
// the etag values and parse it to the provider, if it has implement this interface. To avoid
// breaking changes, we need to catch all parsing errors and report them as 412 instead of 400
// to avoid it from becoming a breaking change.
try
{
success = KeyInstance.TryParseNullableTokens(Uri.UnescapeDataString(strippedETag), out keyInstance);
}
catch (DataServiceException e)
{
success = false;
innerException = e;
}
if (!success)
{
// We could have throwed BadRequest here since the etag value is not properly formattted. But since
// we used to do throw 412 in V1, keeping it that way to avoid breaking change.
throw DataServiceException.CreatePreConditionFailedError(Strings.Serializer_ETagValueDoesNotMatch, innerException);
}
if (keyInstance.PositionalValues.Count != etagProperties.Count)
{
// We could have throwed BadRequest here since the etag value is not properly formattted. But since
// we used to do throw 412 in V1, keeping it that way to avoid breaking change.
throw DataServiceException.CreatePreConditionFailedError(Strings.Serializer_ETagValueDoesNotMatch);
}
KeyValuePair<string, object>[] etagPropertyInfo = new KeyValuePair<string, object>[etagProperties.Count];
for (int i = 0; i < etagPropertyInfo.Length; i++)
{
ResourceProperty etagProperty = etagProperties[i];
object propertyValue = null;
string value = (string)keyInstance.PositionalValues[i];
if (value != XmlConstants.NullLiteralInETag)
{
// The reason we need to catch the Overflow Exception here is because of the Bug #679728.
// In V1, when we didn't have IConcurrencyProvider interface, we always used to compute the
// latest etag from the entity instance we got from IUpdatable.GetResource and then comparing
// it with the If-Match request header. Hence all invalid cases always used to throw
// DataServiceException with 412, since the etags didn't match.
// In V1.5, we have added the support for IConcurrencyProvider, which means we need to parse
// the etag values and parse it to the provider, if it has implement this interface. To avoid
// breaking changes, we need to catch all parsing errors and report them as 412 instead of 400
// to avoid it from becoming a breaking change.
try
{
success = System.Data.Services.Parsing.WebConvert.TryKeyStringToPrimitive(value, etagProperty.Type, out propertyValue);
}
catch (OverflowException e)
{
success = false;
innerException = e;
}
if (!success)
{
// We could have throwed BadRequest here since the etag value is not properly formattted. But since
// we used to do throw 412 in V1, keeping it that way to avoid breaking change.
throw DataServiceException.CreatePreConditionFailedError(Strings.Serializer_ETagValueDoesNotMatch, innerException);
}
}
etagPropertyInfo[i] = new KeyValuePair<string, object>(etagProperties[i].Name, propertyValue);
}
return etagPropertyInfo;
}
}
}
| |
// Copyright 2020, 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.
using Google.Api.Gax;
using Google.Cloud.EntityFrameworkCore.Spanner.Storage.Internal;
using Google.Cloud.Spanner.Data;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Update;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.EntityFrameworkCore.Spanner.Update.Internal
{
/// <summary>
/// This is internal functionality and not intended for public use.
///
/// SpannerModificationCommandBatch will by default execute updates using mutations when implicit
/// transactions are being used, and DML when explicit transactions are being used. Using DML for
/// explicit transactions allows the transaction to read its own writes. Using mutations for implicit
/// transactions is more efficient, as mutations are faster than DML and implicit transactions imply
/// that read-your-writes is not needed.
///
/// Client applications can configure mutation usage when creating a DbContext to change the default
/// behavior:
/// * MutationUsage.ImplicitTransactions (default): Use mutations when implicit transactions are used.
/// * Never: Never use mutations and always use DML. This will reduce the performance of implicit transactions.
/// * Always: Always use mutations, also for explicit transactions. This will break read-your-writes in transactions.
/// </summary>
internal sealed class SpannerModificationCommandBatch : ModificationCommandBatch
{
private readonly IRelationalTypeMappingSource _typeMapper;
private readonly List<ModificationCommand> _modificationCommands = new List<ModificationCommand>();
private readonly List<SpannerRetriableCommand> _propagateResultsCommands = new List<SpannerRetriableCommand>();
private readonly char _statementTerminator;
private readonly bool _hasExplicitTransaction;
/// <summary>
/// This is internal functionality and not intended for public use.
/// </summary>
public SpannerModificationCommandBatch(
[NotNull] ModificationCommandBatchFactoryDependencies dependencies,
IRelationalTypeMappingSource typeMapper)
{
Dependencies = dependencies;
_typeMapper = typeMapper;
// This class needs a statement terminator because the EFCore built-in SQL generator helper
// will generate multiple statements as one string.
_statementTerminator = ';';
_hasExplicitTransaction = dependencies.CurrentContext.Context.Database.CurrentTransaction != null;
}
/// <summary>
/// Service dependencies.
/// </summary>
public ModificationCommandBatchFactoryDependencies Dependencies { get; }
/// <summary>
/// This is internal functionality and not intended for public use.
/// </summary>
public override IReadOnlyList<ModificationCommand> ModificationCommands => _modificationCommands;
/// <summary>
/// The affected rows per modification command in this batch. This property is only valid after the batch has been executed.
/// </summary>
internal List<long> UpdateCounts { get; private set; } = new List<long>();
internal int RowsAffected
{
// This ensures that the deletion of a record in a parent table that also cascades to
// one or more child tables is still only counted as one mutation.
get => UpdateCounts.Select(c => c == 0L ? 0 : 1).Sum();
}
/// <summary>
/// Creates the <see cref="IRelationalValueBufferFactory" /> that will be used for creating a
/// <see cref="ValueBuffer" /> to consume the data reader.
/// </summary>
/// <param name="columnModifications">
/// The list of <see cref="ColumnModification" />s for all the columns
/// being modified such that a ValueBuffer with appropriate slots can be created.
/// </param>
/// <returns> The factory. </returns>
private IRelationalValueBufferFactory CreateValueBufferFactory(
[NotNull] IReadOnlyList<ColumnModification> columnModifications)
=> Dependencies.ValueBufferFactoryFactory
.Create(
columnModifications
.Where(c => c.IsRead)
.Select(c => new TypeMaterializationInfo(c.Property.ClrType, c.Property, _typeMapper))
.ToArray());
/// <summary>
/// This is internal functionality and not intended for public use.
/// </summary>
public override bool AddCommand(ModificationCommand modificationCommand)
{
if (SpannerPendingCommitTimestampModificationCommand.HasCommitTimestampColumn(modificationCommand))
{
_modificationCommands.Add(new SpannerPendingCommitTimestampModificationCommand(modificationCommand, Dependencies.Logger.ShouldLogSensitiveData()));
}
else
{
_modificationCommands.Add(modificationCommand);
}
return true;
}
/// <summary>
/// This is internal functionality and not intended for public use.
/// </summary>
public override void Execute(IRelationalConnection connection)
{
Task.Run(() => ExecuteAsync(connection)).WaitWithUnwrappedExceptions();
}
/// <summary>
/// This is internal functionality and not intended for public use.
/// </summary>
public override async Task ExecuteAsync(IRelationalConnection connection,
CancellationToken cancellationToken = default)
{
var spannerRelationalConnection = (SpannerRelationalConnection)connection;
var spannerConnection = (SpannerRetriableConnection)connection.DbConnection;
// There should always be a transaction:
// 1. Implicit: A transaction is automatically started by Entity Framework when SaveChanges() is called.
// 2. Explicit: The client application has called BeginTransaction() on the database.
if (!(connection.CurrentTransaction?.GetDbTransaction() is SpannerRetriableTransaction transaction))
{
throw new InvalidOperationException("There is no active transaction. Cloud Spanner does not support executing updates without a transaction.");
}
var useMutations = spannerRelationalConnection.MutationUsage == Infrastructure.MutationUsage.Always
|| (!_hasExplicitTransaction && spannerRelationalConnection.MutationUsage == Infrastructure.MutationUsage.ImplicitTransactions);
if (useMutations)
{
await ExecuteMutationsAsync(spannerConnection, transaction, cancellationToken);
}
else
{
await ExecuteDmlAsync(spannerConnection, transaction, cancellationToken);
}
}
/// <summary>
/// Executes the command batch using mutations. Mutations are more efficient than DML, but do not support read-your-writes.
/// Mutations are therefore by default only used for implicit transactions, but client applications can configure the Spanner
/// Entity Framework provider to use mutations for explicit transactions as well.
/// </summary>
private async Task ExecuteMutationsAsync(
SpannerRetriableConnection spannerConnection, SpannerRetriableTransaction transaction, CancellationToken cancellationToken)
{
int index = 0;
foreach (var modificationCommand in _modificationCommands)
{
// We assume that each mutation will affect exactly one row. This assumption always holds for INSERT
// and UPDATE mutations (unless they return an error). DELETE mutations could affect zero rows if the
// row had already been deleted, and more than one row if the deleted row is in a table with one or
// more INTERLEAVED tables that are defined with ON DELETE CASCADE.
//
// This can be changed if a concurrency token check fails.
var updateCount = 1L;
// Concurrency token checks cannot be included in mutations. Instead, we need to do manual select to check
// that the concurrency token is still the same as what we expect. This select is executed in the same
// transaction as the mutations, so it is guaranteed that the value that we read here will still be valid
// when the mutations are committed.
var operations = modificationCommand.ColumnModifications;
var hasConcurrencyCondition = operations.Where(o => o.IsCondition && o.IsConcurrencyToken).Any();
if (hasConcurrencyCondition)
{
var conditionOperations = operations.Where(o => o.IsCondition).ToList();
var concurrencySql = ((SpannerUpdateSqlGenerator)Dependencies.UpdateSqlGenerator).GenerateSelectConcurrencyCheckSql(modificationCommand.TableName, conditionOperations);
var concurrencyCommand = spannerConnection.CreateSelectCommand(concurrencySql);
concurrencyCommand.Transaction = transaction;
foreach (var columnModification in conditionOperations)
{
concurrencyCommand.Parameters.Add(CreateParameter(columnModification, concurrencyCommand, UseValue.Original, false));
}
// Execute the concurrency check query in the read/write transaction and check whether the expected row exists.
using var reader = await concurrencyCommand.ExecuteReaderAsync(cancellationToken);
if (!await reader.ReadAsync(cancellationToken))
{
// Set the update count to 0 to trigger a concurrency exception.
// We do not throw the exception here already, as there might be more concurrency problems,
// and we want to be able to report all in the exception.
updateCount = 0L;
}
}
// Mutation commands must use a specific TIMESTAMP constant for pending commit timestamps instead of the
// placeholder string PENDING_COMMIT_TIMESTAMP(). This instructs any pending commit timestamp modifications
// to use the mutation constant instead.
if (modificationCommand is SpannerPendingCommitTimestampModificationCommand commitTimestampModificationCommand)
{
commitTimestampModificationCommand.MarkAsMutationCommand();
transaction.AddSpannerPendingCommitTimestampModificationCommand(commitTimestampModificationCommand);
}
// Create the mutation command and execute it.
var cmd = CreateSpannerMutationCommand(spannerConnection, transaction, modificationCommand);
// Note: The following line does not actually execute any command on the backend, it only buffers
// the mutation locally to be sent with the next Commit statement.
await cmd.ExecuteNonQueryAsync(cancellationToken);
UpdateCounts.Add(updateCount);
// Check whether we need to generate a SELECT command to propagate computed values back to the context.
// This SELECT command will be executed outside of the current implicit transaction.
// The propagation query is skipped if the batch uses an explicit transaction, as it will not be able
// to read the new value anyways.
if (modificationCommand.RequiresResultPropagation && !_hasExplicitTransaction)
{
var keyOperations = operations.Where(o => o.IsKey).ToList();
var readOperations = operations.Where(o => o.IsRead).ToList();
var sql = ((SpannerUpdateSqlGenerator)Dependencies.UpdateSqlGenerator).GenerateSelectAffectedSql(
modificationCommand.TableName, modificationCommand.Schema, readOperations, keyOperations, index);
_propagateResultsCommands.Add(CreateSelectedAffectedCommand(spannerConnection, modificationCommand, sql));
}
index++;
}
// Check that there were no concurrency problems detected.
if (RowsAffected != _modificationCommands.Count)
{
ThrowAggregateUpdateConcurrencyException();
}
}
/// <summary>
/// Executes the command batch using DML. DML is less efficient than mutations, but do allow applications
/// to read their own writes within a transaction. DML is therefore used by default for explicit transactions.
/// Applications can also configure the Spanner Entity Framework provider to use DML for implicit transactions as well.
/// </summary>
private async Task ExecuteDmlAsync(SpannerRetriableConnection spannerConnection, SpannerRetriableTransaction transaction, CancellationToken cancellationToken)
{
// Create a Batch DML command that contains all the updates in this batch.
// The update statements will include any concurrency token checks that might be needed.
var cmd = CreateSpannerBatchDmlCommand(spannerConnection, transaction);
UpdateCounts = (await cmd.Item1.ExecuteNonQueryAsync(cancellationToken)).ToList();
if (RowsAffected != _modificationCommands.Count)
{
ThrowAggregateUpdateConcurrencyException();
}
// Add any select commands that were generated by the batch for updates that need to propagate results.
if (cmd.Item2.Count > 0)
{
_propagateResultsCommands.AddRange(cmd.Item2);
}
}
/// <summary>
/// Constructs and throws a DbUpdateConcurrencyException for this batch based on the UpdateCounts.
/// </summary>
private void ThrowAggregateUpdateConcurrencyException()
{
var expectedRowsAffected = _modificationCommands.Count;
var index = 0;
var entries = new List<IUpdateEntry>();
foreach (var c in UpdateCounts)
{
if (c == 0L)
{
entries.AddRange(ModificationCommands[index].Entries);
}
index++;
}
throw new DbUpdateConcurrencyException(
RelationalStrings.UpdateConcurrencyException(expectedRowsAffected, RowsAffected), entries);
}
internal void PropagateResults()
{
if (_propagateResultsCommands.Count == 0)
{
return;
}
Task.Run(() => PropagateResultsAsync()).WaitWithUnwrappedExceptions();
}
/// <summary>
/// Propagates results from update statements that caused a computed column to be changed.
/// Result propagation is done by executing a separate SELECT statement on the table that was
/// updated. These SELECT statements are executed after the batch has been executed, and outside
/// of the transaction if implicit transactions are used.
///
/// If the batch uses an explicit transaction, the result propagation will be executed inside the
/// transaction.
/// </summary>
internal async Task PropagateResultsAsync(CancellationToken cancellationToken = default)
{
if (_propagateResultsCommands.Count == 0)
{
return;
}
int index = 0;
foreach (var modificationCommand in _modificationCommands)
{
if (modificationCommand.RequiresResultPropagation)
{
using var reader = await _propagateResultsCommands[index].ExecuteReaderAsync(cancellationToken);
if (await reader.ReadAsync(cancellationToken))
{
var valueBufferFactory = CreateValueBufferFactory(modificationCommand.ColumnModifications);
modificationCommand.PropagateResults(valueBufferFactory.Create(reader));
}
index++;
}
}
}
/// <summary>
/// Generates a Batch DML command for the modifications in this batch and SELECT statements for any
/// results that need to be propagated after the update.
/// </summary>
private Tuple<SpannerRetriableBatchCommand, List<SpannerRetriableCommand>> CreateSpannerBatchDmlCommand(SpannerRetriableConnection connection, SpannerRetriableTransaction transaction)
{
var selectCommands = new List<SpannerRetriableCommand>();
var commandPosition = 0;
var cmd = connection.CreateBatchDmlCommand();
cmd.Transaction = transaction;
foreach (var modificationCommand in _modificationCommands)
{
var commands = CreateSpannerDmlCommand(connection, modificationCommand, commandPosition);
cmd.Add(commands.Item1);
if (commands.Item2 != null)
{
if (_hasExplicitTransaction)
{
commands.Item2.Transaction = transaction;
}
selectCommands.Add(commands.Item2);
}
if (modificationCommand is SpannerPendingCommitTimestampModificationCommand commitTimestampModificationCommand)
{
transaction.AddSpannerPendingCommitTimestampModificationCommand(commitTimestampModificationCommand);
}
commandPosition++;
}
return Tuple.Create(cmd, selectCommands);
}
private Tuple<SpannerCommand, SpannerRetriableCommand> CreateSpannerDmlCommand(SpannerRetriableConnection connection, ModificationCommand modificationCommand, int commandPosition)
{
var builder = new StringBuilder();
ResultSetMapping res;
switch (modificationCommand.EntityState)
{
case EntityState.Deleted:
res = Dependencies.UpdateSqlGenerator.AppendDeleteOperation(builder, modificationCommand, commandPosition);
break;
case EntityState.Modified:
res = Dependencies.UpdateSqlGenerator.AppendUpdateOperation(builder, modificationCommand, commandPosition);
break;
case EntityState.Added:
res = Dependencies.UpdateSqlGenerator.AppendInsertOperation(builder, modificationCommand, commandPosition);
break;
default:
throw new NotSupportedException(
$"Modification type {modificationCommand.EntityState} is not supported.");
}
string dml;
SpannerRetriableCommand selectCommand = null;
if (res != ResultSetMapping.NoResultSet)
{
var commandTexts = builder.ToString().Split(_statementTerminator);
dml = commandTexts[0];
if (commandTexts.Length > 1)
{
selectCommand = CreateSelectedAffectedCommand(connection, modificationCommand, commandTexts[1]);
}
}
else
{
dml = builder.ToString();
dml = dml.TrimEnd('\r', '\n', _statementTerminator);
}
// This intentionally uses a SpannerCommand instead of the internal SpannerRetriableCommand, because the command
// will eventually be added to a BatchCommand.
var cmd = connection.SpannerConnection.CreateDmlCommand(dml);
AppendWriteParameters(modificationCommand, cmd, false, true);
return Tuple.Create(cmd, selectCommand);
}
private SpannerRetriableCommand CreateSpannerMutationCommand(
SpannerRetriableConnection spannerConnection,
SpannerRetriableTransaction transaction,
ModificationCommand modificationCommand)
{
var cmd = modificationCommand.EntityState switch
{
EntityState.Deleted => spannerConnection.CreateDeleteCommand(modificationCommand.TableName),
EntityState.Modified => spannerConnection.CreateUpdateCommand(modificationCommand.TableName),
EntityState.Added => spannerConnection.CreateInsertCommand(modificationCommand.TableName),
_ => throw new NotSupportedException($"Modification type {modificationCommand.EntityState} is not supported."),
};
cmd.Transaction = transaction;
AppendWriteParameters(modificationCommand, cmd, true, false);
return cmd;
}
/// <summary>
/// Adds the parameters that need to be written for an update command. This can be both a DML and a mutation command.
///
/// ConcurrencyToken conditions are not included in mutation commands, as these do not support a WHERE clause or other filtering.
/// </summary>
private void AppendWriteParameters(ModificationCommand modificationCommand, DbCommand cmd, bool useColumnName, bool includeConcurrencyTokenConditions)
{
foreach (var columnModification in modificationCommand.ColumnModifications.Where(
o => o.UseOriginalValueParameter && (includeConcurrencyTokenConditions || !(o.IsCondition && o.IsConcurrencyToken))))
{
cmd.Parameters.Add(CreateParameter(columnModification, cmd, UseValue.Original, useColumnName));
}
foreach (var columnModification in modificationCommand.ColumnModifications.Where(o => o.UseCurrentValueParameter))
{
cmd.Parameters.Add(CreateParameter(columnModification, cmd, UseValue.Current, useColumnName));
}
}
/// <summary>
/// Creates a SELECT command for a result that needs to be propagated after the update.
/// </summary>
private SpannerRetriableCommand CreateSelectedAffectedCommand(SpannerRetriableConnection connection, ModificationCommand modificationCommand, string sql)
{
var selectCommand = connection.CreateSelectCommand(sql);
foreach (var columnModification in modificationCommand.ColumnModifications)
{
if (columnModification.IsKey && (columnModification.UseOriginalValueParameter || columnModification.UseCurrentValueParameter))
{
selectCommand.Parameters.Add(CreateParameter(columnModification, selectCommand, columnModification.UseOriginalValueParameter ? UseValue.Original : UseValue.Current, false));
}
}
return selectCommand;
}
/// <summary>
/// Creates a SpannerParameter for a command and sets the correct type.
/// </summary>
private DbParameter CreateParameter(ColumnModification columnModification, DbCommand cmd, UseValue useValue, bool useColumnName)
{
string paramName;
if (useColumnName)
{
paramName = columnModification.ColumnName;
}
else
{
paramName = useValue == UseValue.Original ? columnModification.OriginalParameterName : columnModification.ParameterName;
}
var param = _typeMapper.GetMapping(columnModification.Property).CreateParameter(cmd,
paramName,
useValue == UseValue.Original ? columnModification.OriginalValue : columnModification.Value,
columnModification.Property.IsNullable);
if (param is SpannerParameter spannerParameter && SpannerDbType.Unspecified.Equals(spannerParameter.SpannerDbType))
{
spannerParameter.SpannerDbType = SpannerDbType.FromClrType(GetUnderlyingTypeOrSelf(columnModification.Property.ClrType));
}
return param;
}
private System.Type GetUnderlyingTypeOrSelf(System.Type type)
{
var underlying = Nullable.GetUnderlyingType(type);
return underlying == null ? type : underlying;
}
}
enum UseValue
{
Original,
Current
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Tools.Vhd.Model.Persistence
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Tools.Common.General;
public class VhdDataReader
{
private readonly BinaryReader reader;
private byte[] m_buffer;
public VhdDataReader(BinaryReader reader)
{
this.reader = reader;
this.m_buffer = new byte[16];
}
public long Size
{
get { return this.reader.BaseStream.Length; }
}
public bool ReadBoolean(long offset)
{
this.SetPosition(offset);
return this.reader.ReadBoolean();
}
public IAsyncResult BeginReadBoolean(long offset, AsyncCallback callback, object state)
{
this.SetPosition(offset);
return AsyncMachine.BeginAsyncMachine(FillBuffer, 1, callback, state);
}
public bool EndReadBoolean(IAsyncResult result)
{
AsyncMachine.EndAsyncMachine(result);
return (m_buffer[0] != 0);
}
IEnumerable<CompletionPort> FillBuffer(AsyncMachine machine, int numBytes)
{
if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length))
{
throw new ArgumentOutOfRangeException("numBytes", String.Format("Expected (0-16) however found: {0}", numBytes));
}
int bytesRead = 0;
int n = 0;
// Need to find a good threshold for calling ReadByte() repeatedly
// vs. calling Read(byte[], int, int) for both buffered & unbuffered
// streams.
if (numBytes == 1)
{
this.reader.BaseStream.BeginRead(m_buffer, 0, numBytes, machine.CompletionCallback, null);
yield return CompletionPort.SingleOperation;
n = this.reader.BaseStream.EndRead(machine.CompletionResult);
if (n == -1)
{
throw new EndOfStreamException();
}
m_buffer[0] = (byte)n;
}
do
{
this.reader.BaseStream.BeginRead(m_buffer, bytesRead, numBytes - bytesRead, machine.CompletionCallback, null);
yield return CompletionPort.SingleOperation;
n = this.reader.BaseStream.EndRead(machine.CompletionResult);
if (n == 0)
{
throw new EndOfStreamException();
}
bytesRead += n;
} while (bytesRead < numBytes);
}
public short ReadInt16(long offset)
{
this.SetPosition(offset);
return IPAddress.NetworkToHostOrder((short)this.reader.ReadUInt16());
}
public IAsyncResult BeginReadInt16(long offset, AsyncCallback callback, object state)
{
this.SetPosition(offset);
return AsyncMachine.BeginAsyncMachine(FillBuffer, 2, callback, state);
}
public short EndReadInt16(IAsyncResult result)
{
AsyncMachine.EndAsyncMachine(result);
short value = (short) (m_buffer[0] | m_buffer[1] << 8);
return IPAddress.NetworkToHostOrder(value);
}
public uint ReadUInt32(long offset)
{
this.SetPosition(offset);
return (uint)IPAddress.NetworkToHostOrder((int)this.reader.ReadUInt32());
}
public IAsyncResult BeginReadUInt32(long offset, AsyncCallback callback, object state)
{
this.SetPosition(offset);
return AsyncMachine.BeginAsyncMachine(FillBuffer, 4, callback, state);
}
public uint EndReadUInt32(IAsyncResult result)
{
AsyncMachine.EndAsyncMachine(result);
var value = (m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24);
return (uint)IPAddress.NetworkToHostOrder(value);
}
public uint ReadUInt32()
{
return (uint)IPAddress.NetworkToHostOrder((int)this.reader.ReadUInt32());
}
public IAsyncResult BeginReadUInt32(AsyncCallback callback, object state)
{
return AsyncMachine.BeginAsyncMachine(FillBuffer, 4, callback, state);
}
public ulong ReadUInt64(long offset)
{
this.SetPosition(offset);
var value = (long)this.reader.ReadUInt64();
return (ulong)IPAddress.NetworkToHostOrder(value);
}
public IAsyncResult BeginReadUInt64(long offset, AsyncCallback callback, object state)
{
this.SetPosition(offset);
return AsyncMachine.BeginAsyncMachine(FillBuffer, 8, callback, state);
}
public ulong EndReadUInt64(IAsyncResult result)
{
AsyncMachine.EndAsyncMachine(result);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
m_buffer[2] << 16 | m_buffer[3] << 24);
uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 |
m_buffer[6] << 16 | m_buffer[7] << 24);
ulong value = ((ulong) hi) << 32 | lo;
return (ulong)IPAddress.NetworkToHostOrder((long)value);
}
public byte[] ReadBytes(long offset, int count)
{
this.SetPosition(offset);
return this.reader.ReadBytes(count);
}
public IAsyncResult BeginReadBytes(long offset, int count, AsyncCallback callback, object state)
{
this.SetPosition(offset);
return AsyncMachine<byte[]>.BeginAsyncMachine(ReadBytesAsync, offset, count, callback, state);
}
public byte[] EndReadBytes(IAsyncResult result)
{
return AsyncMachine<byte[]>.EndAsyncMachine(result);
}
private IEnumerable<CompletionPort> ReadBytesAsync(AsyncMachine<byte[]> machine, long offset, int count)
{
StreamHelper.BeginReadBytes(this.reader.BaseStream, offset, count, machine.CompletionCallback, null);
yield return CompletionPort.SingleOperation;
byte[] values = StreamHelper.EndReadBytes(machine.CompletionResult);
machine.ParameterValue = values;
}
public byte[] ReadBytes(int count)
{
return this.reader.ReadBytes(count);
}
public IAsyncResult BeginReadBytes(int count, AsyncCallback callback, object state)
{
return AsyncMachine<byte[]>.BeginAsyncMachine(ReadBytesAsync, this.reader.BaseStream.Position, count, callback, state);
}
public string ReadString(int count)
{
return Encoding.ASCII.GetString(this.reader.ReadBytes(count));
}
public IAsyncResult BeginReadString(int count, AsyncCallback callback, object state)
{
return AsyncMachine<string>.BeginAsyncMachine(ReadStringAsync, this.reader.BaseStream.Position, count, callback, state);
}
public string EndReadString(IAsyncResult result)
{
return AsyncMachine<string>.EndAsyncMachine(result);
}
private IEnumerable<CompletionPort> ReadStringAsync(AsyncMachine<string> machine, long offset, int count)
{
BeginReadBytes(offset, count, machine.CompletionCallback, null);
yield return CompletionPort.SingleOperation;
byte[] values = EndReadBytes(machine.CompletionResult);
machine.ParameterValue = Encoding.ASCII.GetString(values);
}
public byte ReadByte(long offset)
{
this.SetPosition(offset);
return this.reader.ReadByte();
}
public IAsyncResult BeginReadByte(long offset, AsyncCallback callback, object state)
{
return BeginReadBytes(offset, 1, callback, state);
}
public byte EndReadByte(IAsyncResult result)
{
return EndReadBytes(result)[0];
}
public Guid ReadGuid(long offset)
{
return new Guid(this.ReadBytes(offset, 16));
}
public IAsyncResult BeginReadGuid(long offset, AsyncCallback callback, object state)
{
return BeginReadBytes(offset, 16, callback, state);
}
public Guid EndReadGuid(IAsyncResult result)
{
byte[] guidValue = EndReadBytes(result);
return new Guid(guidValue);
}
public DateTime ReadDateTime(long offset)
{
var timeStamp = new VhdTimeStamp(this.ReadUInt32(offset));
return timeStamp.ToDateTime();
}
public IAsyncResult BeginReadDateTime(long offset, AsyncCallback callback, object state)
{
return BeginReadUInt32(offset, callback, state);
}
public DateTime EndReadDateTime(IAsyncResult result)
{
uint value = EndReadUInt32(result);
var timeStamp = new VhdTimeStamp(value);
return timeStamp.ToDateTime();
}
public DateTime ReadDateTime()
{
var timeStamp = new VhdTimeStamp(this.ReadUInt32());
return timeStamp.ToDateTime();
}
public IAsyncResult BeginReadDateTime(AsyncCallback callback, object state)
{
return BeginReadUInt32(callback, state);
}
public void SetPosition(long batOffset)
{
this.reader.BaseStream.Seek(batOffset, SeekOrigin.Begin);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for EncryptionProtectorsOperations.
/// </summary>
public static partial class EncryptionProtectorsOperationsExtensions
{
/// <summary>
/// Gets a list of server encryption protectors
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static IPage<EncryptionProtector> ListByServer(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName)
{
return operations.ListByServerAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of server encryption protectors
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<EncryptionProtector>> ListByServerAsync(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a server encryption protector.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static EncryptionProtector Get(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName)
{
return operations.GetAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a server encryption protector.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EncryptionProtector> GetAsync(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing encryption protector.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The requested encryption protector resource state.
/// </param>
public static EncryptionProtector CreateOrUpdate(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName, EncryptionProtector parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing encryption protector.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The requested encryption protector resource state.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EncryptionProtector> CreateOrUpdateAsync(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName, EncryptionProtector parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing encryption protector.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The requested encryption protector resource state.
/// </param>
public static EncryptionProtector BeginCreateOrUpdate(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName, EncryptionProtector parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing encryption protector.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The requested encryption protector resource state.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EncryptionProtector> BeginCreateOrUpdateAsync(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName, EncryptionProtector parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of server encryption protectors
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<EncryptionProtector> ListByServerNext(this IEncryptionProtectorsOperations operations, string nextPageLink)
{
return operations.ListByServerNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of server encryption protectors
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<EncryptionProtector>> ListByServerNextAsync(this IEncryptionProtectorsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright 2019 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Tasks.Offline;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.Xaml;
namespace ArcGISRuntime.UWP.Samples.DownloadPreplannedMap
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Download preplanned map area",
category: "Map",
description: "Take a map offline using a preplanned map area.",
instructions: "Select a map area from the Preplanned Map Areas list. Click the button to download the selected area. The download progress will be shown in the Downloads list. When a download is complete, select it to display the offline map in the map view.",
tags: new[] { "map area", "offline", "pre-planned", "preplanned" })]
public partial class DownloadPreplannedMap
{
// ID of a web map with preplanned map areas.
private const string PortalItemId = "acc027394bc84c2fb04d1ed317aac674";
// Folder to store the downloaded mobile map packages.
private string _offlineDataFolder;
// Task for taking map areas offline.
private OfflineMapTask _offlineMapTask;
// Hold onto the original map.
private Map _originalMap;
// Most recently opened map package.
private MobileMapPackage _mobileMapPackage;
public DownloadPreplannedMap()
{
InitializeComponent();
Initialize();
}
private async void Initialize()
{
try
{
// Close the current mobile package when the sample closes.
Unloaded += (s, e) => { _mobileMapPackage?.Close(); };
// The data manager provides a method to get a suitable offline data folder.
_offlineDataFolder = Path.Combine(DataManager.GetDataFolder(), "SampleData", "DownloadPreplannedMapAreas");
// If temporary data folder doesn't exists, create it.
if (!Directory.Exists(_offlineDataFolder))
{
Directory.CreateDirectory(_offlineDataFolder);
}
// Create a portal to enable access to the portal item.
ArcGISPortal portal = await ArcGISPortal.CreateAsync();
// Create the portal item from the portal item ID.
PortalItem webMapItem = await PortalItem.CreateAsync(portal, PortalItemId);
// Show the map.
_originalMap = new Map(webMapItem);
MyMapView.Map = _originalMap;
// Create an offline map task for the web map item.
_offlineMapTask = await OfflineMapTask.CreateAsync(webMapItem);
// Find the available preplanned map areas.
IReadOnlyList<PreplannedMapArea> preplannedAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();
// Load each item, then add it to the UI.
foreach (PreplannedMapArea area in preplannedAreas)
{
await area.LoadAsync();
AreasList.Items.Add(area);
}
// Hide the loading indicator.
BusyIndicator.Visibility = Visibility.Collapsed;
}
catch (Exception ex)
{
// Something unexpected happened, show the error message.
Debug.WriteLine(ex);
await new MessageDialog(ex.Message, "There was an error.").ShowAsync();
}
}
private void ShowOnlineButton_Click(object sender, RoutedEventArgs e)
{
// Show the online map.
MyMapView.Map = _originalMap;
// Disable the button.
ShowOnlineButton.IsEnabled = false;
}
private async Task DownloadMapAreaAsync(PreplannedMapArea mapArea)
{
// Close the current mobile package.
_mobileMapPackage?.Close();
// Set up UI for downloading.
ProgressBar.IsIndeterminate = false;
ProgressBar.Value = 0;
BusyText.Text = "Downloading map area...";
BusyIndicator.Visibility = Visibility.Visible;
// Create folder path where the map package will be downloaded.
string path = Path.Combine(_offlineDataFolder, mapArea.PortalItem.Title);
// If the area is already downloaded, open it.
if (Directory.Exists(path))
{
try
{
// Open the offline map package.
_mobileMapPackage = await MobileMapPackage.OpenAsync(path);
// Display the first map.
MyMapView.Map = _mobileMapPackage.Maps.First();
// Update the UI.
BusyText.Text = string.Empty;
BusyIndicator.Visibility = Visibility.Collapsed;
MessageLabel.Text = "Opened offline area.";
return;
}
catch (Exception e)
{
Debug.WriteLine(e);
await new MessageDialog(e.Message, "Couldn't open offline area. Proceeding to take area offline.").ShowAsync();
}
}
// Create download parameters.
DownloadPreplannedOfflineMapParameters parameters = await _offlineMapTask.CreateDefaultDownloadPreplannedOfflineMapParametersAsync(mapArea);
// Set the update mode to not receive updates.
parameters.UpdateMode = PreplannedUpdateMode.NoUpdates;
// Create the job.
DownloadPreplannedOfflineMapJob job = _offlineMapTask.DownloadPreplannedOfflineMap(parameters, path);
// Set up event to update the progress bar while the job is in progress.
job.ProgressChanged += OnJobProgressChanged;
try
{
// Download the area.
DownloadPreplannedOfflineMapResult results = await job.GetResultAsync();
// Set the current mobile map package.
_mobileMapPackage = results.MobileMapPackage;
// Handle possible errors and show them to the user.
if (results.HasErrors)
{
// Accumulate all layer and table errors into a single message.
string errors = "";
foreach (KeyValuePair<Layer, Exception> layerError in results.LayerErrors)
{
errors = $"{errors}\n{layerError.Key.Name} {layerError.Value.Message}";
}
foreach (KeyValuePair<FeatureTable, Exception> tableError in results.TableErrors)
{
errors = $"{errors}\n{tableError.Key.TableName} {tableError.Value.Message}";
}
// Show the message.
await new MessageDialog(errors, "Warning!").ShowAsync();
}
// Show the downloaded map.
MyMapView.Map = results.OfflineMap;
// Update the UI.
ShowOnlineButton.IsEnabled = true;
DownloadButton.Content = "View downloaded area";
MessageLabel.Text = "Downloaded preplanned area.";
}
catch (Exception ex)
{
// Report any errors.
Debug.WriteLine(ex);
await new MessageDialog(ex.Message, "Downloading map area failed.").ShowAsync();
}
finally
{
BusyText.Text = string.Empty;
BusyIndicator.Visibility = Visibility.Collapsed;
}
}
private async void OnJobProgressChanged(object sender, EventArgs e)
{
// Because the event is raised on a background thread, the dispatcher must be used to
// ensure that UI updates happen on the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
// Update the UI with the progress.
DownloadPreplannedOfflineMapJob downloadJob = sender as DownloadPreplannedOfflineMapJob;
ProgressBar.Value = downloadJob.Progress;
BusyPercentage.Text = $"{downloadJob.Progress}%";
});
}
private async void OnDownloadMapAreaClicked(object sender, RoutedEventArgs e)
{
if (AreasList.SelectedItem != null)
{
PreplannedMapArea selectedMapArea = AreasList.SelectedItem as PreplannedMapArea;
await DownloadMapAreaAsync(selectedMapArea);
}
}
private async void OnDeleteAllMapAreasClicked(object sender, RoutedEventArgs e)
{
try
{
// Set up UI for downloading.
ProgressBar.IsIndeterminate = true;
BusyText.Text = "Deleting downloaded map area...";
BusyIndicator.Visibility = Visibility.Visible;
// Reset the map.
MyMapView.Map = _originalMap;
// Close the current mobile package.
_mobileMapPackage?.Close();
// Delete all data from the temporary data folder.
Directory.Delete(_offlineDataFolder, true);
Directory.CreateDirectory(_offlineDataFolder);
// Update the UI.
MessageLabel.Text = "Deleted downloaded areas.";
DownloadButton.Content = "Download preplanned area";
ShowOnlineButton.IsEnabled = false;
}
catch (Exception ex)
{
// Report the error.
await new MessageDialog(ex.Message, "Deleting map areas failed.").ShowAsync();
}
finally
{
BusyIndicator.Visibility = Visibility.Collapsed;
}
}
private void AreasList_SelectionChanged(object sender, Windows.UI.Xaml.Controls.SelectionChangedEventArgs e)
{
// Update the download button to reflect if the map area has already been downloaded.
if (Directory.Exists(Path.Combine(_offlineDataFolder, (AreasList.SelectedItem as PreplannedMapArea).PortalItem.Title)))
{
DownloadButton.Content = "View downloaded area";
}
else
{
DownloadButton.Content = "Download preplanned area";
}
}
}
}
| |
// 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.IO;
using System.Windows.Input;
using System.Windows.Ink;
namespace MS.Internal.Ink.InkSerializedFormat
{
/// <summary>
/// Summary description for MetricEnty.
/// </summary>
internal enum MetricEntryType
{
Optional = 0,
Must,
Never,
Custom,
}
// This is used while comparing two Metric Collections. This defines the relationship between
// two collections when one is superset of the other and can replace the other in the global
// list of collections
internal enum SetType
{
SubSet = 0,
SuperSet,
}
internal struct MetricEntryList
{
public KnownTagCache.KnownTagIndex Tag;
public StylusPointPropertyInfo PropertyMetrics;
public MetricEntryList (KnownTagCache.KnownTagIndex tag, StylusPointPropertyInfo prop)
{
Tag = tag;
PropertyMetrics = prop;
}
}
/// <summary>
/// This class holds the MetricEntries corresponding to a PacketProperty in the form of a link list
/// </summary>
internal class MetricEntry
{
//Maximum buffer size required to store the largest MetricEntry
private static int MAX_METRIC_DATA_BUFF = 24;
private KnownTagCache.KnownTagIndex _tag = 0;
private uint _size = 0;
private MetricEntry _next;
private byte[] _data = new Byte[MAX_METRIC_DATA_BUFF]; // We always allocate the max buffer needed to store the largest possible Metric Information blob
private static MetricEntryList[] _metricEntryOptional;
// helpers for Ink-local property metrics for X/Y coordiantes
public static StylusPointPropertyInfo DefaultXMetric = MetricEntry_Optional[0].PropertyMetrics;
public static StylusPointPropertyInfo DefaultYMetric = MetricEntry_Optional[1].PropertyMetrics;
/// <summary>
/// List of MetricEntry that may or may not appear in the serialized form depending on their default Metrics.
/// </summary>
public static MetricEntryList[] MetricEntry_Optional
{
get
{
if (_metricEntryOptional == null)
{
_metricEntryOptional = new MetricEntryList[] {
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.X, StylusPointPropertyInfoDefaults.X),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.Y, StylusPointPropertyInfoDefaults.Y),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.Z, StylusPointPropertyInfoDefaults.Z),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.NormalPressure, StylusPointPropertyInfoDefaults.NormalPressure),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.TangentPressure, StylusPointPropertyInfoDefaults.TangentPressure),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.ButtonPressure, StylusPointPropertyInfoDefaults.ButtonPressure),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.XTiltOrientation, StylusPointPropertyInfoDefaults.XTiltOrientation),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.YTiltOrientation, StylusPointPropertyInfoDefaults.YTiltOrientation),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.AzimuthOrientation, StylusPointPropertyInfoDefaults.AzimuthOrientation),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.AltitudeOrientation, StylusPointPropertyInfoDefaults.AltitudeOrientation),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.TwistOrientation, StylusPointPropertyInfoDefaults.TwistOrientation)};
}
return _metricEntryOptional;
}
}
/// <summary>
/// List of MetricEntry whose Metric Information must appear in the serialized form and always written as they do not have proper default
/// </summary>
static KnownTagCache.KnownTagIndex[] MetricEntry_Must = new KnownTagCache.KnownTagIndex[]
{
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.PitchRotation),
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.RollRotation),
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.YawRotation),
};
/// <summary>
/// List of MetricEntry whose Metric information will never appear in the Serialized format and always ignored
/// </summary>
static KnownTagCache.KnownTagIndex[] MetricEntry_Never = new KnownTagCache.KnownTagIndex[]
{
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.PacketStatus),
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.TimerTick),
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.SerialNumber),
};
/// <summary>
/// Default StylusPointPropertyInfo for any property
/// </summary>
static StylusPointPropertyInfo DefaultPropertyMetrics = StylusPointPropertyInfoDefaults.DefaultValue;
/// <summary>
/// Gets or sets the Tag associated with this entry
/// </summary>
public KnownTagCache.KnownTagIndex Tag
{
get
{
return _tag;
}
set
{
_tag = value;
}
}
/// <summary>
/// Gets the size associated with this entry
/// </summary>
public uint Size
{
get
{
return _size;
}
}
/// <summary>
/// Gets or Sets the data associated with this metric entry
/// </summary>
public byte[] Data
{
get
{
return _data;
}
set
{
byte [] data = (byte[])value;
if( data.Length > MAX_METRIC_DATA_BUFF )
_size = (uint)MAX_METRIC_DATA_BUFF;
else
_size = (uint)data.Length;
for( int i = 0; i < (int)_size; i++ )
_data[i] = data[i];
}
}
/// <summary>
/// Compares a metricEntry object with this one and returns true or false
/// </summary>
/// <param name="metricEntry"></param>
/// <returns></returns>
public bool Compare(MetricEntry metricEntry)
{
if( Tag != metricEntry.Tag )
return false;
if( Size != metricEntry.Size )
return false;
for( int i = 0; i < Size; i++ )
{
if( Data[i] != metricEntry.Data[i] )
return false;
}
return true;
}
/// <summary>
/// Gets/Sets the next entry in the list
/// </summary>
public MetricEntry Next
{
get
{
return _next;
}
set
{
_next = value;
}
}
/// <summary>
/// Constructro
/// </summary>
public MetricEntry()
{
}
/// <summary>
/// Adds an entry in the list
/// </summary>
/// <param name="next"></param>
public void Add(MetricEntry next)
{
if( null == _next )
{
_next = next;
return;
}
MetricEntry prev = _next;
while( null != prev.Next )
{
prev = prev.Next;
}
prev.Next = next;
}
/// <summary>
/// Initializes a MetricEntry based on StylusPointPropertyInfo and default StylusPointPropertyInfo for the property
/// </summary>
/// <param name="originalInfo"></param>
/// <param name="defaultInfo"></param>
/// <returns></returns>
public void Initialize(StylusPointPropertyInfo originalInfo, StylusPointPropertyInfo defaultInfo)
{
_size = 0;
using (MemoryStream strm = new MemoryStream(_data))
{
if (!DoubleUtil.AreClose(originalInfo.Resolution, defaultInfo.Resolution))
{
// First min value
_size += SerializationHelper.SignEncode(strm, originalInfo.Minimum);
// Max value
_size += SerializationHelper.SignEncode(strm, originalInfo.Maximum);
// Units
_size += SerializationHelper.Encode(strm, (uint)originalInfo.Unit);
// resolution
using (BinaryWriter bw = new BinaryWriter(strm))
{
bw.Write(originalInfo.Resolution);
_size += 4; // sizeof(float)
}
}
else if (originalInfo.Unit != defaultInfo.Unit)
{
// First min value
_size += SerializationHelper.SignEncode(strm, originalInfo.Minimum);
// Max value
_size += SerializationHelper.SignEncode(strm, originalInfo.Maximum);
// Units
_size += SerializationHelper.Encode(strm, (uint)originalInfo.Unit);
}
else if (originalInfo.Maximum != defaultInfo.Maximum)
{
// First min value
_size += SerializationHelper.SignEncode(strm, originalInfo.Minimum);
// Max value
_size += SerializationHelper.SignEncode(strm, originalInfo.Maximum);
}
else if (originalInfo.Minimum != defaultInfo.Minimum)
{
_size += SerializationHelper.SignEncode(strm, originalInfo.Minimum);
}
}
}
/// <summary>
/// Creates a metric entry based on a PropertyInfo and Tag and returns the Metric Entry Type created
/// </summary>
/// <param name="propertyInfo"></param>
/// <param name="tag"></param>
/// <returns></returns>
public MetricEntryType CreateMetricEntry(StylusPointPropertyInfo propertyInfo, KnownTagCache.KnownTagIndex tag)
{
// First create the default Metric entry based on the property and type of metric entry and then use that to initialize the
// metric entry data.
uint index = 0;
Tag = tag;
MetricEntryType type;
if( IsValidMetricEntry(propertyInfo, Tag, out type, out index) )
{
switch(type)
{
case MetricEntryType.Optional:
{
Initialize(propertyInfo, MetricEntry_Optional[index].PropertyMetrics);
break;
}
case MetricEntryType.Must :
case MetricEntryType.Custom:
Initialize(propertyInfo, DefaultPropertyMetrics);
break;
default:
throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("MetricEntryType was persisted with Never flag which should never happen"));
}
}
return type;
}
/// <summary>
/// This function checks if this packet property results in a valid metric entry. This will be a valid entry if
/// 1. it is a custom property, 2. Does not belong to the global list of gaMetricEntry_Never, 3. Belongs to the
/// global list of gaMetricEntry_Must and 4. Belongs to global list of gaMetricEntry_Optional and at least one of
/// its metric values is different from the corresponding default.
/// </summary>
/// <param name="propertyInfo"></param>
/// <param name="tag"></param>
/// <param name="metricEntryType"></param>
/// <param name="index"></param>
/// <returns></returns>
static bool IsValidMetricEntry(StylusPointPropertyInfo propertyInfo, KnownTagCache.KnownTagIndex tag, out MetricEntryType metricEntryType, out uint index)
{
index = 0;
// If this is a custom property, check if all the Metric values are null or not. If they are then this is not a
// valid metric entry
if (tag >= (KnownTagCache.KnownTagIndex)KnownIdCache.CustomGuidBaseIndex)
{
metricEntryType = MetricEntryType.Custom;
if( Int32.MinValue == propertyInfo.Minimum &&
Int32.MaxValue == propertyInfo.Maximum &&
StylusPointPropertyUnit.None == propertyInfo.Unit &&
DoubleUtil.AreClose(1.0, propertyInfo.Resolution) )
return false;
else
return true;
}
else
{
int ul;
// First find the property in the gaMetricEntry_Never. If it belongs to this list,
// we will never write the metric table for this prop. So return FALSE;
for( ul = 0; ul < MetricEntry_Never.Length ; ul++ )
{
if( MetricEntry_Never[ul] == tag )
{
metricEntryType = MetricEntryType.Never;
return false;
}
}
// Then search the property in the gaMetricEntry_Must list. If it belongs to this list,
// we must always write the metric table for this prop. So return TRUE;
for( ul = 0; ul<MetricEntry_Must.Length; ul++ )
{
if( MetricEntry_Must[ul] == tag )
{
metricEntryType = MetricEntryType.Must;
if( propertyInfo.Minimum == DefaultPropertyMetrics.Minimum &&
propertyInfo.Maximum == DefaultPropertyMetrics.Maximum &&
propertyInfo.Unit == DefaultPropertyMetrics.Unit &&
DoubleUtil.AreClose(propertyInfo.Resolution, DefaultPropertyMetrics.Resolution ))
return false;
else
return true;
}
}
// Now seach it in the gaMetricEntry_Optional list. If it is there, check the metric values
// agianst the default values and if there is any non default value, return TRUE;
for( ul = 0; ul<MetricEntry_Optional.Length; ul++ )
{
if( ((MetricEntryList)MetricEntry_Optional[ul]).Tag == tag )
{
metricEntryType = MetricEntryType.Optional;
if( propertyInfo.Minimum == MetricEntry_Optional[ul].PropertyMetrics.Minimum &&
propertyInfo.Maximum == MetricEntry_Optional[ul].PropertyMetrics.Maximum &&
propertyInfo.Unit == MetricEntry_Optional[ul].PropertyMetrics.Unit &&
DoubleUtil.AreClose(propertyInfo.Resolution, MetricEntry_Optional[ul].PropertyMetrics.Resolution) )
return false;
else
{
index = (uint)ul;
return true;
}
}
}
// it is not found in any of the list. Force to write all metric entries for the property.
metricEntryType = MetricEntryType.Must;
return true;
}
}
}
/// <summary>
/// CMetricBlock owns CMetricEntry which is created based on the Packet Description of the stroke. It also
/// stores the pointer of the next Block. This is not used in the context of a stroke but is used in the
/// context of WispInk. Wispink forms a linked list based on the CMetricBlocks of all the strokes.
/// </summary>
internal class MetricBlock
{
private MetricEntry _Entry;
private uint _Count;
private uint _size;
/// <summary>
/// Constructor
/// </summary>
public MetricBlock()
{
}
/// <summary>
/// Gets the MetricEntry list associated with this instance
/// </summary>
/// <returns></returns>
public MetricEntry GetMetricEntryList()
{
return _Entry;
}
/// <summary>
/// Gets the count of MetricEntry for this instance
/// </summary>
public uint MetricEntryCount
{
get
{
return _Count;
}
}
// Returns the size required to serialize this instance
public uint Size
{
get
{
return (_size + SerializationHelper.VarSize(_size));
}
}
/// <summary>
/// Adds a new metric entry in the existing list of metric entries
/// </summary>
/// <param name="newEntry"></param>
/// <returns></returns>
public void AddMetricEntry(MetricEntry newEntry)
{
if (null == newEntry)
{
throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("MetricEntry cannot be null"));
}
if( null == _Entry )
_Entry = newEntry;
else
_Entry.Add(newEntry); // tack on at the end
_Count ++;
_size += newEntry.Size + SerializationHelper.VarSize(newEntry.Size) + SerializationHelper.VarSize((uint)newEntry.Tag);
}
/// <summary>
/// Adds a new metric entry in the existing list of metric entries
/// </summary>
/// <param name="property"></param>
/// <param name="tag"></param>
/// <returns></returns>
public MetricEntryType AddMetricEntry(StylusPointPropertyInfo property, KnownTagCache.KnownTagIndex tag)
{
// Create a new metric entry based on the packet information passed.
MetricEntry entry = new MetricEntry();
MetricEntryType type = entry.CreateMetricEntry(property, tag);
// Don't add this entry to the global list if size is 0, means default metric values!
if( 0 == entry.Size )
{
return type;
}
MetricEntry start = _Entry;
if( null == start )
{
_Entry = entry;
}
else // tack on data at the end, want to keep x,y at the beginning
{
while(start.Next != null)
{
start = start.Next;
}
start.Next = entry;
}
_Count++;
_size += entry.Size + SerializationHelper.VarSize(entry.Size) + SerializationHelper.VarSize((uint)_Entry.Tag);
return type;
}
/// <summary>
/// This function Packs the data in the buffer provided. The
/// function is being called during the save loop and caller
/// must call GetSize for the block before calling this function.
/// The buffer must be preallocated and buffer size must be at
/// least the size of the block.
/// On return cbBuffer contains the size of the data written.
/// Called only by BuildMetricTable funtion
/// </summary>
/// <param name="strm"></param>
/// <returns></returns>
public uint Pack(Stream strm)
{
// Write the size of the Block at the begining of the buffer.
// But first check the validity of the buffer & its size
uint cbWrite = 0;
// First write the size of the block
cbWrite = SerializationHelper.Encode(strm, _size);
// Now write each entry for the block
MetricEntry entry = _Entry;
while( null != entry )
{
cbWrite += SerializationHelper.Encode(strm, (uint)entry.Tag);
cbWrite += SerializationHelper.Encode(strm, entry.Size);
strm.Write(entry.Data, 0, (int)entry.Size);
cbWrite += entry.Size;
entry = entry.Next;
}
return cbWrite;
}
//
//
/// <summary>
/// This function compares pMetricColl with the current one. If pMetricColl has more entries apart from the one
/// in the current list with which some of its entries are identical, setType is set as SUPERSET.
/// </summary>
/// <param name="metricColl"></param>
/// <param name="setType"></param>
/// <returns></returns>
public bool CompareMetricBlock( MetricBlock metricColl, ref SetType setType)
{
if( null == metricColl )
return false;
// if both have null entry, implies default metric Block for both of them
// and it already exists in the list. Return TRUE
// If only one of the blocks is empty, return FALSE - they cannot be merged
// because the other block may have customized GUID_X or GUID_Y.
if (null == GetMetricEntryList())
return (metricColl.GetMetricEntryList() == null);
if (null == metricColl.GetMetricEntryList())
return false;
// Else compare the entries
bool fTagFound = false;
uint cbLhs = this.MetricEntryCount; // No of entries in this block
uint cbRhs = metricColl.MetricEntryCount; // No of entries in the block to be compared
MetricEntry outside, inside;
if( metricColl.MetricEntryCount <= MetricEntryCount )
{
outside = metricColl.GetMetricEntryList();
inside = GetMetricEntryList();
}
else
{
inside = metricColl.GetMetricEntryList();
outside = GetMetricEntryList();
setType = SetType.SuperSet;
}
// For each entry in metricColl, search for the same in this Block.
// If it is found, continue with the next entry of smaller Block.
while( null != outside )
{
fTagFound = false;
// Always start at the begining of the larger block
MetricEntry temp = inside;
while( null != temp )
{
if( outside.Compare(temp) )
{
fTagFound = true;
break;
}
else
temp = temp.Next;
}
if( !fTagFound )
return false;
// Found the entry; Continue with the next entry in the outside block
outside = outside.Next;
}
return true;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Runtime.InteropServices;
namespace OpenLiveWriter.Interop.Com.Ribbon
{
public enum ContextAvailability
{
NotAvailable = 0,
Available = 1,
Active = 2,
}
public enum FontProperties
{
NotAvailable = 0,
NotSet = 1,
Set = 2,
}
public enum FontPropertiesVerticalPositioning
{
NotAvailable = 0,
NotSet = 1,
Superscript = 2,
Subscript = 3,
}
public enum FontPropertiesUnderline
{
NotAvailable = 0,
NotSet = 1,
Set = 2,
}
public enum ControlDock
{
Top = 1,
Bottom = 3,
}
public enum SwatchColorType
{
NoColor = 0,
Automatic = 1, // automatic swatch
RGB = 2, // Solid color swatch
}
[Flags]
public enum CommandInvalidationFlags
{
AllCommands = 0,
State = 0x00000001, // UI_PKEY_Enabled
Value = 0x00000002, // Value property
Property = 0x00000004, // Any property
AllProperties = 0x00000008 // All properties
}
public enum CollectionChangeType
{
Insert = 0,
Remove = 1,
Replace = 2,
Reset = 3,
}
public enum CommandExecutionVerb
{
Execute = 0,
Preview = 1,
CancelPreview = 2
}
public enum CommandTypeID
{
UI_COMMANDTYPE_UNKNOWN = 0,
UI_COMMANDTYPE_GROUP = 1,
UI_COMMANDTYPE_ACTION = 2,
UI_COMMANDTYPE_ANCHOR = 3,
UI_COMMANDTYPE_CONTEXT = 4,
UI_COMMANDTYPE_COLLECTION = 5,
UI_COMMANDTYPE_COMMANDCOLLECTION = 6,
UI_COMMANDTYPE_DECIMAL = 7,
UI_COMMANDTYPE_BOOLEAN = 8,
UI_COMMANDTYPE_FONT = 9,
UI_COMMANDTYPE_RECENTITEMS = 10,
UI_COMMANDTYPE_COLORANCHOR = 11,
UI_COMMANDTYPE_COLORCOLLECTION = 12,
}
public enum ViewVerb
{
Create,
Destroy,
Size,
Error,
}
public enum ImageCreationOptions
{
Transfer, // IUIImage now owns HBITMAP; caller must NOT free it.
Copy, // IUIImage creates a copy of HBITMAP; caller must free it.
}
[
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("c205bb48-5b1c-4219-a106-15bd0a5f24e2")
]
public interface IUISimplePropertySet
{
// Retrieves the stored value of a given property
[PreserveSig]
Int32 GetValue([In] ref PropertyKey key, [Out] out PropVariant value);
}
[
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("803982ab-370a-4f7e-a9e7-8784036a6e26")
]
public interface IUIRibbon
{
// Returns the Ribbon height
[PreserveSig]
Int32 GetHeight([Out] out UInt32 cy);
// Load QAT from a stream
[PreserveSig]
Int32 LoadSettingsFromStream([In] System.Runtime.InteropServices.ComTypes.IStream pStream);
// Save QAT to a stream
[PreserveSig]
Int32 SaveSettingsToStream([In] System.Runtime.InteropServices.ComTypes.IStream pStream);
}
[
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("F4F0385D-6872-43a8-AD09-4C339CB3F5C5")
]
public interface IUIFramework
{
// Connects the framework and the application
[PreserveSig]
Int32 Initialize(IntPtr frameWnd, IUIApplication application);
// Releases all framework objects
[PreserveSig]
Int32 Destroy();
// Loads and instantiates the views and commands specified in markup
[PreserveSig]
Int32 LoadUI(IntPtr instance, [MarshalAs(UnmanagedType.LPWStr)] string resourceName);
// Retrieves a pointer to a view object
[PreserveSig]
Int32 GetView(UInt32 viewId, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface, IidParameterIndex = 1)] out object ppv);
// Retrieves the current value of a property
[PreserveSig]
Int32 GetUICommandProperty(UInt32 commandId, [In] ref PropertyKey key, [Out] out PropVariant value);
// Immediately sets the value of a property
[PreserveSig]
Int32 SetUICommandProperty(UInt32 commandId, [In] ref PropertyKey key, [In] ref PropVariant value);
// Asks the framework to retrieve the new value of a property at the next update cycle
[PreserveSig]
Int32 InvalidateUICommand(UInt32 commandId, CommandInvalidationFlags flags, IntPtr keyPtr);
// Flush all the pending UI command updates
[PreserveSig]
Int32 FlushPendingInvalidations();
// Asks the framework to switch to the list of modes specified and adjust visibility of controls accordingly
[PreserveSig]
Int32 SetModes(Int32 iModes);
}
[
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("EEA11F37-7C46-437c-8E55-B52122B29293")
]
public interface IContextualUI
{
// Sets the desired anchor point where ContextualUI should be displayed.
// Typically this is the mouse location at the time of right click.
// x and y are in virtual screen coordinates
[PreserveSig]
Int32 ShowAtLocation(Int32 x, Int32 y);
}
[
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("DF4F45BF-6F9D-4dd7-9D68-D8F9CD18C4DB")
]
public interface IUICollection
{
// Retrieves the count of the collection
[PreserveSig]
Int32 GetCount([Out] out UInt32 count);
// Retrieves an item
[PreserveSig]
Int32 GetItem(UInt32 index, [Out, MarshalAs(UnmanagedType.IUnknown)] out object item);
// Adds an item to the end
[PreserveSig]
Int32 Add([In, MarshalAs(UnmanagedType.IUnknown)] object item);
// Inserts an item
[PreserveSig]
Int32 Insert(UInt32 index, [In, MarshalAs(UnmanagedType.IUnknown)] object item);
// Removes an item at the specified position
[PreserveSig]
Int32 RemoveAt(UInt32 index);
// Replaces an item at the specified position
[PreserveSig]
Int32 Replace(UInt32 indexReplaced, [In, MarshalAs(UnmanagedType.IUnknown)] object itemReplaceWith);
// Clear the collection
[PreserveSig]
Int32 Clear();
}
[
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("6502AE91-A14D-44b5-BBD0-62AACC581D52")
]
public interface IUICollectionChangedEvent
{
[PreserveSig]
Int32 OnChanged(CollectionChangeType action,
UInt32 oldIndex,
[In, Optional, MarshalAs(UnmanagedType.IUnknown)] object oldItem,
UInt32 newIndex,
[In, Optional, MarshalAs(UnmanagedType.IUnknown)] object newItem);
}
[
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("75ae0a2d-dc03-4c9f-8883-069660d0beb6")
]
public interface IUICommandHandler
{
// User action callback, with transient execution parameters
[PreserveSig]
Int32 Execute(UInt32 commandId, // the command that has been executed
CommandExecutionVerb verb, // the mode of execution
[In, Optional] PropertyKeyRef key, // the property that has changed
[In, Optional] PropVariantRef currentValue, // the new value of the property that has changed
[In, Optional] IUISimplePropertySet commandExecutionProperties); // additional data for this execution
// Informs of the current value of a property, and queries for the new one
[PreserveSig]
Int32 UpdateProperty(UInt32 commandId,
[In] ref PropertyKey key,
[In, Optional] PropVariantRef currentValue,
[Out] out PropVariant newValue);
}
[
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("D428903C-729A-491d-910D-682A08FF2522")
]
public interface IUIApplication
{
// A view has changed
[PreserveSig]
Int32 OnViewChanged(UInt32 viewId,
CommandTypeID typeID,
[In, MarshalAs(UnmanagedType.IUnknown)] object view,
ViewVerb verb,
Int32 uReasonCode);
// Command creation callback
[PreserveSig]
Int32 OnCreateUICommand(UInt32 commandId,
CommandTypeID typeID,
[Out] out IUICommandHandler commandHandler);
// Command destroy callback
[PreserveSig]
Int32 OnDestroyUICommand(UInt32 commandId,
CommandTypeID typeID,
[In, Optional] IUICommandHandler commandHandler);
}
[
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("23c8c838-4de6-436b-ab01-5554bb7c30dd")
]
public interface IUIImage
{
[PreserveSig]
Int32 GetBitmap([Out] out IntPtr bitmap);
}
[
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("18aba7f3-4c1c-4ba2-bf6c-f5c3326fa816")
]
public interface IUIImageFromBitmap
{
IUIImage CreateImage(IntPtr bitmap, ImageCreationOptions options);
}
[
ComImport,
Guid("926749fa-2615-4987-8845-c33e65f2b957")
]
public class UIRibbonFrameworkClass
{
}
[
ComImport,
Guid("0F7434B6-59B6-4250-999E-D168D6AE4293")]
public class UIRibbonImageFromBitmapFactory
{
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Metadata.ManagedReference
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.DocAsCode.DataContracts.Common;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
public static class YamlViewModelExtensions
{
public static bool IsPageLevel(this MemberType type)
{
return type == MemberType.Namespace || type == MemberType.Class || type == MemberType.Enum || type == MemberType.Delegate || type == MemberType.Interface || type == MemberType.Struct;
}
/// <summary>
/// Allow multiple items in one yml file
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool AllowMultipleItems(this MemberType type)
{
return type == MemberType.Class || type == MemberType.Enum || type == MemberType.Delegate || type == MemberType.Interface || type == MemberType.Struct;
}
public static MetadataItem ShrinkToSimpleToc(this MetadataItem item)
{
MetadataItem shrinkedItem = new MetadataItem()
{
Name = item.Name,
DisplayNames = item.DisplayNames,
Items = null
};
if (item.Items == null)
{
return shrinkedItem;
}
if (item.Type == MemberType.Toc || item.Type == MemberType.Namespace)
{
foreach (var i in item.Items)
{
if (shrinkedItem.Items == null)
{
shrinkedItem.Items = new List<MetadataItem>();
}
if (i.IsInvalid)
{
continue;
}
var shrinkedI = i.ShrinkToSimpleToc();
shrinkedItem.Items.Add(shrinkedI);
}
}
return shrinkedItem;
}
/// <summary>
/// Only when Namespace is not empty, return it
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static MetadataItem ShrinkToSimpleTocWithNamespaceNotEmpty(this MetadataItem item)
{
MetadataItem shrinkedItem = new MetadataItem()
{
Name = item.Name,
DisplayNames = item.DisplayNames,
Type = item.Type,
Items = null
};
if (item.Type == MemberType.Toc || item.Type == MemberType.Namespace)
{
if (item.Items != null)
{
foreach (var i in item.Items)
{
if (shrinkedItem.Items == null)
{
shrinkedItem.Items = new List<MetadataItem>();
}
if (i.IsInvalid)
{
continue;
}
var shrinkedI = i.ShrinkToSimpleTocWithNamespaceNotEmpty();
if (shrinkedI != null)
{
shrinkedItem.Items.Add(shrinkedI);
}
}
}
}
if (item.Type == MemberType.Namespace)
{
if (shrinkedItem.Items == null || shrinkedItem.Items.Count == 0)
{
return null;
}
}
return shrinkedItem;
}
public static TocViewModel ToTocViewModel(this MetadataItem item)
{
if (item == null)
{
Debug.Fail("item is null.");
return null;
}
switch (item.Type)
{
case MemberType.Toc:
case MemberType.Namespace:
var result = new List<TocItemViewModel>();
foreach (var child in item.Items)
{
result.Add(child.ToTocItemViewModel());
}
return new TocViewModel(result.OrderBy(s => s.Name));
default:
return null;
}
}
public static TocItemViewModel ToTocItemViewModel(this MetadataItem item)
{
var result = new TocItemViewModel
{
Uid = item.Name,
Name = item.DisplayNames.GetLanguageProperty(SyntaxLanguage.Default),
};
var nameForCSharp = item.DisplayNames.GetLanguageProperty(SyntaxLanguage.CSharp);
if (nameForCSharp != result.Name)
{
result.NameForCSharp = nameForCSharp;
}
var nameForVB = item.DisplayNames.GetLanguageProperty(SyntaxLanguage.VB);
if (nameForVB != result.Name)
{
result.NameForVB = nameForVB;
}
if (item.Items != null)
{
result.Items = item.ToTocViewModel();
}
return result;
}
public static PageViewModel ToPageViewModel(this MetadataItem model)
{
if (model == null)
{
return null;
}
var result = new PageViewModel();
result.Items.Add(model.ToItemViewModel());
if (model.Type.AllowMultipleItems())
{
AddChildren(model, result);
}
foreach (var item in model.References)
{
result.References.Add(item.ToReferenceViewModel());
}
return result;
}
public static ReferenceViewModel ToReferenceViewModel(this KeyValuePair<string, ReferenceItem> model)
{
Debug.Assert(model.Value != null, "Unexpected reference.");
var result = new ReferenceViewModel
{
Uid = model.Key,
CommentId = model.Value.CommentId,
Parent = model.Value.Parent,
Definition = model.Value.Definition,
};
if (model.Value.Parts != null && model.Value.Parts.Count > 0)
{
result.Name = GetName(model.Value, SyntaxLanguage.Default, l => l.DisplayName);
var nameForCSharp = GetName(model.Value, SyntaxLanguage.CSharp, l => l.DisplayName);
if (result.Name != nameForCSharp)
{
result.NameInDevLangs[Constants.DevLang.CSharp] = nameForCSharp;
}
var nameForVB = GetName(model.Value, SyntaxLanguage.VB, l => l.DisplayName);
if (result.Name != nameForVB)
{
result.NameInDevLangs[Constants.DevLang.VB] = nameForVB;
}
result.NameWithType = GetName(model.Value, SyntaxLanguage.Default, l => l.DisplayNamesWithType);
var nameWithTypeForCSharp = GetName(model.Value, SyntaxLanguage.CSharp, l => l.DisplayNamesWithType);
if (result.NameWithType != nameWithTypeForCSharp)
{
result.NameWithTypeInDevLangs[Constants.DevLang.CSharp] = nameWithTypeForCSharp;
}
var nameWithTypeForVB = GetName(model.Value, SyntaxLanguage.VB, l => l.DisplayNamesWithType);
if (result.NameWithType != nameWithTypeForVB)
{
result.NameWithTypeInDevLangs[Constants.DevLang.VB] = nameWithTypeForVB;
}
result.FullName = GetName(model.Value, SyntaxLanguage.Default, l => l.DisplayQualifiedNames);
var fullnameForCSharp = GetName(model.Value, SyntaxLanguage.CSharp, l => l.DisplayQualifiedNames);
if (result.FullName != fullnameForCSharp)
{
result.FullNameInDevLangs[Constants.DevLang.CSharp] = fullnameForCSharp;
}
var fullnameForVB = GetName(model.Value, SyntaxLanguage.VB, l => l.DisplayQualifiedNames);
if (result.FullName != fullnameForVB)
{
result.FullNameInDevLangs[Constants.DevLang.VB] = fullnameForVB;
}
result.Specs[Constants.DevLang.CSharp] = GetSpec(model.Value, SyntaxLanguage.CSharp);
result.Specs[Constants.DevLang.VB] = GetSpec(model.Value, SyntaxLanguage.VB);
result.IsExternal = GetIsExternal(model.Value);
result.Href = GetHref(model.Value);
}
return result;
}
public static ItemViewModel ToItemViewModel(this MetadataItem model)
{
if (model == null)
{
return null;
}
var result = new ItemViewModel
{
Uid = model.Name,
CommentId = model.CommentId,
IsExplicitInterfaceImplementation = model.IsExplicitInterfaceImplementation,
IsExtensionMethod = model.IsExtensionMethod,
Parent = model.Parent?.Name,
Children = model.Items?.Select(x => x.Name).OrderBy(s => s).ToList(),
Type = model.Type,
Source = model.Source,
Documentation = model.Documentation,
AssemblyNameList = model.AssemblyNameList,
NamespaceName = model.NamespaceName,
Summary = model.Summary,
Remarks = model.Remarks,
Examples = model.Examples,
Syntax = model.Syntax.ToSyntaxDetailViewModel(),
Overridden = model.Overridden,
Overload = model.Overload,
Exceptions = model.Exceptions,
Sees = model.Sees,
SeeAlsos = model.SeeAlsos,
DerivedClasses = model.DerivedClasses,
Inheritance = model.Inheritance,
Implements = model.Implements,
InheritedMembers = model.InheritedMembers,
ExtensionMethods = model.ExtensionMethods,
Attributes = model.Attributes,
};
result.Id = model.Name.Substring((model.Parent?.Name?.Length ?? -1) + 1);
result.Name = model.DisplayNames.GetLanguageProperty(SyntaxLanguage.Default);
var nameForCSharp = model.DisplayNames.GetLanguageProperty(SyntaxLanguage.CSharp);
if (result.Name != nameForCSharp)
{
result.NameForCSharp = nameForCSharp;
}
var nameForVB = model.DisplayNames.GetLanguageProperty(SyntaxLanguage.VB);
if (result.Name != nameForVB)
{
result.NameForVB = nameForVB;
}
result.NameWithType = model.DisplayNamesWithType.GetLanguageProperty(SyntaxLanguage.Default);
var nameWithTypeForCSharp = model.DisplayNamesWithType.GetLanguageProperty(SyntaxLanguage.CSharp);
if (result.NameWithType != nameWithTypeForCSharp)
{
result.NameWithTypeForCSharp = nameWithTypeForCSharp;
}
var nameWithTypeForVB = model.DisplayNamesWithType.GetLanguageProperty(SyntaxLanguage.VB);
if (result.NameWithType != nameWithTypeForVB)
{
result.NameWithTypeForVB = nameWithTypeForVB;
}
result.FullName = model.DisplayQualifiedNames.GetLanguageProperty(SyntaxLanguage.Default);
var fullnameForCSharp = model.DisplayQualifiedNames.GetLanguageProperty(SyntaxLanguage.CSharp);
if (result.FullName != fullnameForCSharp)
{
result.FullNameForCSharp = fullnameForCSharp;
}
var fullnameForVB = model.DisplayQualifiedNames.GetLanguageProperty(SyntaxLanguage.VB);
if (result.FullName != fullnameForVB)
{
result.FullNameForVB = fullnameForVB;
}
var modifierCSharp = model.Modifiers.GetLanguageProperty(SyntaxLanguage.CSharp);
if (modifierCSharp?.Count > 0)
{
result.Modifiers["csharp"] = modifierCSharp;
}
var modifierForVB = model.Modifiers.GetLanguageProperty(SyntaxLanguage.VB);
if (modifierForVB?.Count > 0)
{
result.Modifiers["vb"] = modifierForVB;
}
return result;
}
public static SyntaxDetailViewModel ToSyntaxDetailViewModel(this SyntaxDetail model)
{
if (model == null)
{
return null;
}
var result = new SyntaxDetailViewModel
{
Parameters = model.Parameters,
TypeParameters = model.TypeParameters,
Return = model.Return,
};
if (model.Content != null && model.Content.Count > 0)
{
result.Content = model.Content.GetLanguageProperty(SyntaxLanguage.Default);
var contentForCSharp = model.Content.GetLanguageProperty(SyntaxLanguage.CSharp);
if (result.Content != contentForCSharp)
{
result.ContentForCSharp = contentForCSharp;
}
var contentForVB = model.Content.GetLanguageProperty(SyntaxLanguage.VB);
if (result.Content != contentForVB)
{
result.ContentForVB = contentForVB;
}
}
return result;
}
public static SpecViewModel ToSpecViewModel(this LinkItem model)
{
if (model == null)
{
return null;
}
var result = new SpecViewModel
{
Uid = model.Name,
Name = model.DisplayName,
NameWithType = model.DisplayNamesWithType,
FullName = model.DisplayQualifiedNames,
IsExternal = model.IsExternalPath,
Href = model.Href,
};
return result;
}
public static TValue GetLanguageProperty<TValue>(this SortedList<SyntaxLanguage, TValue> dict, SyntaxLanguage language, TValue defaultValue = null)
where TValue : class
{
if (dict.TryGetValue(language, out TValue result))
{
return result;
}
if (language == SyntaxLanguage.Default && dict.Count > 0)
{
return dict.Values[0];
}
return defaultValue;
}
private static void AddChildren(MetadataItem model, PageViewModel result)
{
if (model.Items != null && model.Items.Count > 0)
{
foreach (var item in model.Items)
{
result.Items.Add(item.ToItemViewModel());
AddChildren(item, result);
}
}
}
private static string GetName(ReferenceItem reference, SyntaxLanguage language, Converter<LinkItem, string> getName)
{
var list = reference.Parts.GetLanguageProperty(language);
if (list == null)
{
return null;
}
if (list.Count == 0)
{
Debug.Fail("Unexpected reference.");
return null;
}
if (list.Count == 1)
{
return getName(list[0]);
}
return string.Concat(list.ConvertAll(item => getName(item)).ToArray());
}
private static List<SpecViewModel> GetSpec(ReferenceItem reference, SyntaxLanguage language)
{
var list = reference.Parts.GetLanguageProperty(language);
if (list == null || list.Count <= 1)
{
return null;
}
return list.ConvertAll(s => s.ToSpecViewModel());
}
private static bool? GetIsExternal(ReferenceItem reference)
{
if (reference.IsDefinition != true)
{
return null;
}
foreach (var list in reference.Parts.Values)
{
foreach (var item in list)
{
if (item.IsExternalPath)
{
return true;
}
}
}
return false;
}
private static string GetHref(ReferenceItem reference)
{
foreach (var list in reference.Parts.Values)
{
foreach (var item in list)
{
if (item.Href != null)
{
return item.Href;
}
}
}
return null;
}
}
}
| |
//////////////////////////////////////////////////////////////////////////////////
// DataTypes.cs
// Managed Wiimote Library
// Written by Brian Peek (http://www.brianpeek.com/)
// for MSDN's Coding4Fun (http://msdn.microsoft.com/coding4fun/)
// Visit http://blogs.msdn.com/coding4fun/archive/2007/03/14/1879033.aspx
// and http://www.codeplex.com/WiimoteLib
// for more information
//////////////////////////////////////////////////////////////////////////////////
using System;
// if we're building the MSRS version, we need to bring in the MSRS Attributes
// if we're not doing the MSRS build then define some fake attribute classes for DataMember/DataContract
#if MSRS
using Microsoft.Dss.Core.Attributes;
#else
sealed class DataContract : Attribute
{
}
sealed class DataMember: Attribute
{
}
#endif
namespace BlenderWiiMoteInterface.WiimoteLib
{
#if MSRS
[DataContract]
public struct RumbleRequest
{
[DataMember]
public bool Rumble;
}
#endif
/// <summary>
/// Point structure for floating point 2D positions (X, Y)
/// </summary>
[Serializable]
[DataContract]
public struct PointF
{
/// <summary>
/// X, Y coordinates of this point
/// </summary>
[DataMember]
public float X, Y;
/// <summary>
/// Convert to human-readable string
/// </summary>
/// <returns>A string that represents the point</returns>
public override string ToString()
{
return string.Format("{{X={0}, Y={1}}}", X, Y);
}
}
/// <summary>
/// Point structure for int 2D positions (X, Y)
/// </summary>
[Serializable]
[DataContract]
public struct Point
{
/// <summary>
/// X, Y coordinates of this point
/// </summary>
[DataMember]
public int X, Y;
/// <summary>
/// Convert to human-readable string
/// </summary>
/// <returns>A string that represents the point.</returns>
public override string ToString()
{
return string.Format("{{X={0}, Y={1}}}", X, Y);
}
}
/// <summary>
/// Point structure for floating point 3D positions (X, Y, Z)
/// </summary>
[Serializable]
[DataContract]
public struct Point3F
{
/// <summary>
/// X, Y, Z coordinates of this point
/// </summary>
[DataMember]
public float X, Y, Z;
/// <summary>
/// Convert to human-readable string
/// </summary>
/// <returns>A string that represents the point</returns>
public override string ToString()
{
return string.Format("{{X={0}, Y={1}, Z={2}}}", X, Y, Z);
}
}
/// <summary>
/// Point structure for int 3D positions (X, Y, Z)
/// </summary>
[Serializable]
[DataContract]
public struct Point3
{
/// <summary>
/// X, Y, Z coordinates of this point
/// </summary>
[DataMember]
public int X, Y, Z;
/// <summary>
/// Convert to human-readable string
/// </summary>
/// <returns>A string that represents the point.</returns>
public override string ToString()
{
return string.Format("{{X={0}, Y={1}, Z={2}}}", X, Y, Z);
}
}
/// <summary>
/// Current overall state of the Wiimote and all attachments
/// </summary>
[Serializable]
[DataContract]
public class WiimoteState
{
/// <summary>
/// Current calibration information
/// </summary>
[DataMember]
public AccelCalibrationInfo AccelCalibrationInfo;
/// <summary>
/// Current state of accelerometers
/// </summary>
[DataMember]
public AccelState AccelState;
/// <summary>
/// Current state of buttons
/// </summary>
[DataMember]
public ButtonState ButtonState;
/// <summary>
/// Current state of IR sensors
/// </summary>
[DataMember]
public IRState IRState;
/// <summary>
/// Raw byte value of current battery level
/// </summary>
[DataMember]
public byte BatteryRaw;
/// <summary>
/// Calculated current battery level
/// </summary>
[DataMember]
public float Battery;
/// <summary>
/// Current state of rumble
/// </summary>
[DataMember]
public bool Rumble;
/// <summary>
/// Is an extension controller inserted?
/// </summary>
[DataMember]
public bool Extension;
/// <summary>
/// Extension controller currently inserted, if any
/// </summary>
[DataMember]
public ExtensionType ExtensionType;
/// <summary>
/// Current state of Nunchuk extension
/// </summary>
[DataMember]
public NunchukState NunchukState;
/// <summary>
/// Current state of Classic Controller extension
/// </summary>
[DataMember]
public ClassicControllerState ClassicControllerState;
/// <summary>
/// Current state of Guitar extension
/// </summary>
[DataMember]
public GuitarState GuitarState;
/// <summary>
/// Current state of Drums extension
/// </summary>
[DataMember]
public DrumsState DrumsState;
/// <summary>
/// Current state of the Wii Fit Balance Board
/// </summary>
public BalanceBoardState BalanceBoardState;
/// <summary>
/// Current state of LEDs
/// </summary>
[DataMember]
public LEDState LEDState;
/// <summary>
/// Constructor for WiimoteState class
/// </summary>
public WiimoteState()
{
IRState.IRSensors = new IRSensor[4];
}
}
/// <summary>
/// Current state of LEDs
/// </summary>
[Serializable]
[DataContract]
public struct LEDState
{
/// <summary>
/// LED on the Wiimote
/// </summary>
[DataMember]
public bool LED1, LED2, LED3, LED4;
}
/// <summary>
/// Calibration information stored on the Nunchuk
/// </summary>
[Serializable]
[DataContract]
public struct NunchukCalibrationInfo
{
/// <summary>
/// Accelerometer calibration data
/// </summary>
public AccelCalibrationInfo AccelCalibration;
/// <summary>
/// Joystick X-axis calibration
/// </summary>
[DataMember]
public byte MinX, MidX, MaxX;
/// <summary>
/// Joystick Y-axis calibration
/// </summary>
[DataMember]
public byte MinY, MidY, MaxY;
}
/// <summary>
/// Calibration information stored on the Classic Controller
/// </summary>
[Serializable]
[DataContract]
public struct ClassicControllerCalibrationInfo
{
/// <summary>
/// Left joystick X-axis
/// </summary>
[DataMember]
public byte MinXL, MidXL, MaxXL;
/// <summary>
/// Left joystick Y-axis
/// </summary>
[DataMember]
public byte MinYL, MidYL, MaxYL;
/// <summary>
/// Right joystick X-axis
/// </summary>
[DataMember]
public byte MinXR, MidXR, MaxXR;
/// <summary>
/// Right joystick Y-axis
/// </summary>
[DataMember]
public byte MinYR, MidYR, MaxYR;
/// <summary>
/// Left analog trigger
/// </summary>
[DataMember]
public byte MinTriggerL, MaxTriggerL;
/// <summary>
/// Right analog trigger
/// </summary>
[DataMember]
public byte MinTriggerR, MaxTriggerR;
}
/// <summary>
/// Current state of the Nunchuk extension
/// </summary>
[Serializable]
[DataContract]
public struct NunchukState
{
/// <summary>
/// Calibration data for Nunchuk extension
/// </summary>
[DataMember]
public NunchukCalibrationInfo CalibrationInfo;
/// <summary>
/// State of accelerometers
/// </summary>
[DataMember]
public AccelState AccelState;
/// <summary>
/// Raw joystick position before normalization. Values range between 0 and 255.
/// </summary>
[DataMember]
public Point RawJoystick;
/// <summary>
/// Normalized joystick position. Values range between -0.5 and 0.5
/// </summary>
[DataMember]
public PointF Joystick;
/// <summary>
/// Digital button on Nunchuk extension
/// </summary>
[DataMember]
public bool C, Z;
}
/// <summary>
/// Curernt button state of the Classic Controller
/// </summary>
[Serializable]
[DataContract]
public struct ClassicControllerButtonState
{
/// <summary>
/// Digital button on the Classic Controller extension
/// </summary>
[DataMember]
public bool A, B, Plus, Home, Minus, Up, Down, Left, Right, X, Y, ZL, ZR;
/// <summary>
/// Analog trigger - false if released, true for any pressure applied
/// </summary>
[DataMember]
public bool TriggerL, TriggerR;
}
/// <summary>
/// Current state of the Classic Controller
/// </summary>
[Serializable]
[DataContract]
public struct ClassicControllerState
{
/// <summary>
/// Calibration data for Classic Controller extension
/// </summary>
[DataMember]
public ClassicControllerCalibrationInfo CalibrationInfo;
/// <summary>
/// Current button state
/// </summary>
[DataMember]
public ClassicControllerButtonState ButtonState;
/// <summary>
/// Raw value of left joystick. Values range between 0 - 255.
/// </summary>
[DataMember]
public Point RawJoystickL;
/// <summary>
/// Raw value of right joystick. Values range between 0 - 255.
/// </summary>
[DataMember]
public Point RawJoystickR;
/// <summary>
/// Normalized value of left joystick. Values range between -0.5 - 0.5
/// </summary>
[DataMember]
public PointF JoystickL;
/// <summary>
/// Normalized value of right joystick. Values range between -0.5 - 0.5
/// </summary>
[DataMember]
public PointF JoystickR;
/// <summary>
/// Raw value of analog trigger. Values range between 0 - 255.
/// </summary>
[DataMember]
public byte RawTriggerL, RawTriggerR;
/// <summary>
/// Normalized value of analog trigger. Values range between 0.0 - 1.0.
/// </summary>
[DataMember]
public float TriggerL, TriggerR;
}
/// <summary>
/// Current state of the Guitar controller
/// </summary>
[Serializable]
[DataContract]
public struct GuitarState
{
/// <summary>
/// Guitar type
/// </summary>
[DataMember]
public GuitarType GuitarType;
/// <summary>
/// Current button state of the Guitar
/// </summary>
[DataMember]
public GuitarButtonState ButtonState;
/// <summary>
/// Current fret button state of the Guitar
/// </summary>
[DataMember]
public GuitarFretButtonState FretButtonState;
/// <summary>
/// Current touchbar state of the Guitar
/// </summary>
[DataMember]
public GuitarFretButtonState TouchbarState;
/// <summary>
/// Raw joystick position. Values range between 0 - 63.
/// </summary>
[DataMember]
public Point RawJoystick;
/// <summary>
/// Normalized value of joystick position. Values range between 0.0 - 1.0.
/// </summary>
[DataMember]
public PointF Joystick;
/// <summary>
/// Raw whammy bar position. Values range between 0 - 10.
/// </summary>
[DataMember]
public byte RawWhammyBar;
/// <summary>
/// Normalized value of whammy bar position. Values range between 0.0 - 1.0.
/// </summary>
[DataMember]
public float WhammyBar;
}
/// <summary>
/// Current fret button state of the Guitar controller
/// </summary>
[Serializable]
[DataContract]
public struct GuitarFretButtonState
{
/// <summary>
/// Fret buttons
/// </summary>
[DataMember]
public bool Green, Red, Yellow, Blue, Orange;
}
/// <summary>
/// Current button state of the Guitar controller
/// </summary>
[Serializable]
[DataContract]
public struct GuitarButtonState
{
/// <summary>
/// Strum bar
/// </summary>
[DataMember]
public bool StrumUp, StrumDown;
/// <summary>
/// Other buttons
/// </summary>
[DataMember]
public bool Minus, Plus;
}
/// <summary>
/// Current state of the Drums controller
/// </summary>
[Serializable]
[DataContract]
public struct DrumsState
{
/// <summary>
/// Drum pads
/// </summary>
public bool Red, Green, Blue, Orange, Yellow, Pedal;
/// <summary>
/// Speed at which the pad is hit. Values range from 0 (very hard) to 6 (very soft)
/// </summary>
public int RedVelocity, GreenVelocity, BlueVelocity, OrangeVelocity, YellowVelocity, PedalVelocity;
/// <summary>
/// Other buttons
/// </summary>
public bool Plus, Minus;
/// <summary>
/// Raw value of analong joystick. Values range from 0 - 15
/// </summary>
public Point RawJoystick;
/// <summary>
/// Normalized value of analog joystick. Values range from 0.0 - 1.0
/// </summary>
public PointF Joystick;
}
/// <summary>
/// Current state of the Wii Fit Balance Board controller
/// </summary>
[Serializable]
[DataContract]
public struct BalanceBoardState
{
/// <summary>
/// Calibration information for the Balance Board
/// </summary>
[DataMember]
public BalanceBoardCalibrationInfo CalibrationInfo;
/// <summary>
/// Raw values of each sensor
/// </summary>
[DataMember]
public BalanceBoardSensors SensorValuesRaw;
/// <summary>
/// Kilograms per sensor
/// </summary>
[DataMember]
public BalanceBoardSensorsF SensorValuesKg;
/// <summary>
/// Pounds per sensor
/// </summary>
[DataMember]
public BalanceBoardSensorsF SensorValuesLb;
/// <summary>
/// Total kilograms on the Balance Board
/// </summary>
[DataMember]
public float WeightKg;
/// <summary>
/// Total pounds on the Balance Board
/// </summary>
[DataMember]
public float WeightLb;
/// <summary>
/// Center of gravity of Balance Board user
/// </summary>
[DataMember]
public PointF CenterOfGravity;
}
/// <summary>
/// Calibration information
/// </summary>
[Serializable]
[DataContract]
public struct BalanceBoardCalibrationInfo
{
/// <summary>
/// Calibration information at 0kg
/// </summary>
[DataMember]
public BalanceBoardSensors Kg0;
/// <summary>
/// Calibration information at 17kg
/// </summary>
[DataMember]
public BalanceBoardSensors Kg17;
/// <summary>
/// Calibration information at 34kg
/// </summary>
[DataMember]
public BalanceBoardSensors Kg34;
}
/// <summary>
/// The 4 sensors on the Balance Board (short values)
/// </summary>
[Serializable]
[DataContract]
public struct BalanceBoardSensors
{
/// <summary>
/// Sensor at top right
/// </summary>
[DataMember]
public short TopRight;
/// <summary>
/// Sensor at top left
/// </summary>
[DataMember]
public short TopLeft;
/// <summary>
/// Sensor at bottom right
/// </summary>
[DataMember]
public short BottomRight;
/// <summary>
/// Sensor at bottom left
/// </summary>
[DataMember]
public short BottomLeft;
}
/// <summary>
/// The 4 sensors on the Balance Board (float values)
/// </summary>
[Serializable]
[DataContract]
public struct BalanceBoardSensorsF
{
/// <summary>
/// Sensor at top right
/// </summary>
[DataMember]
public float TopRight;
/// <summary>
/// Sensor at top left
/// </summary>
[DataMember]
public float TopLeft;
/// <summary>
/// Sensor at bottom right
/// </summary>
[DataMember]
public float BottomRight;
/// <summary>
/// Sensor at bottom left
/// </summary>
[DataMember]
public float BottomLeft;
}
/// <summary>
/// Current state of a single IR sensor
/// </summary>
[Serializable]
[DataContract]
public struct IRSensor
{
/// <summary>
/// Raw values of individual sensor. Values range between 0 - 1023 on the X axis and 0 - 767 on the Y axis.
/// </summary>
[DataMember]
public Point RawPosition;
/// <summary>
/// Normalized values of the sensor position. Values range between 0.0 - 1.0.
/// </summary>
[DataMember]
public PointF Position;
/// <summary>
/// Size of IR Sensor. Values range from 0 - 15
/// </summary>
[DataMember]
public int Size;
/// <summary>
/// IR sensor seen
/// </summary>
[DataMember]
public bool Found;
/// <summary>
/// Convert to human-readable string
/// </summary>
/// <returns>A string that represents the point.</returns>
public override string ToString()
{
return string.Format("{{{0}, Size={1}, Found={2}}}", Position, Size, Found);
}
}
/// <summary>
/// Current state of the IR camera
/// </summary>
[Serializable]
[DataContract]
public struct IRState
{
/// <summary>
/// Current mode of IR sensor data
/// </summary>
[DataMember]
public IRMode Mode;
/// <summary>
/// Current state of IR sensors
/// </summary>
[DataMember]
public IRSensor[] IRSensors;
/// <summary>
/// Raw midpoint of IR sensors 1 and 2 only. Values range between 0 - 1023, 0 - 767
/// </summary>
[DataMember]
public Point RawMidpoint;
/// <summary>
/// Normalized midpoint of IR sensors 1 and 2 only. Values range between 0.0 - 1.0
/// </summary>
[DataMember]
public PointF Midpoint;
}
/// <summary>
/// Current state of the accelerometers
/// </summary>
[Serializable]
[DataContract]
public struct AccelState
{
/// <summary>
/// Raw accelerometer data.
/// <remarks>Values range between 0 - 255</remarks>
/// </summary>
[DataMember]
public Point3 RawValues;
/// <summary>
/// Normalized accelerometer data. Values range between 0 - ?, but values > 3 and < -3 are inaccurate.
/// </summary>
[DataMember]
public Point3F Values;
}
/// <summary>
/// Accelerometer calibration information
/// </summary>
[Serializable]
[DataContract]
public struct AccelCalibrationInfo
{
/// <summary>
/// Zero point of accelerometer
/// </summary>
[DataMember]
public byte X0, Y0, Z0;
/// <summary>
/// Gravity at rest of accelerometer
/// </summary>
[DataMember]
public byte XG, YG, ZG;
}
/// <summary>
/// Current button state
/// </summary>
[Serializable]
[DataContract]
public struct ButtonState
{
/// <summary>
/// Digital button on the Wiimote
/// </summary>
[DataMember]
public bool A, B, Plus, Home, Minus, One, Two, Up, Down, Left, Right;
}
/// <summary>
/// The extension plugged into the Wiimote
/// </summary>
[DataContract]
public enum ExtensionType : long
{
/// <summary>
/// No extension
/// </summary>
None = 0x000000000000,
/// <summary>
/// Nunchuk extension
/// </summary>
Nunchuk = 0x0000a4200000,
/// <summary>
/// Classic Controller extension
/// </summary>
ClassicController = 0x0000a4200101,
/// <summary>
/// Guitar controller from Guitar Hero 3/WorldTour
/// </summary>
Guitar = 0x0000a4200103,
/// <summary>
/// Drum controller from Guitar Hero: World Tour
/// </summary>
Drums = 0x0100a4200103,
/// <summary>
/// Wii Fit Balance Board controller
/// </summary>
BalanceBoard = 0x0000a4200402,
/// <summary>
/// Partially inserted extension. This is an error condition.
/// </summary>
ParitallyInserted = 0xffffffffffff
};
/// <summary>
/// The mode of data reported for the IR sensor
/// </summary>
[DataContract]
public enum IRMode : byte
{
/// <summary>
/// IR sensor off
/// </summary>
Off = 0x00,
/// <summary>
/// Basic mode
/// </summary>
Basic = 0x01, // 10 bytes
/// <summary>
/// Extended mode
/// </summary>
Extended = 0x03, // 12 bytes
/// <summary>
/// Full mode (unsupported)
/// </summary>
Full = 0x05, // 16 bytes * 2 (format unknown)
};
/// <summary>
/// The report format in which the Wiimote should return data
/// </summary>
public enum InputReport : byte
{
/// <summary>
/// Status report
/// </summary>
Status = 0x20,
/// <summary>
/// Read data from memory location
/// </summary>
ReadData = 0x21,
/// <summary>
/// Register write complete
/// </summary>
OutputReportAck = 0x22,
/// <summary>
/// Button data only
/// </summary>
Buttons = 0x30,
/// <summary>
/// Button and accelerometer data
/// </summary>
ButtonsAccel = 0x31,
/// <summary>
/// IR sensor and accelerometer data
/// </summary>
IRAccel = 0x33,
/// <summary>
/// Button and extension controller data
/// </summary>
ButtonsExtension = 0x34,
/// <summary>
/// Extension and accelerometer data
/// </summary>
ExtensionAccel = 0x35,
/// <summary>
/// IR sensor, extension controller and accelerometer data
/// </summary>
IRExtensionAccel = 0x37,
};
/// <summary>
/// Sensitivity of the IR camera on the Wiimote
/// </summary>
public enum IRSensitivity
{
/// <summary>
/// Equivalent to level 1 on the Wii console
/// </summary>
WiiLevel1,
/// <summary>
/// Equivalent to level 2 on the Wii console
/// </summary>
WiiLevel2,
/// <summary>
/// Equivalent to level 3 on the Wii console (default)
/// </summary>
WiiLevel3,
/// <summary>
/// Equivalent to level 4 on the Wii console
/// </summary>
WiiLevel4,
/// <summary>
/// Equivalent to level 5 on the Wii console
/// </summary>
WiiLevel5,
/// <summary>
/// Maximum sensitivity
/// </summary>
Maximum
}
/// <summary>
/// Type of guitar extension: Guitar Hero 3 or Guitar Hero World Tour
/// </summary>
public enum GuitarType
{
/// <summary>
/// Guitar Hero 3 guitar controller
/// </summary>
GuitarHero3,
/// <summary>
/// Guitar Hero: World Tour guitar controller
/// </summary>
GuitarHeroWorldTour
}
}
| |
// 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;
internal class TestApp
{
private static int test_0_0(int num, AA init, AA zero)
{
return init.q.val;
}
private static int test_0_1(int num, AA init, AA zero)
{
zero.q.val = num;
return zero.q.val;
}
private static int test_0_2(int num, AA init, AA zero)
{
if (init.q != zero.q)
return 100;
else
return zero.q.val;
}
private static int test_0_3(int num, AA init, AA zero)
{
return init.q.val < num + 1 ? 100 : -1;
}
private static int test_0_4(int num, AA init, AA zero)
{
return (init.q.val > zero.q.val ? 1 : 0) + 99;
}
private static int test_0_5(int num, AA init, AA zero)
{
return (init.q.val ^ zero.q.val) | num;
}
private static int test_0_6(int num, AA init, AA zero)
{
zero.q.val |= init.q.val;
return zero.q.val & num;
}
private static int test_0_7(int num, AA init, AA zero)
{
return init.q.val >> zero.q.val;
}
private static int test_0_8(int num, AA init, AA zero)
{
return AA.a_init[init.q.val].q.val;
}
private static int test_0_9(int num, AA init, AA zero)
{
return AA.aa_init[num - 100, (init.q.val | 1) - 2, 1 + zero.q.val].q.val;
}
private static int test_0_10(int num, AA init, AA zero)
{
object bb = init.q.val;
return (int)bb;
}
private static int test_0_11(int num, AA init, AA zero)
{
double dbl = init.q.val;
return (int)dbl;
}
private static int test_0_12(int num, AA init, AA zero)
{
return AA.call_target(init.q).val;
}
private static int test_0_13(int num, AA init, AA zero)
{
return AA.call_target_ref(ref init.q).val;
}
private static int test_0_14(int num, AA init, AA zero)
{
return init.q.ret_code();
}
private static int test_1_0(int num, ref AA r_init, ref AA r_zero)
{
return r_init.q.val;
}
private static int test_1_1(int num, ref AA r_init, ref AA r_zero)
{
r_zero.q.val = num;
return r_zero.q.val;
}
private static int test_1_2(int num, ref AA r_init, ref AA r_zero)
{
if (r_init.q != r_zero.q)
return 100;
else
return r_zero.q.val;
}
private static int test_1_3(int num, ref AA r_init, ref AA r_zero)
{
return r_init.q.val < num + 1 ? 100 : -1;
}
private static int test_1_4(int num, ref AA r_init, ref AA r_zero)
{
return (r_init.q.val > r_zero.q.val ? 1 : 0) + 99;
}
private static int test_1_5(int num, ref AA r_init, ref AA r_zero)
{
return (r_init.q.val ^ r_zero.q.val) | num;
}
private static int test_1_6(int num, ref AA r_init, ref AA r_zero)
{
r_zero.q.val |= r_init.q.val;
return r_zero.q.val & num;
}
private static int test_1_7(int num, ref AA r_init, ref AA r_zero)
{
return r_init.q.val >> r_zero.q.val;
}
private static int test_1_8(int num, ref AA r_init, ref AA r_zero)
{
return AA.a_init[r_init.q.val].q.val;
}
private static int test_1_9(int num, ref AA r_init, ref AA r_zero)
{
return AA.aa_init[num - 100, (r_init.q.val | 1) - 2, 1 + r_zero.q.val].q.val;
}
private static int test_1_10(int num, ref AA r_init, ref AA r_zero)
{
object bb = r_init.q.val;
return (int)bb;
}
private static int test_1_11(int num, ref AA r_init, ref AA r_zero)
{
double dbl = r_init.q.val;
return (int)dbl;
}
private static int test_1_12(int num, ref AA r_init, ref AA r_zero)
{
return AA.call_target(r_init.q).val;
}
private static int test_1_13(int num, ref AA r_init, ref AA r_zero)
{
return AA.call_target_ref(ref r_init.q).val;
}
private static int test_1_14(int num, ref AA r_init, ref AA r_zero)
{
return r_init.q.ret_code();
}
private static int test_2_0(int num)
{
return AA.a_init[num].q.val;
}
private static int test_2_1(int num)
{
AA.a_zero[num].q.val = num;
return AA.a_zero[num].q.val;
}
private static int test_2_2(int num)
{
if (AA.a_init[num].q != AA.a_zero[num].q)
return 100;
else
return AA.a_zero[num].q.val;
}
private static int test_2_3(int num)
{
return AA.a_init[num].q.val < num + 1 ? 100 : -1;
}
private static int test_2_4(int num)
{
return (AA.a_init[num].q.val > AA.a_zero[num].q.val ? 1 : 0) + 99;
}
private static int test_2_5(int num)
{
return (AA.a_init[num].q.val ^ AA.a_zero[num].q.val) | num;
}
private static int test_2_6(int num)
{
AA.a_zero[num].q.val |= AA.a_init[num].q.val;
return AA.a_zero[num].q.val & num;
}
private static int test_2_7(int num)
{
return AA.a_init[num].q.val >> AA.a_zero[num].q.val;
}
private static int test_2_8(int num)
{
return AA.a_init[AA.a_init[num].q.val].q.val;
}
private static int test_2_9(int num)
{
return AA.aa_init[num - 100, (AA.a_init[num].q.val | 1) - 2, 1 + AA.a_zero[num].q.val].q.val;
}
private static int test_2_10(int num)
{
object bb = AA.a_init[num].q.val;
return (int)bb;
}
private static int test_2_11(int num)
{
double dbl = AA.a_init[num].q.val;
return (int)dbl;
}
private static int test_2_12(int num)
{
return AA.call_target(AA.a_init[num].q).val;
}
private static int test_2_13(int num)
{
return AA.call_target_ref(ref AA.a_init[num].q).val;
}
private static int test_2_14(int num)
{
return AA.a_init[num].q.ret_code();
}
private static int test_3_0(int num)
{
return AA.aa_init[0, num - 1, num / 100].q.val;
}
private static int test_3_1(int num)
{
AA.aa_zero[0, num - 1, num / 100].q.val = num;
return AA.aa_zero[0, num - 1, num / 100].q.val;
}
private static int test_3_2(int num)
{
if (AA.aa_init[0, num - 1, num / 100].q != AA.aa_zero[0, num - 1, num / 100].q)
return 100;
else
return AA.aa_zero[0, num - 1, num / 100].q.val;
}
private static int test_3_3(int num)
{
return AA.aa_init[0, num - 1, num / 100].q.val < num + 1 ? 100 : -1;
}
private static int test_3_4(int num)
{
return (AA.aa_init[0, num - 1, num / 100].q.val > AA.aa_zero[0, num - 1, num / 100].q.val ? 1 : 0) + 99;
}
private static int test_3_5(int num)
{
return (AA.aa_init[0, num - 1, num / 100].q.val ^ AA.aa_zero[0, num - 1, num / 100].q.val) | num;
}
private static int test_3_6(int num)
{
AA.aa_zero[0, num - 1, num / 100].q.val |= AA.aa_init[0, num - 1, num / 100].q.val;
return AA.aa_zero[0, num - 1, num / 100].q.val & num;
}
private static int test_3_7(int num)
{
return AA.aa_init[0, num - 1, num / 100].q.val >> AA.aa_zero[0, num - 1, num / 100].q.val;
}
private static int test_3_8(int num)
{
return AA.a_init[AA.aa_init[0, num - 1, num / 100].q.val].q.val;
}
private static int test_3_9(int num)
{
return AA.aa_init[num - 100, (AA.aa_init[0, num - 1, num / 100].q.val | 1) - 2, 1 + AA.aa_zero[0, num - 1, num / 100].q.val].q.val;
}
private static int test_3_10(int num)
{
object bb = AA.aa_init[0, num - 1, num / 100].q.val;
return (int)bb;
}
private static int test_3_11(int num)
{
double dbl = AA.aa_init[0, num - 1, num / 100].q.val;
return (int)dbl;
}
private static int test_3_12(int num)
{
return AA.call_target(AA.aa_init[0, num - 1, num / 100].q).val;
}
private static int test_3_13(int num)
{
return AA.call_target_ref(ref AA.aa_init[0, num - 1, num / 100].q).val;
}
private static int test_3_14(int num)
{
return AA.aa_init[0, num - 1, num / 100].q.ret_code();
}
private static int test_4_0(int num)
{
return BB.f_init.q.val;
}
private static int test_4_1(int num)
{
BB.f_zero.q.val = num;
return BB.f_zero.q.val;
}
private static int test_4_2(int num)
{
if (BB.f_init.q != BB.f_zero.q)
return 100;
else
return BB.f_zero.q.val;
}
private static int test_4_3(int num)
{
return BB.f_init.q.val < num + 1 ? 100 : -1;
}
private static int test_4_4(int num)
{
return (BB.f_init.q.val > BB.f_zero.q.val ? 1 : 0) + 99;
}
private static int test_4_5(int num)
{
return (BB.f_init.q.val ^ BB.f_zero.q.val) | num;
}
private static int test_4_6(int num)
{
BB.f_zero.q.val |= BB.f_init.q.val;
return BB.f_zero.q.val & num;
}
private static int test_4_7(int num)
{
return BB.f_init.q.val >> BB.f_zero.q.val;
}
private static int test_4_8(int num)
{
return AA.a_init[BB.f_init.q.val].q.val;
}
private static int test_4_9(int num)
{
return AA.aa_init[num - 100, (BB.f_init.q.val | 1) - 2, 1 + BB.f_zero.q.val].q.val;
}
private static int test_4_10(int num)
{
object bb = BB.f_init.q.val;
return (int)bb;
}
private static int test_4_11(int num)
{
double dbl = BB.f_init.q.val;
return (int)dbl;
}
private static int test_4_12(int num)
{
return AA.call_target(BB.f_init.q).val;
}
private static int test_4_13(int num)
{
return AA.call_target_ref(ref BB.f_init.q).val;
}
private static int test_4_14(int num)
{
return BB.f_init.q.ret_code();
}
private static int test_5_0(int num)
{
return ((AA)AA.b_init).q.val;
}
private static int test_6_0(int num, TypedReference tr_init)
{
return __refvalue(tr_init, AA).q.val;
}
private static unsafe int Main()
{
AA.reset();
if (test_0_0(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_0() failed.");
return 101;
}
AA.verify_all(); AA.reset();
if (test_0_1(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_1() failed.");
return 102;
}
AA.verify_all(); AA.reset();
if (test_0_2(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_2() failed.");
return 103;
}
AA.verify_all(); AA.reset();
if (test_0_3(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_3() failed.");
return 104;
}
AA.verify_all(); AA.reset();
if (test_0_4(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_4() failed.");
return 105;
}
AA.verify_all(); AA.reset();
if (test_0_5(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_5() failed.");
return 106;
}
AA.verify_all(); AA.reset();
if (test_0_6(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_6() failed.");
return 107;
}
AA.verify_all(); AA.reset();
if (test_0_7(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_7() failed.");
return 108;
}
AA.verify_all(); AA.reset();
if (test_0_8(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_8() failed.");
return 109;
}
AA.verify_all(); AA.reset();
if (test_0_9(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_9() failed.");
return 110;
}
AA.verify_all(); AA.reset();
if (test_0_10(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_10() failed.");
return 111;
}
AA.verify_all(); AA.reset();
if (test_0_11(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_11() failed.");
return 112;
}
AA.verify_all(); AA.reset();
if (test_0_12(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_12() failed.");
return 113;
}
AA.verify_all(); AA.reset();
if (test_0_13(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_13() failed.");
return 114;
}
AA.verify_all(); AA.reset();
if (test_0_14(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_14() failed.");
return 115;
}
AA.verify_all(); AA.reset();
if (test_1_0(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_0() failed.");
return 116;
}
AA.verify_all(); AA.reset();
if (test_1_1(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_1() failed.");
return 117;
}
AA.verify_all(); AA.reset();
if (test_1_2(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_2() failed.");
return 118;
}
AA.verify_all(); AA.reset();
if (test_1_3(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_3() failed.");
return 119;
}
AA.verify_all(); AA.reset();
if (test_1_4(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_4() failed.");
return 120;
}
AA.verify_all(); AA.reset();
if (test_1_5(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_5() failed.");
return 121;
}
AA.verify_all(); AA.reset();
if (test_1_6(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_6() failed.");
return 122;
}
AA.verify_all(); AA.reset();
if (test_1_7(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_7() failed.");
return 123;
}
AA.verify_all(); AA.reset();
if (test_1_8(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_8() failed.");
return 124;
}
AA.verify_all(); AA.reset();
if (test_1_9(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_9() failed.");
return 125;
}
AA.verify_all(); AA.reset();
if (test_1_10(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_10() failed.");
return 126;
}
AA.verify_all(); AA.reset();
if (test_1_11(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_11() failed.");
return 127;
}
AA.verify_all(); AA.reset();
if (test_1_12(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_12() failed.");
return 128;
}
AA.verify_all(); AA.reset();
if (test_1_13(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_13() failed.");
return 129;
}
AA.verify_all(); AA.reset();
if (test_1_14(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_14() failed.");
return 130;
}
AA.verify_all(); AA.reset();
if (test_2_0(100) != 100)
{
Console.WriteLine("test_2_0() failed.");
return 131;
}
AA.verify_all(); AA.reset();
if (test_2_1(100) != 100)
{
Console.WriteLine("test_2_1() failed.");
return 132;
}
AA.verify_all(); AA.reset();
if (test_2_2(100) != 100)
{
Console.WriteLine("test_2_2() failed.");
return 133;
}
AA.verify_all(); AA.reset();
if (test_2_3(100) != 100)
{
Console.WriteLine("test_2_3() failed.");
return 134;
}
AA.verify_all(); AA.reset();
if (test_2_4(100) != 100)
{
Console.WriteLine("test_2_4() failed.");
return 135;
}
AA.verify_all(); AA.reset();
if (test_2_5(100) != 100)
{
Console.WriteLine("test_2_5() failed.");
return 136;
}
AA.verify_all(); AA.reset();
if (test_2_6(100) != 100)
{
Console.WriteLine("test_2_6() failed.");
return 137;
}
AA.verify_all(); AA.reset();
if (test_2_7(100) != 100)
{
Console.WriteLine("test_2_7() failed.");
return 138;
}
AA.verify_all(); AA.reset();
if (test_2_8(100) != 100)
{
Console.WriteLine("test_2_8() failed.");
return 139;
}
AA.verify_all(); AA.reset();
if (test_2_9(100) != 100)
{
Console.WriteLine("test_2_9() failed.");
return 140;
}
AA.verify_all(); AA.reset();
if (test_2_10(100) != 100)
{
Console.WriteLine("test_2_10() failed.");
return 141;
}
AA.verify_all(); AA.reset();
if (test_2_11(100) != 100)
{
Console.WriteLine("test_2_11() failed.");
return 142;
}
AA.verify_all(); AA.reset();
if (test_2_12(100) != 100)
{
Console.WriteLine("test_2_12() failed.");
return 143;
}
AA.verify_all(); AA.reset();
if (test_2_13(100) != 100)
{
Console.WriteLine("test_2_13() failed.");
return 144;
}
AA.verify_all(); AA.reset();
if (test_2_14(100) != 100)
{
Console.WriteLine("test_2_14() failed.");
return 145;
}
AA.verify_all(); AA.reset();
if (test_3_0(100) != 100)
{
Console.WriteLine("test_3_0() failed.");
return 146;
}
AA.verify_all(); AA.reset();
if (test_3_1(100) != 100)
{
Console.WriteLine("test_3_1() failed.");
return 147;
}
AA.verify_all(); AA.reset();
if (test_3_2(100) != 100)
{
Console.WriteLine("test_3_2() failed.");
return 148;
}
AA.verify_all(); AA.reset();
if (test_3_3(100) != 100)
{
Console.WriteLine("test_3_3() failed.");
return 149;
}
AA.verify_all(); AA.reset();
if (test_3_4(100) != 100)
{
Console.WriteLine("test_3_4() failed.");
return 150;
}
AA.verify_all(); AA.reset();
if (test_3_5(100) != 100)
{
Console.WriteLine("test_3_5() failed.");
return 151;
}
AA.verify_all(); AA.reset();
if (test_3_6(100) != 100)
{
Console.WriteLine("test_3_6() failed.");
return 152;
}
AA.verify_all(); AA.reset();
if (test_3_7(100) != 100)
{
Console.WriteLine("test_3_7() failed.");
return 153;
}
AA.verify_all(); AA.reset();
if (test_3_8(100) != 100)
{
Console.WriteLine("test_3_8() failed.");
return 154;
}
AA.verify_all(); AA.reset();
if (test_3_9(100) != 100)
{
Console.WriteLine("test_3_9() failed.");
return 155;
}
AA.verify_all(); AA.reset();
if (test_3_10(100) != 100)
{
Console.WriteLine("test_3_10() failed.");
return 156;
}
AA.verify_all(); AA.reset();
if (test_3_11(100) != 100)
{
Console.WriteLine("test_3_11() failed.");
return 157;
}
AA.verify_all(); AA.reset();
if (test_3_12(100) != 100)
{
Console.WriteLine("test_3_12() failed.");
return 158;
}
AA.verify_all(); AA.reset();
if (test_3_13(100) != 100)
{
Console.WriteLine("test_3_13() failed.");
return 159;
}
AA.verify_all(); AA.reset();
if (test_3_14(100) != 100)
{
Console.WriteLine("test_3_14() failed.");
return 160;
}
AA.verify_all(); AA.reset();
if (test_4_0(100) != 100)
{
Console.WriteLine("test_4_0() failed.");
return 161;
}
AA.verify_all(); AA.reset();
if (test_4_1(100) != 100)
{
Console.WriteLine("test_4_1() failed.");
return 162;
}
AA.verify_all(); AA.reset();
if (test_4_2(100) != 100)
{
Console.WriteLine("test_4_2() failed.");
return 163;
}
AA.verify_all(); AA.reset();
if (test_4_3(100) != 100)
{
Console.WriteLine("test_4_3() failed.");
return 164;
}
AA.verify_all(); AA.reset();
if (test_4_4(100) != 100)
{
Console.WriteLine("test_4_4() failed.");
return 165;
}
AA.verify_all(); AA.reset();
if (test_4_5(100) != 100)
{
Console.WriteLine("test_4_5() failed.");
return 166;
}
AA.verify_all(); AA.reset();
if (test_4_6(100) != 100)
{
Console.WriteLine("test_4_6() failed.");
return 167;
}
AA.verify_all(); AA.reset();
if (test_4_7(100) != 100)
{
Console.WriteLine("test_4_7() failed.");
return 168;
}
AA.verify_all(); AA.reset();
if (test_4_8(100) != 100)
{
Console.WriteLine("test_4_8() failed.");
return 169;
}
AA.verify_all(); AA.reset();
if (test_4_9(100) != 100)
{
Console.WriteLine("test_4_9() failed.");
return 170;
}
AA.verify_all(); AA.reset();
if (test_4_10(100) != 100)
{
Console.WriteLine("test_4_10() failed.");
return 171;
}
AA.verify_all(); AA.reset();
if (test_4_11(100) != 100)
{
Console.WriteLine("test_4_11() failed.");
return 172;
}
AA.verify_all(); AA.reset();
if (test_4_12(100) != 100)
{
Console.WriteLine("test_4_12() failed.");
return 173;
}
AA.verify_all(); AA.reset();
if (test_4_13(100) != 100)
{
Console.WriteLine("test_4_13() failed.");
return 174;
}
AA.verify_all(); AA.reset();
if (test_4_14(100) != 100)
{
Console.WriteLine("test_4_14() failed.");
return 175;
}
AA.verify_all(); AA.reset();
if (test_5_0(100) != 100)
{
Console.WriteLine("test_5_0() failed.");
return 176;
}
AA.verify_all(); AA.reset();
if (test_6_0(100, __makeref(AA._init)) != 100)
{
Console.WriteLine("test_6_0() failed.");
return 177;
}
AA.verify_all(); Console.WriteLine("All tests passed.");
return 100;
}
}
| |
// 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.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
public partial class CodeGenerationTests
{
public class CSharp
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNamespace()
{
var input = "namespace [|N1|] { }";
var expected = "namespace N1 { namespace N2 { } }";
await TestAddNamespaceAsync(input, expected,
name: "N2");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddField()
{
var input = "class [|C|] { }";
var expected = "class C { public int F; }";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(int)));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStaticField()
{
var input = "class [|C|] { }";
var expected = "class C { private static string F; }";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(string)),
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isStatic: true));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddArrayField()
{
var input = "class [|C|] { }";
var expected = "class C { public int[] F; }";
await TestAddFieldAsync(input, expected,
type: CreateArrayType(typeof(int)));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeField()
{
var input = "class [|C|] { }";
var expected = "class C { public unsafe int F; }";
await TestAddFieldAsync(input, expected,
modifiers: new DeclarationModifiers(isUnsafe: true),
type: GetTypeSymbol(typeof(int)));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddFieldToCompilationUnit()
{
var input = "";
var expected = "public int F;";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(int)), addToCompilationUnit: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructor()
{
var input = "class [|C|] { }";
var expected = "class C { public C() { } }";
await TestAddConstructorAsync(input, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithoutBody()
{
var input = "class [|C|] { }";
var expected = "class C { public C(); }";
await TestAddConstructorAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorResolveNamespaceImport()
{
var input = "class [|C|] { }";
var expected = "using System; class C { public C(DateTime dt, int i) { } }";
await TestAddConstructorAsync(input, expected,
parameters: Parameters(Parameter(typeof(DateTime), "dt"), Parameter(typeof(int), "i")));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddChainedConstructor()
{
var input = "class [|C|] { public C(int i) { } }";
var expected = "class C { public C() : this(42) { } public C(int i) { } }";
await TestAddConstructorAsync(input, expected,
thisArguments: new[] { CS.SyntaxFactory.ParseExpression("42") });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStaticConstructor()
{
var input = "class [|C|] { }";
var expected = "class C { static C() { } }";
await TestAddConstructorAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544082)]
public async Task AddClass()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public class C
{
}
}";
await TestAddNamedTypeAsync(input, expected,
compareTokens: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassEscapeName()
{
var input = "namespace [|N|] { }";
var expected = "namespace N { public class @class { } }";
await TestAddNamedTypeAsync(input, expected,
name: "class");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassUnicodeName()
{
var input = "namespace [|N|] { }";
var expected = "namespace N { public class class\u00E6\u00F8\u00E5 { } }";
await TestAddNamedTypeAsync(input, expected,
name: "cl\u0061ss\u00E6\u00F8\u00E5");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544405)]
public async Task AddStaticClass()
{
var input = "namespace [|N|] { }";
var expected = "namespace N { public static class C { } }";
await TestAddNamedTypeAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544405)]
public async Task AddSealedClass()
{
var input = "namespace [|N|] { }";
var expected = "namespace N { private sealed class C { } }";
await TestAddNamedTypeAsync(input, expected,
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isSealed: true));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544405)]
public async Task AddAbstractClass()
{
var input = "namespace [|N|] { }";
var expected = "namespace N { protected internal abstract class C { } }";
await TestAddNamedTypeAsync(input, expected,
accessibility: Accessibility.ProtectedOrInternal,
modifiers: new DeclarationModifiers(isAbstract: true));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStruct()
{
var input = "namespace [|N|] { }";
var expected = "namespace N { internal struct S { } }";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Internal,
typeKind: TypeKind.Struct);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224)]
public async Task AddSealedStruct()
{
var input = "namespace [|N|] { }";
var expected = "namespace N { public struct S { } }";
await TestAddNamedTypeAsync(input, expected,
name: "S",
modifiers: new DeclarationModifiers(isSealed: true),
accessibility: Accessibility.Public,
typeKind: TypeKind.Struct);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddInterface()
{
var input = "namespace [|N|] { }";
var expected = "namespace N { public interface I { } }";
await TestAddNamedTypeAsync(input, expected,
name: "I",
typeKind: TypeKind.Interface);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544080)]
public async Task AddEnum()
{
var input = "namespace [|N|] { }";
var expected = "namespace N { public enum E { } }";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544527)]
public async Task AddEnumWithValues()
{
var input = "namespace [|N|] { }";
var expected = "namespace N { public enum E { F1 = 1, F2 = 2 } }";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", 1), CreateEnumField("F2", 2)));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544080)]
public async Task AddDelegateType()
{
var input = "class [|C|] { }";
var expected = "class C { public delegate int D(string s); }";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224)]
public async Task AddSealedDelegateType()
{
var input = "class [|C|] { }";
var expected = "class C { public delegate int D(string s); }";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
parameters: Parameters(Parameter(typeof(string), "s")),
modifiers: new DeclarationModifiers(isSealed: true));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEvent()
{
var input = "class [|C|] { }";
var expected = "class C { public event System.Action E; }";
await TestAddEventAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeEvent()
{
var input = "class [|C|] { }";
var expected = "class C { public unsafe event System.Action E; }";
await TestAddEventAsync(input, expected,
modifiers: new DeclarationModifiers(isUnsafe: true),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessors()
{
var input = "class [|C|] { }";
var expected = "class C { public event System.Action E { add { } remove { } } }";
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(SpecializedCollections.EmptyList<AttributeData>(), Accessibility.NotApplicable, SpecializedCollections.EmptyList<SyntaxNode>()),
removeMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(SpecializedCollections.EmptyList<AttributeData>(), Accessibility.NotApplicable, SpecializedCollections.EmptyList<SyntaxNode>()),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClass()
{
var input = "class [|C|] { }";
var expected = "class C { public void M() { } }";
await TestAddMethodAsync(input, expected,
returnType: typeof(void));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassEscapedName()
{
var input = "class [|C|] { }";
var expected = "using System; class C { public DateTime @static() { } }";
await TestAddMethodAsync(input, expected,
name: "static",
returnType: typeof(DateTime));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStaticMethodToStruct()
{
var input = "struct [|S|] { }";
var expected = "struct S { public static int M() { $$ } }";
await TestAddMethodAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true),
returnType: typeof(int),
statements: "return 0;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSealedOverrideMethod()
{
var input = "class [|C|] { }";
var expected = "class C { public sealed override int GetHashCode() { $$ } }";
await TestAddMethodAsync(input, expected,
name: "GetHashCode",
modifiers: new DeclarationModifiers(isOverride: true, isSealed: true),
returnType: typeof(int),
statements: "return 0;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAbstractMethod()
{
var input = "abstract class [|C|] { }";
var expected = "abstract class C { public abstract int M(); }";
await TestAddMethodAsync(input, expected,
modifiers: new DeclarationModifiers(isAbstract: true),
returnType: typeof(int));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodWithoutBody()
{
var input = "class [|C|] { }";
var expected = "class C { public int M(); }";
await TestAddMethodAsync(input, expected,
returnType: typeof(int),
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddGenericMethod()
{
var input = "class [|C|] { }";
var expected = "class C { public int M<T>() { $$ } }";
await TestAddMethodAsync(input, expected,
returnType: typeof(int),
typeParameters: new[] { CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T") },
statements: "return new T().GetHashCode();");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddVirtualMethod()
{
var input = "class [|C|] { }";
var expected = "class C { protected virtual int M() { $$ } }";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.Protected,
modifiers: new DeclarationModifiers(isVirtual: true),
returnType: typeof(int),
statements: "return 0;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeNewMethod()
{
var input = "class [|C|] { }";
var expected = "class C { public unsafe new string ToString() { $$ } }";
await TestAddMethodAsync(input, expected,
name: "ToString",
modifiers: new DeclarationModifiers(isNew: true, isUnsafe: true),
returnType: typeof(string),
statements: "return String.Empty;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitImplementationOfUnsafeMethod()
{
var input = "interface I { unsafe void M(int i); } class [|C|] : I { }";
var expected = "interface I { unsafe void M(int i); } class C : I { unsafe void I.M(int i) { } }";
await TestAddMethodAsync(input, expected,
name: "M",
returnType: typeof(void),
parameters: Parameters(Parameter(typeof(int), "i")),
modifiers: new DeclarationModifiers(isUnsafe: true),
explicitInterface: s => s.LookupSymbols(input.IndexOf('M'), null, "M").First() as IMethodSymbol);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitImplementation()
{
var input = "interface I { void M(int i); } class [|C|] : I { }";
var expected = "interface I { void M(int i); } class C : I { void I.M(int i) { } }";
await TestAddMethodAsync(input, expected,
name: "M",
returnType: typeof(void),
parameters: Parameters(Parameter(typeof(int), "i")),
explicitInterface: s => s.LookupSymbols(input.IndexOf('M'), null, "M").First() as IMethodSymbol);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddTrueFalseOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static bool operator true (C other) { $$ }
public static bool operator false (C other) { $$ }
}
";
await TestAddOperatorsAsync(input, expected,
new[] { CodeGenerationOperatorKind.True, CodeGenerationOperatorKind.False },
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "return false;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnaryOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static object operator + (C other) { $$ }
public static object operator - (C other) { $$ }
public static object operator ! (C other) { $$ }
public static object operator ~ (C other) { $$ }
public static object operator ++ (C other) { $$ }
public static object operator -- (C other) { $$ }
}";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.UnaryPlus,
CodeGenerationOperatorKind.UnaryNegation,
CodeGenerationOperatorKind.LogicalNot,
CodeGenerationOperatorKind.OnesComplement,
CodeGenerationOperatorKind.Increment,
CodeGenerationOperatorKind.Decrement
},
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(object),
statements: "return null;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddBinaryOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static object operator + (C a, C b) { $$ }
public static object operator - (C a, C b) { $$ }
public static object operator * (C a, C b) { $$ }
public static object operator / (C a, C b) { $$ }
public static object operator % (C a, C b) { $$ }
public static object operator & (C a, C b) { $$ }
public static object operator | (C a, C b) { $$ }
public static object operator ^ (C a, C b) { $$ }
public static object operator << (C a, C b) { $$ }
public static object operator >> (C a, C b) { $$ }
}";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Addition,
CodeGenerationOperatorKind.Subtraction,
CodeGenerationOperatorKind.Multiplication,
CodeGenerationOperatorKind.Division,
CodeGenerationOperatorKind.Modulus,
CodeGenerationOperatorKind.BitwiseAnd,
CodeGenerationOperatorKind.BitwiseOr,
CodeGenerationOperatorKind.ExclusiveOr,
CodeGenerationOperatorKind.LeftShift,
CodeGenerationOperatorKind.RightShift
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(object),
statements: "return null;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddComparisonOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static bool operator == (C a, C b) { $$ }
public static bool operator != (C a, C b) { $$ }
public static bool operator < (C a, C b) { $$ }
public static bool operator > (C a, C b) { $$ }
public static bool operator <= (C a, C b) { $$ }
public static bool operator >= (C a, C b) { $$ }
}";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Equality,
CodeGenerationOperatorKind.Inequality,
CodeGenerationOperatorKind.GreaterThan,
CodeGenerationOperatorKind.LessThan,
CodeGenerationOperatorKind.LessThanOrEqual,
CodeGenerationOperatorKind.GreaterThanOrEqual
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(bool),
statements: "return true;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsupportedOperator()
{
var input = "class [|C|] { }";
await TestAddUnsupportedOperatorAsync(input,
operatorKind: CodeGenerationOperatorKind.Like,
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(bool),
statements: "return true;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitConversion()
{
var input = @"class [|C|] { }";
var expected = @"class C { public static explicit operator int(C other) { $$ } }";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
statements: "return 0;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddImplicitConversion()
{
var input = @"class [|C|] { }";
var expected = @"class C { public static implicit operator int(C other) { $$ } }";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
isImplicit: true,
statements: "return 0;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatements()
{
var input = "class C { public void [|M|]() { Console.WriteLine(1); } }";
var expected = "class C { public void M() { Console.WriteLine(1); $$ } }";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(2);");
}
[WorkItem(840265)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddDefaultParameterWithNonDefaultValueToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(string text = \"Hello\") { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(string), "text", true, "Hello")));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddDefaultParameterWithDefaultValueToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(double number = default(double)) { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(double), "number", true)));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(int num, string text =\"Hello!\", float floating = 0.5F) { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num"), Parameter(typeof(string), "text", true, "Hello!"), Parameter(typeof(float), "floating", true, .5f)));
}
[WorkItem(841365)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParamsParameterToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(params char[] characters) { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(char[]), "characters", isParams: true)));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544015)]
public async Task AddAutoProperty()
{
var input = "class [|C|] { }";
var expected = "class C { public int P { get; internal set; } }";
await TestAddPropertyAsync(input, expected,
type: typeof(int),
setterAccessibility: Accessibility.Internal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeAutoProperty()
{
var input = "class [|C|] { }";
var expected = "class C { public unsafe int P { get; internal set; } }";
await TestAddPropertyAsync(input, expected,
type: typeof(int),
modifiers: new DeclarationModifiers(isUnsafe: true),
setterAccessibility: Accessibility.Internal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddIndexer()
{
var input = "class [|C|] { }";
var expected = "class C { public string this[int i] { get { $$ } } }";
await TestAddPropertyAsync(input, expected,
type: typeof(string),
parameters: Parameters(Parameter(typeof(int), "i")),
getStatements: "return String.Empty;",
isIndexer: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParameterfulProperty()
{
var input = "class [|C|] { }";
var expected = "class C { public string get_P(int i, int j) { $$ } public void set_P(int i, int j, string value) { } }";
await TestAddPropertyAsync(input, expected,
type: typeof(string),
getStatements: "return String.Empty;",
setStatements: "",
parameters: Parameters(Parameter(typeof(int), "i"), Parameter(typeof(int), "j")));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToTypes()
{
var input = "class [|C|] { }";
var expected = "[System.Serializable] class C { }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromTypes()
{
var input = @"[System.Serializable] class [|C|] { }";
var expected = "class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToMethods()
{
var input = "class C { public void [|M()|] { } }";
var expected = "class C { [System.Serializable] public void M() { } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromMethods()
{
var input = "class C { [System.Serializable] public void [|M()|] { } }";
var expected = "class C { public void M() { } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToFields()
{
var input = "class C { [|public int F|]; }";
var expected = "class C { [System.Serializable] public int F; }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromFields()
{
var input = "class C { [System.Serializable] public int [|F|]; }";
var expected = "class C { public int F; }";
await TestRemoveAttributeAsync<FieldDeclarationSyntax>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToProperties()
{
var input = "class C { public int [|P|] { get; set; }}";
var expected = "class C { [System.Serializable] public int P { get; set; } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromProperties()
{
var input = "class C { [System.Serializable] public int [|P|] { get; set; }}";
var expected = "class C { public int P { get; set; } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToPropertyAccessor()
{
var input = "class C { public int P { [|get|]; set; }}";
var expected = "class C { public int P { [System.Serializable] get; set; } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromPropertyAccessor()
{
var input = "class C { public int P { [System.Serializable] [|get|]; set; } }";
var expected = "class C { public int P { get; set; } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnums()
{
var input = "enum [|C|] { One, Two }";
var expected = "[System.Serializable] enum C { One, Two }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnums()
{
var input = "[System.Serializable] enum [|C|] { One, Two }";
var expected = "enum C { One, Two }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnumMembers()
{
var input = "enum C { [|One|], Two }";
var expected = "enum C { [System.Serializable] One, Two }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnumMembers()
{
var input = "enum C { [System.Serializable] [|One|], Two }";
var expected = "enum C { One, Two }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToIndexer()
{
var input = "class C { public int [|this[int y]|] { get; set; }}";
var expected = "class C { [System.Serializable] public int this[int y] { get; set; } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromIndexer()
{
var input = "class C { [System.Serializable] public int [|this[int y]|] { get; set; }}";
var expected = "class C { public int this[int y] { get; set; } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToOperator()
{
var input = "class C { public static C operator [|+|] (C c1, C c2) { return new C(); }}";
var expected = "class C { [System.Serializable] public static C operator + (C c1, C c2) { return new C(); } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromOperator()
{
var input = "class C { [System.Serializable] public static C operator [|+|](C c1, C c2) { return new C(); }}";
var expected = "class C { public static C operator +(C c1, C c2) { return new C(); } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToDelegate()
{
var input = "delegate int [|D()|];";
var expected = "[System.Serializable] delegate int D();";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromDelegate()
{
var input = "[System.Serializable] delegate int [|D()|];";
var expected = "delegate int D();";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToParam()
{
var input = "class C { public void M([|int x|]) { } }";
var expected = "class C { public void M([System.Serializable] int x) { } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromParam()
{
var input = "class C { public void M([System.Serializable] [|int x|]) { } }";
var expected = "class C { public void M(int x) { } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToTypeParam()
{
var input = "class C<[|T|]> { }";
var expected = "class C<[System.Serializable] T> { }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromTypeParam()
{
var input = "class C<[System.Serializable] [|T|]> { }";
var expected = "class C<T> { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToCompilationUnit()
{
var input = "[|class C { } class D {} |]";
var expected = "[assembly: System.Serializable] class C{ } class D {}";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), SyntaxFactory.Token(SyntaxKind.AssemblyKeyword));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeWithWrongTarget()
{
var input = "[|class C { } class D {} |]";
var expected = "";
await Assert.ThrowsAsync<AggregateException>(async () =>
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), SyntaxFactory.Token(SyntaxKind.RefKeyword)));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia()
{
// With trivia.
var input = @"// Comment 1
[System.Serializable] // Comment 2
/* Comment 3*/ class [|C|] { }";
var expected = @"// Comment 1
/* Comment 3*/ class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia_NewLine()
{
// With trivia, redundant newline at end of attribute removed.
var input = @"// Comment 1
[System.Serializable]
/* Comment 3*/ class [|C|] { }";
var expected = @"// Comment 1
/* Comment 3*/ class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributes()
{
// Multiple attributes.
var input = @"// Comment 1
/*Comment2*/[ /*Comment3*/ System.Serializable /*Comment4*/, /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
/* Comment 8*/
class [|C|] { }";
var expected = @"// Comment 1
/*Comment2*/[ /*Comment3*/ /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
/* Comment 8*/
class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributeLists()
{
// Multiple attributes.
var input = @"// Comment 1
/*Comment2*/[ /*Comment3*/ System.Serializable /*Comment4*/, /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
[ /*Comment9*/ System.Obsolete /*Comment10*/] /*Comment11*/
/* Comment12*/
class [|C|] { }";
var expected = @"// Comment 1
/*Comment2*/[ /*Comment3*/ /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
[ /*Comment9*/ System.Obsolete /*Comment10*/] /*Comment11*/
/* Comment12*/
class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateModifiers()
{
var input = @"public static class [|C|] // Comment 1
{
// Comment 2
}";
var expected = @"internal partial sealed class C // Comment 1
{
// Comment 2
}";
var eol = SyntaxFactory.EndOfLine(@"");
var newModifiers = new[] { SyntaxFactory.Token(SyntaxKind.InternalKeyword).WithLeadingTrivia(eol) }.Concat(
CreateModifierTokens(new DeclarationModifiers(isSealed: true, isPartial: true), LanguageNames.CSharp));
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(input, expected, modifiers: newModifiers);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateAccessibility()
{
var input = @"// Comment 0
public static class [|C|] // Comment 1
{
// Comment 2
}";
var expected = @"// Comment 0
internal static class C // Comment 1
{
// Comment 2
}";
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(input, expected, accessibility: Accessibility.Internal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationType()
{
var input = @"
public static class C
{
// Comment 1
public static char [|F|]() { return 0; }
}";
var expected = @"
public static class C
{
// Comment 1
public static int F() { return 0; }
}";
await TestUpdateDeclarationAsync<MethodDeclarationSyntax>(input, expected, getType: GetTypeSymbol(typeof(int)));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationMembers()
{
var input = @"
public static class [|C|]
{
// Comment 0
public int {|RetainedMember:f|};
// Comment 1
public static char F() { return 0; }
}";
var expected = @"
public static class C
{
// Comment 0
public int f;
public int f2;
}";
var getField = CreateField(Accessibility.Public, new DeclarationModifiers(), typeof(int), "f2");
var getMembers = new List<Func<SemanticModel, ISymbol>>();
getMembers.Add(getField);
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(input, expected, getNewMembers: getMembers);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationMembers_DifferentOrder()
{
var input = @"
public static class [|C|]
{
// Comment 0
public int f;
// Comment 1
public static char {|RetainedMember:F|}() { return 0; }
}";
var expected = @"
public static class C
{
public int f2;
// Comment 1
public static char F() { return 0; }
}";
var getField = CreateField(Accessibility.Public, new DeclarationModifiers(), typeof(int), "f2");
var getMembers = new List<Func<SemanticModel, ISymbol>>();
getMembers.Add(getField);
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(input, expected, getNewMembers: getMembers, declareNewMembersAtTop: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortAroundDestructor()
{
var generationSource = "public class [|C|] { public C(){} public int this[int index]{get{return 0;}set{value = 0;}} }";
var initial = "public class [|C|] { ~C(){} }";
var expected = @"
public class C
{
public C(){}
~C(){}
public int this[int index] { get{} set{} }
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortOperators()
{
var generationSource = @"
namespace N
{
public class [|C|]
{
// Unary operators
public static bool operator false (C other) { return false; }
public static bool operator true (C other) { return true; }
public static C operator ++ (C other) { return null; }
public static C operator -- (C other) { return null; }
public static C operator ~ (C other) { return null; }
public static C operator ! (C other) { return null; }
public static C operator - (C other) { return null; }
public static C operator + (C other) { return null; }
// Binary operators
public static C operator >> (C a, int shift) { return null; }
public static C operator << (C a, int shift) { return null; }
public static C operator ^ (C a, C b) { return null; }
public static C operator | (C a, C b) { return null; }
public static C operator & (C a, C b) { return null; }
public static C operator % (C a, C b) { return null; }
public static C operator / (C a, C b) { return null; }
public static C operator * (C a, C b) { return null; }
public static C operator - (C a, C b) { return null; }
public static C operator + (C a, C b) { return null; }
// Comparison operators
public static bool operator >= (C a, C b) { return true; }
public static bool operator <= (C a, C b) { return true; }
public static bool operator > (C a, C b) { return true; }
public static bool operator < (C a, C b) { return true; }
public static bool operator != (C a, C b) { return true; }
public static bool operator == (C a, C b) { return true; }
}
}";
var initial = "namespace [|N|] { }";
var expected = @"
namespace N
{
public class C
{
public static C operator +(C other);
public static C operator +(C a, C b);
public static C operator -(C other);
public static C operator -(C a, C b);
public static C operator !(C other);
public static C operator ~(C other);
public static C operator ++(C other);
public static C operator --(C other);
public static C operator *(C a, C b);
public static C operator /(C a, C b);
public static C operator %(C a, C b);
public static C operator &(C a, C b);
public static C operator |(C a, C b);
public static C operator ^(C a, C b);
public static C operator <<(C a, int shift);
public static C operator >>(C a, int shift);
public static bool operator ==(C a, C b);
public static bool operator !=(C a, C b);
public static bool operator <(C a, C b);
public static bool operator >(C a, C b);
public static bool operator <=(C a, C b);
public static bool operator >=(C a, C b);
public static bool operator true(C other);
public static bool operator false(C other);
}
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
forceLanguage: LanguageNames.CSharp,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
}
[WorkItem(665008)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestExtensionMethods()
{
var generationSource = @"
public static class [|C|]
{
public static void ExtMethod1(this string s, int y, string z) {}
}";
var initial = "public static class [|C|] {}";
var expected = @"
public static class C
{
public static void ExtMethod1(this string s, int y, string z);
}
";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
[WorkItem(530829)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestVBPropertiesWithParams()
{
var generationSource = @"
Namespace N
Public Class [|C|]
Public Overridable Property IndexProp(ByVal p1 As Integer) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class
End Namespace
";
var initial = "namespace [|N|] {}";
var expected = @"
namespace N
{
public class C
{
public virtual string get_IndexProp ( int p1 ) ;
public virtual void set_IndexProp ( int p1 , string value ) ;
}
}
";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[WorkItem(812738)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestRefParamsWithDefaultValue()
{
var generationSource = @"
Public Class [|C|]
Public Sub Foo(x As Integer, Optional ByRef y As Integer = 10, Optional ByRef z As Object = Nothing)
End Sub
End Class";
var initial = "public class [|C|] {}";
var expected = @"
public class C
{
public void Foo(int x, ref int y, ref object z);
}
";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
[WorkItem(848357)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestConstraints()
{
var generationSource = @"
namespace N
{
public class [|C|]<T, U> where T : struct where U : class
{
public void Foo<Q, R>() where Q : new() where R : IComparable { }
public delegate void D<T, U>(T t, U u) where T : struct where U : class;
}
}
";
var initial = "namespace [|N|] {}";
var expected = @"
namespace N
{
public class C<T, U> where T : struct where U : class
{
public void Foo<Q, R>() where Q : new() where R : IComparable;
public delegate void D<T, U>(T t, U u) where T : struct where U : class;
}
}
";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
}
}
| |
namespace Ioke.Math {
using System;
using System.Text;
class Conversion {
private Conversion() {}
internal static readonly int[] digitFitInInt = { -1, -1, 31, 19, 15, 13, 11,
11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 5 };
internal static readonly int[] bigRadices = { -2147483648, 1162261467,
1073741824, 1220703125, 362797056, 1977326743, 1073741824,
387420489, 1000000000, 214358881, 429981696, 815730721, 1475789056,
170859375, 268435456, 410338673, 612220032, 893871739, 1280000000,
1801088541, 113379904, 148035889, 191102976, 244140625, 308915776,
387420489, 481890304, 594823321, 729000000, 887503681, 1073741824,
1291467969, 1544804416, 1838265625, 60466176 };
internal static String bigInteger2String(BigInteger val, int radix) {
int sign = val.sign;
int numberLength = val.numberLength;
int[] digits = val.digits;
if (sign == 0) {
return "0"; //$NON-NLS-1$
}
if (numberLength == 1) {
int highDigit = digits[numberLength - 1];
long v = highDigit & 0xFFFFFFFFL;
if (sign < 0) {
v = -v;
}
return Convert.ToString(v, radix);
}
if ((radix == 10) || (radix < 0)
|| (radix > 26)) {
return val.ToString();
}
double bitsForRadixDigit;
bitsForRadixDigit = Math.Log(radix) / Math.Log(2);
int resLengthInChars = (int) (val.abs().bitLength() / bitsForRadixDigit + ((sign < 0) ? 1
: 0)) + 1;
char[] result = new char[resLengthInChars];
int currentChar = resLengthInChars;
int resDigit;
if (radix != 16) {
int[] temp = new int[numberLength];
Array.Copy(digits, 0, temp, 0, numberLength);
int tempLen = numberLength;
int charsPerInt = digitFitInInt[radix];
int i;
// get the maximal power of radix that fits in int
int bigRadix = bigRadices[radix - 2];
while (true) {
// divide the array of digits by bigRadix and convert remainders
// to characters collecting them in the char array
resDigit = Division.divideArrayByInt(temp, temp, tempLen,
bigRadix);
int previous = currentChar;
do {
result[--currentChar] = Convert.ToString(resDigit % radix, radix)[0];
} while (((resDigit /= radix) != 0) && (currentChar != 0));
int delta = charsPerInt - previous + currentChar;
for (i = 0; i < delta && currentChar > 0; i++) {
result[--currentChar] = '0';
}
for (i = tempLen - 1; (i > 0) && (temp[i] == 0); i--) {
;
}
tempLen = i + 1;
if ((tempLen == 1) && (temp[0] == 0)) { // the quotient is 0
break;
}
}
} else {
// radix == 16
for (int i = 0; i < numberLength; i++) {
for (int j = 0; (j < 8) && (currentChar > 0); j++) {
resDigit = digits[i] >> (j << 2) & 0xf;
result[--currentChar] = Convert.ToString(resDigit % radix, 16)[0];
}
}
}
while (result[currentChar] == '0') {
currentChar++;
}
if (sign == -1) {
result[--currentChar] = '-';
}
return new String(result, currentChar, resLengthInChars - currentChar);
}
internal static String toDecimalScaledString(BigInteger val, int scale) {
int sign = val.sign;
int numberLength = val.numberLength;
int[] digits = val.digits;
int resLengthInChars;
int currentChar;
char[] result;
if (sign == 0) {
switch (scale) {
case 0:
return "0"; //$NON-NLS-1$
case 1:
return "0.0"; //$NON-NLS-1$
case 2:
return "0.00"; //$NON-NLS-1$
case 3:
return "0.000"; //$NON-NLS-1$
case 4:
return "0.0000"; //$NON-NLS-1$
case 5:
return "0.00000"; //$NON-NLS-1$
case 6:
return "0.000000"; //$NON-NLS-1$
default:
StringBuilder result1x = new StringBuilder();
if (scale < 0) {
result1x.Append("0E+"); //$NON-NLS-1$
} else {
result1x.Append("0E"); //$NON-NLS-1$
}
result1x.Append(-scale);
return result1x.ToString();
}
}
// one 32-bit unsigned value may contains 10 decimal digits
resLengthInChars = numberLength * 10 + 1 + 7;
// Explanation why +1+7:
// +1 - one char for sign if needed.
// +7 - For "special case 2" (see below) we have 7 free chars for
// inserting necessary scaled digits.
result = new char[resLengthInChars + 1];
// allocated [resLengthInChars+1] characters.
// a free latest character may be used for "special case 1" (see
// below)
currentChar = resLengthInChars;
if (numberLength == 1) {
int highDigit = digits[0];
if (highDigit < 0) {
long v = highDigit & 0xFFFFFFFFL;
do {
long prev = v;
v /= 10;
result[--currentChar] = (char) (0x0030 + ((int) (prev - v * 10)));
} while (v != 0);
} else {
int v = highDigit;
do {
int prev = v;
v /= 10;
result[--currentChar] = (char) (0x0030 + (prev - v * 10));
} while (v != 0);
}
} else {
int[] temp = new int[numberLength];
int tempLen = numberLength;
Array.Copy(digits, temp, tempLen);
while (true) {
// divide the array of digits by bigRadix and convert
// remainders
// to characters collecting them in the char array
long result11 = 0;
for (int i1 = tempLen - 1; i1 >= 0; i1--) {
long temp1 = (result11 << 32)
+ (temp[i1] & 0xFFFFFFFFL);
long res = divideLongByBillion(temp1);
temp[i1] = (int) res;
result11 = (int) (res >> 32);
}
int resDigit = (int) result11;
int previous = currentChar;
do {
result[--currentChar] = (char) (0x0030 + (resDigit % 10));
} while (((resDigit /= 10) != 0) && (currentChar != 0));
int delta = 9 - previous + currentChar;
for (int i = 0; (i < delta) && (currentChar > 0); i++) {
result[--currentChar] = '0';
}
int j = tempLen - 1;
bool bigloop = false;
for (; temp[j] == 0; j--) {
if (j == 0) { // means temp[0] == 0
bigloop = true;
break;
}
}
if(bigloop) break;
tempLen = j + 1;
}
while (result[currentChar] == '0') {
currentChar++;
}
}
bool negNumber = (sign < 0);
int exponent = resLengthInChars - currentChar - scale - 1;
if (scale == 0) {
if (negNumber) {
result[--currentChar] = '-';
}
return new String(result, currentChar, resLengthInChars
- currentChar);
}
if ((scale > 0) && (exponent >= -6)) {
if (exponent >= 0) {
// special case 1
int insertPoint = currentChar + exponent;
for (int j = resLengthInChars - 1; j >= insertPoint; j--) {
result[j + 1] = result[j];
}
result[++insertPoint] = '.';
if (negNumber) {
result[--currentChar] = '-';
}
return new String(result, currentChar, resLengthInChars
- currentChar + 1);
}
// special case 2
for (int j = 2; j < -exponent + 1; j++) {
result[--currentChar] = '0';
}
result[--currentChar] = '.';
result[--currentChar] = '0';
if (negNumber) {
result[--currentChar] = '-';
}
return new String(result, currentChar, resLengthInChars
- currentChar);
}
int startPoint = currentChar + 1;
int endPoint = resLengthInChars;
StringBuilder result1 = new StringBuilder(16 + endPoint - startPoint);
if (negNumber) {
result1.Append('-');
}
if (endPoint - startPoint >= 1) {
result1.Append(result[currentChar]);
result1.Append('.');
result1.Append(result, currentChar + 1, resLengthInChars
- currentChar - 1);
} else {
result1.Append(result, currentChar, resLengthInChars
- currentChar);
}
result1.Append('E');
if (exponent > 0) {
result1.Append('+');
}
result1.Append(exponent.ToString());
return result1.ToString();
}
/* can process only 32-bit numbers */
internal static String toDecimalScaledString(long value, int scale) {
int resLengthInChars;
int currentChar;
char[] result;
bool negNumber = value < 0;
if(negNumber) {
value = -value;
}
if (value == 0) {
switch (scale) {
case 0: return "0"; //$NON-NLS-1$
case 1: return "0.0"; //$NON-NLS-1$
case 2: return "0.00"; //$NON-NLS-1$
case 3: return "0.000"; //$NON-NLS-1$
case 4: return "0.0000"; //$NON-NLS-1$
case 5: return "0.00000"; //$NON-NLS-1$
case 6: return "0.000000"; //$NON-NLS-1$
default:
StringBuilder result1x = new StringBuilder();
if (scale < 0) {
result1x.Append("0E+");
} else {
result1x.Append("0E");
}
result1x.Append( (scale == Int32.MinValue) ? "2147483648" : (-scale).ToString());
return result1x.ToString();
}
}
// one 32-bit unsigned value may contains 10 decimal digits
resLengthInChars = 18;
// Explanation why +1+7:
// +1 - one char for sign if needed.
// +7 - For "special case 2" (see below) we have 7 free chars for
// inserting necessary scaled digits.
result = new char[resLengthInChars+1];
// Allocated [resLengthInChars+1] characters.
// a free latest character may be used for "special case 1" (see below)
currentChar = resLengthInChars;
long v = value;
do {
long prev = v;
v /= 10;
result[--currentChar] = (char) (0x0030 + (prev - v * 10));
} while (v != 0);
long exponent = (long)resLengthInChars - (long)currentChar - scale - 1L;
if (scale == 0) {
if (negNumber) {
result[--currentChar] = '-';
}
return new String(result, currentChar, resLengthInChars - currentChar);
}
if (scale > 0 && exponent >= -6) {
if (exponent >= 0) {
// special case 1
int insertPoint = currentChar + (int) exponent ;
for(int j=resLengthInChars-1; j>=insertPoint; j--) {
result[j+1] = result[j];
}
result[++insertPoint]='.';
if (negNumber) {
result[--currentChar] = '-';
}
return new String(result, currentChar, resLengthInChars - currentChar + 1);
}
// special case 2
for (int j = 2; j < -exponent + 1; j++) {
result[--currentChar] = '0';
}
result[--currentChar] = '.';
result[--currentChar] = '0';
if (negNumber) {
result[--currentChar] = '-';
}
return new String(result, currentChar, resLengthInChars - currentChar);
}
int startPoint = currentChar + 1;
int endPoint = resLengthInChars;
StringBuilder result1 = new StringBuilder(16+endPoint-startPoint);
if (negNumber) {
result1.Append('-');
}
if (endPoint - startPoint >= 1) {
result1.Append(result[currentChar]);
result1.Append('.');
result1.Append(result,currentChar+1,resLengthInChars - currentChar-1);
} else {
result1.Append(result,currentChar,resLengthInChars - currentChar);
}
result1.Append('E');
if (exponent > 0) {
result1.Append('+');
}
result1.Append(exponent.ToString());
return result1.ToString();
}
internal static long divideLongByBillion(long a) {
long quot;
long rem;
if (a >= 0) {
long bLong = 1000000000L;
quot = (a / bLong);
rem = (a % bLong);
} else {
/*
* Make the dividend positive shifting it right by 1 bit then get
* the quotient an remainder and correct them properly
*/
long aPos = (long)(((ulong)a) >> 1);
long bPos = (long)(((ulong)1000000000L) >> 1);
quot = aPos / bPos;
rem = aPos % bPos;
// double the remainder and add 1 if 'a' is odd
rem = (rem << 1) + (a & 1);
}
return ((rem << 32) | (quot & 0xFFFFFFFFL));
}
/** @see BigInteger#doubleValue() */
internal static double bigInteger2Double(BigInteger val) {
// val.bitLength() < 64
if ((val.numberLength < 2)
|| ((val.numberLength == 2) && (val.digits[1] > 0))) {
return val.longValue();
}
// val.bitLength() >= 33 * 32 > 1024
if (val.numberLength > 32) {
return ((val.sign > 0) ? double.PositiveInfinity
: double.NegativeInfinity);
}
return Convert.ToDouble(val.ToString());
}
}
}
| |
//
// System.Net.HttpListenerResponse
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Globalization;
using System.IO;
using System.Text;
using System;
using System.Net;
namespace HTTP.Net
{
internal class HttpListenerResponse : IDisposable, HttpResponse
{
bool disposed;
Encoding content_encoding;
long content_length;
bool cl_set;
string content_type;
CookieCollection cookies;
WebHeaderCollection headers = new WebHeaderCollection ();
bool keep_alive = true;
ResponseStream output_stream;
Version version = HttpVersion.Version11;
string location;
int status_code = 200;
string status_description = "OK";
bool chunked;
MonoContext context;
internal bool HeadersSent;
bool force_close_chunked;
ExtReponse eResp;
internal HttpListenerResponse (MonoContext context)
{
this.context = context;
eResp = new ExtReponse(this);
}
internal bool ForceCloseChunked {
get { return force_close_chunked; }
}
public TextWriter Output { get { return eResp.Output; } }
public string[] FileDependencies { get { return eResp.FileDependencies; } }
public int Expires { get { return eResp.Expires; } set { eResp.Expires = value; } }
public CustomCachePolicy Cache { get { return eResp.Cache; } set { eResp.Cache = value; } }
public Stream Filter { get { return eResp.Filter; } set { eResp.Filter = (InputFilterStream)value; } }
public DateTime ExpiresAbsolute { get { return eResp.Cache.Expires; } set { eResp.Cache.SetExpires(value); } }
public Encoding ContentEncoding {
get {
if (content_encoding == null)
content_encoding = Encoding.Default;
return content_encoding;
}
set {
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
//TODO: is null ok?
if (HeadersSent)
throw new InvalidOperationException ("Cannot be changed after headers are sent.");
content_encoding = value;
}
}
public long ContentLength64 {
get { return content_length; }
set {
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException ("Cannot be changed after headers are sent.");
if (value < 0)
throw new ArgumentOutOfRangeException ("Must be >= 0", "value");
cl_set = true;
content_length = value;
}
}
public string ContentType {
get { return content_type; }
set {
// TODO: is null ok?
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException ("Cannot be changed after headers are sent.");
content_type = value;
}
}
// RFC 2109, 2965 + the netscape specification at http://wp.netscape.com/newsref/std/cookie_spec.html
public CookieCollection Cookies {
get {
if (cookies == null)
cookies = new CookieCollection ();
return cookies;
}
set { cookies = value; } // null allowed?
}
public WebHeaderCollection Headers {
get { return headers; }
set {
/**
* "If you attempt to set a Content-Length, Keep-Alive, Transfer-Encoding, or
* WWW-Authenticate header using the Headers property, an exception will be
* thrown. Use the KeepAlive or ContentLength64 properties to set these headers.
* You cannot set the Transfer-Encoding or WWW-Authenticate headers manually."
*/
// TODO: check if this is marked readonly after headers are sent.
headers = value;
}
}
public bool KeepAlive {
get { return keep_alive; }
set {
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException ("Cannot be changed after headers are sent.");
keep_alive = value;
}
}
public Stream OutputStream {
get {
if (output_stream == null)
output_stream = context.Connection.GetResponseStream ();
return output_stream;
}
}
public Version ProtocolVersion {
get { return version; }
set {
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException ("Cannot be changed after headers are sent.");
if (value == null)
throw new ArgumentNullException ("value");
if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
throw new ArgumentException ("Must be 1.0 or 1.1", "value");
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
version = value;
}
}
public string RedirectLocation {
get { return location; }
set {
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException ("Cannot be changed after headers are sent.");
location = value;
}
}
public bool SendChunked {
get { return chunked; }
set {
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException ("Cannot be changed after headers are sent.");
chunked = value;
}
}
public int StatusCode {
get { return status_code; }
set {
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException ("Cannot be changed after headers are sent.");
if (value < 100 || value > 999)
throw new ProtocolViolationException ("StatusCode must be between 100 and 999.");
status_code = value;
status_description = GetStatusDescription (value);
}
}
internal static string GetStatusDescription (int code)
{
switch (code){
case 100: return "Continue";
case 101: return "Switching Protocols";
case 102: return "Processing";
case 200: return "OK";
case 201: return "Created";
case 202: return "Accepted";
case 203: return "Non-Authoritative Information";
case 204: return "No Content";
case 205: return "Reset Content";
case 206: return "Partial Content";
case 207: return "Multi-Status";
case 300: return "Multiple Choices";
case 301: return "Moved Permanently";
case 302: return "Found";
case 303: return "See Other";
case 304: return "Not Modified";
case 305: return "Use Proxy";
case 307: return "Temporary Redirect";
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 402: return "Payment Required";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 406: return "Not Acceptable";
case 407: return "Proxy Authentication Required";
case 408: return "Request Timeout";
case 409: return "Conflict";
case 410: return "Gone";
case 411: return "Length Required";
case 412: return "Precondition Failed";
case 413: return "Request Entity Too Large";
case 414: return "Request-Uri Too Long";
case 415: return "Unsupported Media Type";
case 416: return "Requested Range Not Satisfiable";
case 417: return "Expectation Failed";
case 422: return "Unprocessable Entity";
case 423: return "Locked";
case 424: return "Failed Dependency";
case 500: return "Internal Server Error";
case 501: return "Not Implemented";
case 502: return "Bad Gateway";
case 503: return "Service Unavailable";
case 504: return "Gateway Timeout";
case 505: return "Http Version Not Supported";
case 507: return "Insufficient Storage";
}
return "";
}
public string StatusDescription {
get { return status_description; }
set {
status_description = value;
}
}
void IDisposable.Dispose ()
{
Close (true); //TODO: Abort or Close?
}
public void Abort ()
{
if (disposed)
return;
Close (true);
}
public void AddHeader (string name, string value)
{
if (name == null)
throw new ArgumentNullException ("name");
if (name == "")
throw new ArgumentException ("'name' cannot be empty", "name");
//TODO: check for forbidden headers and invalid characters
if (value.Length > 65535)
throw new ArgumentOutOfRangeException ("value");
headers.Set (name, value);
}
public void AppendCookie (Cookie cookie)
{
if (cookie == null)
throw new ArgumentNullException ("cookie");
Cookies.Add (cookie);
}
public void AppendHeader (string name, string value)
{
if (name == null)
throw new ArgumentNullException ("name");
if (name == "")
throw new ArgumentException ("'name' cannot be empty", "name");
if (value.Length > 65535)
throw new ArgumentOutOfRangeException ("value");
headers.Add (name, value);
}
void Close (bool force)
{
disposed = true;
context.Connection.Close (force);
}
public void Close ()
{
if (disposed)
return;
Close (false);
}
public void Close (byte [] responseEntity, bool willBlock)
{
if (disposed)
return;
if (responseEntity == null)
throw new ArgumentNullException ("responseEntity");
//TODO: if willBlock -> BeginWrite + Close ?
ContentLength64 = responseEntity.Length;
OutputStream.Write (responseEntity, 0, (int) content_length);
Close (false);
}
public void CopyFrom (HttpListenerResponse templateResponse)
{
headers.Clear ();
headers.Add (templateResponse.headers);
content_length = templateResponse.content_length;
status_code = templateResponse.status_code;
status_description = templateResponse.status_description;
keep_alive = templateResponse.keep_alive;
version = templateResponse.version;
}
public void Redirect (string url)
{
StatusCode = 302; // Found
location = url;
}
bool FindCookie (Cookie cookie)
{
string name = cookie.Name;
string domain = cookie.Domain;
string path = cookie.Path;
foreach (Cookie c in cookies) {
if (name != c.Name)
continue;
if (domain != c.Domain)
continue;
if (path == c.Path)
return true;
}
return false;
}
internal void SendHeaders (bool closing, MemoryStream ms)
{
Encoding encoding = content_encoding;
if (encoding == null)
encoding = Encoding.Default;
if (content_type != null) {
if (content_encoding != null && content_type.IndexOf ("charset=", StringComparison.Ordinal) == -1) {
string enc_name = content_encoding.WebName;
headers.Set("Content-Type", content_type + "; charset=" + enc_name);
} else {
headers.Set("Content-Type", content_type);
}
}
if (headers ["Server"] == null)
headers.Set("Server", "Mono-HTTPAPI/1.0");
CultureInfo inv = CultureInfo.InvariantCulture;
if (headers ["Date"] == null)
headers.Set("Date", DateTime.UtcNow.ToString ("r", inv));
if (!chunked) {
if (!cl_set && closing) {
cl_set = true;
content_length = 0;
}
if (cl_set)
headers.Set("Content-Length", content_length.ToString (inv));
}
Version v = context.Request.ProtocolVersion;
if (!cl_set && !chunked && v >= HttpVersion.Version11)
chunked = true;
/* Apache forces closing the connection for these status codes:
* HttpStatusCode.BadRequest 400
* HttpStatusCode.RequestTimeout 408
* HttpStatusCode.LengthRequired 411
* HttpStatusCode.RequestEntityTooLarge 413
* HttpStatusCode.RequestUriTooLong 414
* HttpStatusCode.InternalServerError 500
* HttpStatusCode.ServiceUnavailable 503
*/
bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
status_code == 413 || status_code == 414 || status_code == 500 ||
status_code == 503);
if (conn_close == false)
conn_close = !context.Request.KeepAlive;
// They sent both KeepAlive: true and Connection: close!?
if (!keep_alive || conn_close) {
headers.Set("Connection", "close");
conn_close = true;
}
if (chunked)
headers.Set("Transfer-Encoding", "chunked");
int reuses = context.Connection.Reuses;
if (reuses >= 100) {
force_close_chunked = true;
if (!conn_close) {
headers.Set("Connection", "close");
conn_close = true;
}
}
if (!conn_close) {
headers.Set ("Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses));
if (context.Request.ProtocolVersion <= HttpVersion.Version10)
headers.Set("Connection", "keep-alive");
}
if (location != null)
headers.Set("Location", location);
//if (cookies != null) { /// TODOOO
// foreach (Cookie cookie in cookies)
// headers.Set("Set-Cookie", cookie.ToClientString ());
//}
StreamWriter writer = new StreamWriter (ms, encoding, 256);
writer.Write ("HTTP/{0} {1} {2}\r\n", version, status_code, status_description);
string headers_str = ToStringMultiValue(headers);
writer.Write (headers_str);
writer.Flush ();
int preamble = (encoding.CodePage == 65001) ? 3 : encoding.GetPreamble ().Length;
if (output_stream == null)
output_stream = context.Connection.GetResponseStream ();
/* Assumes that the ms was at position 0 */
ms.Position = preamble;
HeadersSent = true;
}
private string ToStringMultiValue(WebHeaderCollection wh)
{
StringBuilder sb = new StringBuilder();
int count = wh.Count;
for (int i = 0; i < count; i++)
{
foreach (string v in wh.GetValues(i))
{
sb.Append(wh.GetKey(i))
.Append(": ")
.Append(v)
.Append("\r\n");
}
}
return sb.Append("\r\n").ToString();
}
public void SetCookie (Cookie cookie)
{
if (cookie == null)
throw new ArgumentNullException ("cookie");
if (cookies != null) {
if (FindCookie (cookie))
throw new ArgumentException ("The cookie already exists.");
} else {
cookies = new CookieCollection ();
}
cookies.Add (cookie);
}
}
}
| |
using ImplicitNullability.Plugin.Configuration;
using ImplicitNullability.Plugin.Infrastructure;
using JetBrains.Annotations;
using JetBrains.Diagnostics;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CodeAnnotations;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Util;
using JetBrains.ReSharper.Psi.Util;
using JetBrains.ReSharper.Psi.Xaml.DeclaredElements;
using JetBrains.Util;
using static JetBrains.ReSharper.Psi.DeclaredElementConstants;
namespace ImplicitNullability.Plugin
{
/// <summary>
/// Calculates the nullability value of the different PSI elements => implements the Implicit Nullability rules.
/// </summary>
[PsiComponent]
public class ImplicitNullabilityProvider
{
private static readonly ILogger Logger = JetBrains.Util.Logging.Logger.GetLogger(typeof(ImplicitNullabilityProvider));
private readonly ImplicitNullabilityConfigurationEvaluator _configurationEvaluator;
private readonly GeneratedCodeProvider _generatedCodeProvider;
private readonly CodeAnnotationAttributesChecker _codeAnnotationAttributesChecker;
public ImplicitNullabilityProvider(
ImplicitNullabilityConfigurationEvaluator configurationEvaluator,
GeneratedCodeProvider generatedCodeProvider,
CodeAnnotationAttributesChecker codeAnnotationAttributesChecker
)
{
_configurationEvaluator = configurationEvaluator;
_generatedCodeProvider = generatedCodeProvider;
_codeAnnotationAttributesChecker = codeAnnotationAttributesChecker;
}
public CodeAnnotationNullableValue? AnalyzeDeclaredElement([CanBeNull] IDeclaredElement declaredElement)
{
switch (declaredElement)
{
case IParameter parameter:
return AnalyzeParameter(parameter);
case IFunction function /* methods, constructors, and operators */:
return AnalyzeFunction(function);
case IDelegate @delegate:
return AnalyzeDelegate(@delegate);
case IField field:
return AnalyzeField(field);
case IProperty property:
return AnalyzeProperty(property);
}
return null;
}
public CodeAnnotationNullableValue? AnalyzeDeclaredElementContainerElement([CanBeNull] IDeclaredElement declaredElement)
{
switch (declaredElement)
{
case IMethod method:
return AnalyzeFunction(method, useTaskUnderlyingType: true);
case IDelegate @delegate:
return AnalyzeDelegate(@delegate, useTaskUnderlyingType: true);
}
return null;
}
private CodeAnnotationNullableValue? AnalyzeParameter(IParameter parameter)
{
CodeAnnotationNullableValue? result = null;
var containingParametersOwner = parameter.ContainingParametersOwner;
if (IsImplicitNullabilityApplicableToParameterOwner(containingParametersOwner))
{
Assertion.Assert(
containingParametersOwner != null && (containingParametersOwner is IFunction || containingParametersOwner is IProperty),
"containingParametersOwner is function or property");
var configuration = _configurationEvaluator.EvaluateFor(parameter.Module);
if (!IsExcludedGeneratedCode(configuration, (ITypeMember) containingParametersOwner))
{
if (parameter.IsInput() && configuration.HasAppliesTo(ImplicitNullabilityAppliesTo.InputParameters))
{
if (IsOptionalArgumentWithNullDefaultValue(parameter))
result = CodeAnnotationNullableValue.CAN_BE_NULL;
else
result = GetNullabilityForType(parameter.Type);
}
if (parameter.IsRef() && configuration.HasAppliesTo(ImplicitNullabilityAppliesTo.RefParameters))
result = GetNullabilityForType(parameter.Type);
if (parameter.IsOut() && configuration.HasAppliesTo(ImplicitNullabilityAppliesTo.OutParametersAndResult))
result = GetNullabilityForType(parameter.Type);
}
}
return result;
}
private CodeAnnotationNullableValue? AnalyzeFunction(IFunction function, bool useTaskUnderlyingType = false)
{
CodeAnnotationNullableValue? result = null;
if (!IsDelegateInvokeOrEndInvokeFunction(function))
{
var configuration = _configurationEvaluator.EvaluateFor(function.Module);
if (configuration.HasAppliesTo(ImplicitNullabilityAppliesTo.OutParametersAndResult))
{
if (!(ContainsContractAnnotationAttribute(function) || IsExcludedGeneratedCode(configuration, function)))
{
result = GetNullabilityForTypeOrTaskUnderlyingType(function.ReturnType, useTaskUnderlyingType);
}
}
}
return result;
}
private CodeAnnotationNullableValue? AnalyzeDelegate(IDelegate @delegate, bool useTaskUnderlyingType = false)
{
CodeAnnotationNullableValue? result = null;
var configuration = _configurationEvaluator.EvaluateFor(@delegate.Module);
if (configuration.HasAppliesTo(ImplicitNullabilityAppliesTo.OutParametersAndResult))
{
if (!IsExcludedGeneratedCode(configuration, @delegate))
{
result = GetNullabilityForTypeOrTaskUnderlyingType(@delegate.InvokeMethod.ReturnType, useTaskUnderlyingType);
}
}
return result;
}
private CodeAnnotationNullableValue? AnalyzeField(IField field)
{
CodeAnnotationNullableValue? result = null;
if (!(field is IXamlField))
{
var configuration = _configurationEvaluator.EvaluateFor(field.Module);
if (configuration.HasAppliesTo(ImplicitNullabilityAppliesTo.Fields) &&
IsFieldMatchingConfigurationOptions(field, configuration))
{
if (!IsExcludedGeneratedCode(configuration, field))
{
result = GetNullabilityForType(field.Type);
}
}
}
return result;
}
private CodeAnnotationNullableValue? AnalyzeProperty(IProperty property)
{
CodeAnnotationNullableValue? result = null;
var configuration = _configurationEvaluator.EvaluateFor(property.Module);
if (configuration.HasAppliesTo(ImplicitNullabilityAppliesTo.Properties) &&
IsPropertyMatchingConfigurationOptions(property, configuration))
{
if (!IsExcludedGeneratedCode(configuration, property))
{
result = GetNullabilityForType(property.Type);
}
}
return result;
}
private bool IsExcludedGeneratedCode(ImplicitNullabilityConfiguration configuration, ITypeMember typeMember)
{
if (configuration.GeneratedCode == GeneratedCodeOptions.Exclude)
return _generatedCodeProvider.IsGeneratedOrSynthetic(typeMember);
return false;
}
private static CodeAnnotationNullableValue? GetNullabilityForTypeOrTaskUnderlyingType(IType type, bool useTaskUnderlyingType)
{
if (useTaskUnderlyingType)
{
var taskUnderlyingType = GetTaskUnderlyingType(type);
if (taskUnderlyingType == null)
return null; // 'type' is not a 'Task<T>' type => no implicit nullability
return GetNullabilityForType(taskUnderlyingType);
}
return GetNullabilityForType(type);
}
private static CodeAnnotationNullableValue? GetNullabilityForType(IType type)
{
if (type.IsValueType())
{
// Nullable or non-nullable value type
if (type.IsNullable())
return CodeAnnotationNullableValue.CAN_BE_NULL;
}
else
{
// Reference/pointer type, generic method without value type/reference type constraint
return CodeAnnotationNullableValue.NOT_NULL;
}
return null;
}
[CanBeNull]
private static IType GetTaskUnderlyingType(IType type)
{
// Use "latest" language level because this just includes _more_ types (C# 7 "task-like" types) and the nullability
// value we return here also effects _callers_ (whose C# language level we do not know).
return type.GetTasklikeUnderlyingType(CSharpLanguageLevel.Latest);
}
private static bool IsImplicitNullabilityApplicableToParameterOwner([CanBeNull] IParametersOwner parametersOwner)
{
// IFunction includes methods, constructors, operator overloads, delegate (methods), but also implicitly
// defined ("synthetic") methods, which we want to exclude because the developer cannot
// override the implicit annotation.
// IProperty includes indexer parameters.
switch (parametersOwner)
{
case IFunction function:
return !IsDelegateBeginInvokeFunction(function) &&
IsParametersOwnerNotSynthetic(parametersOwner);
case IProperty _:
return true;
}
return false;
}
private static bool IsDelegateBeginInvokeFunction(IFunction function)
{
// Delegate BeginInvoke() methods must be excluded for *parameters*, because ReSharper doesn't pass the parameter attributes to
// the DelegateBeginInvokeMethod => implicit nullability could not be overridden with explicit annotations.
// We can't use R#'s DelegateMethod subtypes to implement this predicate because they don't work for compiled code.
if (function.ShortName != DELEGATE_BEGIN_INVOKE_METHOD_NAME)
return false;
return function.GetContainingType() is IDelegate;
}
private static bool IsDelegateInvokeOrEndInvokeFunction(IFunction function)
{
// Delegate Invoke() and EndInvoke() methods must be excluded for *result values*, because of
// an R# issue, see DelegatesSampleTests.SomeFunctionDelegate.
// We can't use R#'s DelegateMethod subtypes to implement this predicate because they don't work for compiled code.
if (!(function.ShortName == DELEGATE_INVOKE_METHOD_NAME || function.ShortName == DELEGATE_END_INVOKE_METHOD_NAME))
return false;
return function.GetContainingType() is IDelegate;
}
private static bool IsParametersOwnerNotSynthetic(IParametersOwner containingParametersOwner)
{
// Exclude ReSharper's fake (called "synthetic") parameter owners (methods), like ASP.NET WebForms' Render-method, or
// Razor's Write-methods, because these look like regular project methods but should be excluded from Implicit
// Nullability because the developer cannot override the result with explicit annotations.
return !containingParametersOwner.IsSynthetic();
}
private static bool IsOptionalArgumentWithNullDefaultValue(IParameter parameter)
{
#if DEBUG
if (parameter.IsOptional)
{
var defaultValue = parameter.GetDefaultValue();
var optionalParameterText = "OptionalParameter IsConstant: " + defaultValue.IsConstant +
", ConstantValue.Value: " + (defaultValue.ConstantValue.Value ?? "NULL") +
", IsDefaultType: " + defaultValue.IsDefaultType +
", DefaultTypeValue.IsValueType(): " + defaultValue.DefaultTypeValue.IsValueType();
Logger.Verbose(optionalParameterText);
}
#endif
return parameter.IsOptional && IsNullDefaultValue(parameter.GetDefaultValue());
}
private static bool IsNullDefaultValue(DefaultValue defaultValue)
{
// Note that for "param = null" and "param = default(string)", the ConstantValue cannot be trusted; we therefore must check IsDefaultType:
var isNullDefaultExpression = defaultValue.IsDefaultType && !defaultValue.DefaultTypeValue.IsValueType();
// For "param = StringConstantMember" this check is necessary:
var isNullConstantExpression = defaultValue.IsConstant && defaultValue.ConstantValue.Value == null;
return isNullDefaultExpression || isNullConstantExpression;
}
private bool ContainsContractAnnotationAttribute(IFunction function)
{
var attributeInstances = function.GetAttributeInstances(inherit: true);
// Can't use the CodeAnnotationsCache here because we would get an endless recursion:
return _codeAnnotationAttributesChecker.ContainsContractAnnotationAttribute(attributeInstances);
}
private static bool IsFieldMatchingConfigurationOptions(IField field, ImplicitNullabilityConfiguration configuration)
{
return
(!configuration.HasFieldOption(ImplicitNullabilityFieldOptions.RestrictToReadonly) || field.IsReadonly) &&
(!configuration.HasFieldOption(ImplicitNullabilityFieldOptions.RestrictToReferenceTypes) || field.IsMemberOfReferenceType());
}
private static bool IsPropertyMatchingConfigurationOptions(IProperty property, ImplicitNullabilityConfiguration configuration)
{
return
// Note that `IsWritable` also searches for "polymorphic setters" (see `PartiallyOveriddenProperties` test data)
(!configuration.HasPropertyOption(ImplicitNullabilityPropertyOptions.RestrictToGetterOnly) || !property.IsWritable) &&
(!configuration.HasPropertyOption(ImplicitNullabilityPropertyOptions.RestrictToReferenceTypes) || property.IsMemberOfReferenceType());
}
}
}
| |
using System.Linq;
using System.Threading.Tasks;
using Marten.Services;
using Marten.Storage;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Newtonsoft.Json;
using Weasel.Core;
using Weasel.Postgresql;
namespace Marten.Testing.Examples
{
// Leave this commented out please, and always use the User
// in Marten.Testing.Documents
/*
#region sample_user_document
public class User
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Internal { get; set; }
public string UserName { get; set; }
public string Department { get; set; }
}
#endregion
*/
public class ConfiguringDocumentStore
{
public async Task start_a_basic_store()
{
#region sample_start_a_store
var store = DocumentStore
.For("host=localhost;database=marten_testing;password=mypassword;username=someuser");
#endregion
#region sample_start_a_query_session
using (var session = store.QuerySession())
{
var internalUsers = session
.Query<User>().Where(x => x.Internal).ToArray();
}
#endregion
#region sample_opening_sessions
// Open a session for querying, loading, and
// updating documents
using (var session = store.LightweightSession())
{
var user = new User { FirstName = "Han", LastName = "Solo" };
session.Store(user);
await session.SaveChangesAsync();
}
// Open a session for querying, loading, and
// updating documents with a backing "Identity Map"
using (var session = store.QuerySession())
{
var existing = await session
.Query<User>()
.SingleAsync(x => x.FirstName == "Han" && x.LastName == "Solo");
}
#endregion
}
public void start_a_complex_store()
{
#region sample_start_a_complex_store
var store = DocumentStore.For(_ =>
{
// Turn this off in production
_.AutoCreateSchemaObjects = AutoCreate.None;
// This is still mandatory
_.Connection("some connection string");
// Override the JSON Serialization
_.Serializer<TestsSerializer>();
});
#endregion
}
public void customize_json_net_serialization()
{
#region sample_customize_json_net_serialization
var serializer = new Marten.Services.JsonNetSerializer();
// To change the enum storage policy to store Enum's as strings:
serializer.EnumStorage = EnumStorage.AsString;
// All other customizations:
serializer.Customize(_ =>
{
// Code directly against a Newtonsoft.Json JsonSerializer
_.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
_.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
});
var store = DocumentStore.For(_ =>
{
_.Connection("some connection string");
// Replace the default JsonNetSerializer with the one we configured
// above
_.Serializer(serializer);
});
#endregion
}
public void customize_json_net_enum_storage_serialization()
{
#region sample_customize_json_net_enum_storage_serialization
var store = DocumentStore.For(_ =>
{
_.Connection("some connection string");
// Replace the default JsonNetSerializer default enum storage
// with storing them as string
_.UseDefaultSerialization(enumStorage: EnumStorage.AsString);
});
#endregion
}
public void customize_json_net_camelcase_casing_serialization()
{
#region sample_customize_json_net_camelcase_casing_serialization
var store = DocumentStore.For(_ =>
{
_.Connection("some connection string");
// Replace the default (as is) JsonNetSerializer field names casing
// with camelCase formatting
_.UseDefaultSerialization(casing: Casing.CamelCase);
});
#endregion
}
public void customize_json_net_snakecase_casing_serialization()
{
#region sample_customize_json_net_snakecase_casing_serialization
var store = DocumentStore.For(_ =>
{
_.Connection("some connection string");
// Replace the default (as is) JsonNetSerializer field names casing
// with snake_case formatting
_.UseDefaultSerialization(casing: Casing.SnakeCase);
});
#endregion
}
public void customize_json_net_snakecase_collectionstorage()
{
#region sample_customize_json_net_snakecase_collectionstorage
var store = DocumentStore.For(_ =>
{
_.Connection("some connection string");
// Replace the default (strongly typed) JsonNetSerializer collection storage
// with JSON array formatting
_.UseDefaultSerialization(collectionStorage: CollectionStorage.AsArray);
});
#endregion
}
public void customize_json_net_nonpublicsetters()
{
#region sample_customize_json_net_nonpublicsetters
var store = DocumentStore.For(_ =>
{
_.Connection("some connection string");
// Replace the default (only public setters) JsonNetSerializer deserialization settings
// with allowing to also deserialize using non-public setters
_.UseDefaultSerialization(nonPublicMembersStorage: NonPublicMembersStorage.NonPublicSetters);
});
#endregion
}
public void setting_event_schema()
{
#region sample_setting_event_schema
var store = DocumentStore.For(_ =>
{
_.Connection("some connection string");
// Places all the Event Store schema objects
// into the "events" schema
_.Events.DatabaseSchemaName = "events";
});
#endregion
}
#region sample_custom-store-options
public class MyStoreOptions: StoreOptions
{
public static IDocumentStore ToStore()
{
return new DocumentStore(new MyStoreOptions());
}
public MyStoreOptions()
{
Connection(ConnectionSource.ConnectionString);
Serializer(new JsonNetSerializer { EnumStorage = EnumStorage.AsString });
Schema.For<User>().Index(x => x.UserName);
}
}
#endregion
public void set_multi_tenancy_on_events()
{
#region sample_making_the_events_multi_tenanted
var store = DocumentStore.For(opts =>
{
opts.Connection("some connection string");
// And that's all it takes, the events are now multi-tenanted
opts.Events.TenancyStyle = TenancyStyle.Conjoined;
});
#endregion
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 AddSingle()
{
var test = new SimpleBinaryOpTest__AddSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddSingle
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int Op2ElementCount = VectorSize / sizeof(Single);
private const int RetElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static SimpleBinaryOpTest__AddSingle()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AddSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.Add(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse.Add(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.Add(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse).GetMethod(nameof(Sse.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddSingle();
var result = Sse.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, 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>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
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)
{
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.Add)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Net.WebSockets;
using System.Reflection;
using System.Text;
namespace System.Net
{
public sealed unsafe partial class HttpListenerRequest
{
private string[] _acceptTypes;
private string[] _userLanguages;
private CookieCollection _cookies;
private string _rawUrl;
private Uri _requestUri;
private Version _version;
public string[] AcceptTypes
{
get
{
if (_acceptTypes == null)
{
_acceptTypes = Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.Accept]);
}
return _acceptTypes;
}
}
public string[] UserLanguages
{
get
{
if (_userLanguages == null)
{
_userLanguages = Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.AcceptLanguage]);
}
return _userLanguages;
}
}
private static Func<CookieCollection, Cookie, bool, int> s_internalAddMethod = null;
private static Func<CookieCollection, Cookie, bool, int> InternalAddMethod
{
get
{
if (s_internalAddMethod == null)
{
// We need to use CookieCollection.InternalAdd, as this method performs no validation on the Cookies.
// Unfortunately this API is internal so we use reflection to access it. The method is cached for performance reasons.
MethodInfo method = typeof(CookieCollection).GetMethod("InternalAdd", BindingFlags.NonPublic | BindingFlags.Instance);
Debug.Assert(method != null, "We need to use an internal method named InternalAdd that is declared on Cookie.");
s_internalAddMethod = (Func<CookieCollection, Cookie, bool, int>)Delegate.CreateDelegate(typeof(Func<CookieCollection, Cookie, bool, int>), method);
}
return s_internalAddMethod;
}
}
private CookieCollection ParseCookies(Uri uri, string setCookieHeader)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "uri:" + uri + " setCookieHeader:" + setCookieHeader);
CookieCollection cookies = new CookieCollection();
CookieParser parser = new CookieParser(setCookieHeader);
while (true)
{
Cookie cookie = parser.GetServer();
if (cookie == null)
{
// EOF, done.
break;
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "CookieParser returned cookie: " + cookie.ToString());
if (cookie.Name.Length == 0)
{
continue;
}
InternalAddMethod(cookies, cookie, true);
}
return cookies;
}
public CookieCollection Cookies
{
get
{
if (_cookies == null)
{
string cookieString = Headers[HttpKnownHeaderNames.Cookie];
if (!string.IsNullOrEmpty(cookieString))
{
_cookies = ParseCookies(RequestUri, cookieString);
}
if (_cookies == null)
{
_cookies = new CookieCollection();
}
}
return _cookies;
}
}
public Encoding ContentEncoding
{
get
{
if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP"))
{
string postDataCharset = Headers["x-up-devcap-post-charset"];
if (postDataCharset != null && postDataCharset.Length > 0)
{
try
{
return Encoding.GetEncoding(postDataCharset);
}
catch (ArgumentException)
{
}
}
}
if (HasEntityBody)
{
if (ContentType != null)
{
string charSet = Helpers.GetAttributeFromHeader(ContentType, "charset");
if (charSet != null)
{
try
{
return Encoding.GetEncoding(charSet);
}
catch (ArgumentException)
{
}
}
}
}
return Encoding.Default;
}
}
public string ContentType => Headers[HttpKnownHeaderNames.ContentType];
public bool IsLocal => LocalEndPoint.Address.Equals(RemoteEndPoint.Address);
public bool IsWebSocketRequest
{
get
{
if (!SupportsWebSockets)
{
return false;
}
bool foundConnectionUpgradeHeader = false;
if (string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Upgrade]))
{
return false;
}
foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection))
{
if (string.Equals(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase))
{
foundConnectionUpgradeHeader = true;
break;
}
}
if (!foundConnectionUpgradeHeader)
{
return false;
}
foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade))
{
if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
public NameValueCollection QueryString
{
get
{
NameValueCollection queryString = new NameValueCollection();
Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding);
return queryString;
}
}
public string RawUrl => _rawUrl;
private string RequestScheme => IsSecureConnection ? UriScheme.Https : UriScheme.Http;
public string UserAgent => Headers[HttpKnownHeaderNames.UserAgent];
public string UserHostAddress => LocalEndPoint.ToString();
public string UserHostName => Headers[HttpKnownHeaderNames.Host];
public Uri UrlReferrer
{
get
{
string referrer = Headers[HttpKnownHeaderNames.Referer];
if (referrer == null)
{
return null;
}
bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out Uri urlReferrer);
return success ? urlReferrer : null;
}
}
public Uri Url => RequestUri;
public Version ProtocolVersion => _version;
private static class Helpers
{
//
// Get attribute off header value
//
internal static string GetAttributeFromHeader(string headerValue, string attrName)
{
if (headerValue == null)
return null;
int l = headerValue.Length;
int k = attrName.Length;
// find properly separated attribute name
int i = 1; // start searching from 1
while (i < l)
{
i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, attrName, i, CompareOptions.IgnoreCase);
if (i < 0)
break;
if (i + k >= l)
break;
char chPrev = headerValue[i - 1];
char chNext = headerValue[i + k];
if ((chPrev == ';' || chPrev == ',' || char.IsWhiteSpace(chPrev)) && (chNext == '=' || char.IsWhiteSpace(chNext)))
break;
i += k;
}
if (i < 0 || i >= l)
return null;
// skip to '=' and the following whitespace
i += k;
while (i < l && char.IsWhiteSpace(headerValue[i]))
i++;
if (i >= l || headerValue[i] != '=')
return null;
i++;
while (i < l && char.IsWhiteSpace(headerValue[i]))
i++;
if (i >= l)
return null;
// parse the value
string attrValue = null;
int j;
if (i < l && headerValue[i] == '"')
{
if (i == l - 1)
return null;
j = headerValue.IndexOf('"', i + 1);
if (j < 0 || j == i + 1)
return null;
attrValue = headerValue.Substring(i + 1, j - i - 1).Trim();
}
else
{
for (j = i; j < l; j++)
{
if (headerValue[j] == ' ' || headerValue[j] == ',')
break;
}
if (j == i)
return null;
attrValue = headerValue.Substring(i, j - i).Trim();
}
return attrValue;
}
internal static string[] ParseMultivalueHeader(string s)
{
if (s == null)
return null;
int l = s.Length;
// collect comma-separated values into list
List<string> values = new List<string>();
int i = 0;
while (i < l)
{
// find next ,
int ci = s.IndexOf(',', i);
if (ci < 0)
ci = l;
// append corresponding server value
values.Add(s.Substring(i, ci - i));
// move to next
i = ci + 1;
// skip leading space
if (i < l && s[i] == ' ')
i++;
}
// return list as array of strings
int n = values.Count;
string[] strings;
// if n is 0 that means s was empty string
if (n == 0)
{
strings = new string[1];
strings[0] = string.Empty;
}
else
{
strings = new string[n];
values.CopyTo(0, strings, 0, n);
}
return strings;
}
private static string UrlDecodeStringFromStringInternal(string s, Encoding e)
{
int count = s.Length;
UrlDecoder helper = new UrlDecoder(count, e);
// go through the string's chars collapsing %XX and %uXXXX and
// appending each char as char, with exception of %XX constructs
// that are appended as bytes
for (int pos = 0; pos < count; pos++)
{
char ch = s[pos];
if (ch == '+')
{
ch = ' ';
}
else if (ch == '%' && pos < count - 2)
{
if (s[pos + 1] == 'u' && pos < count - 5)
{
int h1 = HexToInt(s[pos + 2]);
int h2 = HexToInt(s[pos + 3]);
int h3 = HexToInt(s[pos + 4]);
int h4 = HexToInt(s[pos + 5]);
if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
{ // valid 4 hex chars
ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
pos += 5;
// only add as char
helper.AddChar(ch);
continue;
}
}
else
{
int h1 = HexToInt(s[pos + 1]);
int h2 = HexToInt(s[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{ // valid 2 hex chars
byte b = (byte)((h1 << 4) | h2);
pos += 2;
// don't add as char
helper.AddByte(b);
continue;
}
}
}
if ((ch & 0xFF80) == 0)
helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
else
helper.AddChar(ch);
}
return helper.GetString();
}
private static int HexToInt(char h)
{
return (h >= '0' && h <= '9') ? h - '0' :
(h >= 'a' && h <= 'f') ? h - 'a' + 10 :
(h >= 'A' && h <= 'F') ? h - 'A' + 10 :
-1;
}
private class UrlDecoder
{
private int _bufferSize;
// Accumulate characters in a special array
private int _numChars;
private char[] _charBuffer;
// Accumulate bytes for decoding into characters in a special array
private int _numBytes;
private byte[] _byteBuffer;
// Encoding to convert chars to bytes
private Encoding _encoding;
private void FlushBytes()
{
if (_numBytes > 0)
{
_numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
_numBytes = 0;
}
}
internal UrlDecoder(int bufferSize, Encoding encoding)
{
_bufferSize = bufferSize;
_encoding = encoding;
_charBuffer = new char[bufferSize];
// byte buffer created on demand
}
internal void AddChar(char ch)
{
if (_numBytes > 0)
FlushBytes();
_charBuffer[_numChars++] = ch;
}
internal void AddByte(byte b)
{
{
if (_byteBuffer == null)
_byteBuffer = new byte[_bufferSize];
_byteBuffer[_numBytes++] = b;
}
}
internal string GetString()
{
if (_numBytes > 0)
FlushBytes();
if (_numChars > 0)
return new string(_charBuffer, 0, _numChars);
else
return string.Empty;
}
}
internal static void FillFromString(NameValueCollection nvc, string s, bool urlencoded, Encoding encoding)
{
int l = (s != null) ? s.Length : 0;
int i = (s.Length > 0 && s[0] == '?') ? 1 : 0;
while (i < l)
{
// find next & while noting first = on the way (and if there are more)
int si = i;
int ti = -1;
while (i < l)
{
char ch = s[i];
if (ch == '=')
{
if (ti < 0)
ti = i;
}
else if (ch == '&')
{
break;
}
i++;
}
// extract the name / value pair
string name = null;
string value = null;
if (ti >= 0)
{
name = s.Substring(si, ti - si);
value = s.Substring(ti + 1, i - ti - 1);
}
else
{
value = s.Substring(si, i - si);
}
// add name / value pair to the collection
if (urlencoded)
nvc.Add(
name == null ? null : UrlDecodeStringFromStringInternal(name, encoding),
UrlDecodeStringFromStringInternal(value, encoding));
else
nvc.Add(name, value);
// trailing '&'
if (i == l - 1 && s[i] == '&')
nvc.Add(null, "");
i++;
}
}
}
}
}
| |
namespace Epi.Windows.MakeView.Dialogs
{
partial class OptionFieldItemsDialogs
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OptionFieldItemsDialogs));
this.rdbRight = new System.Windows.Forms.RadioButton();
this.rdbLeft = new System.Windows.Forms.RadioButton();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.dgOptions = new System.Windows.Forms.DataGrid();
this.dataGridTableStyle1 = new System.Windows.Forms.DataGridTableStyle();
this.dataGridTextBoxColumn1 = new System.Windows.Forms.DataGridTextBoxColumn();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgOptions)).BeginInit();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
//
// rdbRight
//
this.rdbRight.Checked = true;
resources.ApplyResources(this.rdbRight, "rdbRight");
this.rdbRight.Name = "rdbRight";
this.rdbRight.TabStop = true;
//
// rdbLeft
//
resources.ApplyResources(this.rdbLeft, "rdbLeft");
this.rdbLeft.Name = "rdbLeft";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.rdbRight);
this.groupBox1.Controls.Add(this.rdbLeft);
this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
//
// dgOptions
//
resources.ApplyResources(this.dgOptions, "dgOptions");
this.dgOptions.DataMember = "";
this.dgOptions.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgOptions.Name = "dgOptions";
this.dgOptions.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.dataGridTableStyle1});
//
// dataGridTableStyle1
//
resources.ApplyResources(this.dataGridTableStyle1, "dataGridTableStyle1");
this.dataGridTableStyle1.DataGrid = this.dgOptions;
this.dataGridTableStyle1.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {
this.dataGridTextBoxColumn1});
//
// dataGridTextBoxColumn1
//
resources.ApplyResources(this.dataGridTextBoxColumn1, "dataGridTextBoxColumn1");
this.dataGridTextBoxColumn1.FormatInfo = null;
//
// Options
//
this.AcceptButton = this.btnOK;
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.dgOptions);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.HelpButton = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Options";
this.ShowInTaskbar = false;
this.Load += new System.EventHandler(this.Options_Load);
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dgOptions)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RadioButton rdbRight;
private System.Windows.Forms.RadioButton rdbLeft;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.DataGrid dgOptions;
private System.Windows.Forms.DataGridTableStyle dataGridTableStyle1;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn1;
}
}
| |
using System;
namespace Tibia.Util
{
/// <summary>
/// Helper methods for reading memory.
/// </summary>
public static class Memory
{
/// <summary>
/// Read a specified number of bytes from a process.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="bytesToRead"></param>
/// <returns></returns>
public static byte[] ReadBytes(IntPtr handle, long address, uint bytesToRead)
{
IntPtr ptrBytesRead;
byte[] buffer = new byte[bytesToRead];
Util.WinApi.ReadProcessMemory(handle, new IntPtr(address), buffer, bytesToRead, out ptrBytesRead);
return buffer;
}
/// <summary>
/// Read a byte from memory.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <returns></returns>
public static byte ReadByte(IntPtr handle, long address)
{
return ReadBytes(handle, address, 1)[0];
}
/// <summary>
/// Read a short from memory (16-bits).
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <returns></returns>
public static short ReadInt16(IntPtr handle, long address)
{
return BitConverter.ToInt16(ReadBytes(handle, address, 2), 0);
}
/// <summary>
/// Read a ushort from memory (16-bits).
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <returns></returns>
public static ushort ReadUInt16(IntPtr handle, long address)
{
return BitConverter.ToUInt16(ReadBytes(handle, address, 2), 0);
}
[Obsolete("Please use ReadInt16")]
public static short ReadShort(IntPtr handle, long address)
{
return BitConverter.ToInt16(ReadBytes(handle, address, 2), 0);
}
/// <summary>
/// Read an integer from the process (32-bits)
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <returns></returns>
public static int ReadInt32(IntPtr handle, long address)
{
return BitConverter.ToInt32(ReadBytes(handle, address, 4), 0);
}
/// <summary>
/// Read an uinteger from the process (32-bits)
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <returns></returns>
public static uint ReadUInt32(IntPtr handle, long address)
{
return BitConverter.ToUInt32(ReadBytes(handle, address, 4), 0);
}
/// <summary>
/// Read an unsigned long from the process (64-bits)
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <returns></returns>
public static ulong ReadUInt64(IntPtr handle, long address)
{
return BitConverter.ToUInt64(ReadBytes(handle, address, 8), 0);
}
[Obsolete("Please use ReadInt32.")]
public static int ReadInt(IntPtr handle, long address)
{
return BitConverter.ToInt32(ReadBytes(handle, address, 4), 0);
}
/// <summary>
/// Read a 32-bit double from the process
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <returns></returns>
public static double ReadDouble(IntPtr handle, long address)
{
return BitConverter.ToDouble(ReadBytes(handle, address, 8), 0);
}
/// <summary>
/// Read a string from memmory. Splits at 00 and returns first section to avoid junk. Uses default length of 255. Use ReadString(IntPtr handle, long address, int length) to read longer strings, such as the RSA key.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <returns></returns>
public static string ReadString(IntPtr handle, long address)
{
return ReadString(handle, address, 0);
}
/// <summary>
/// Read a string from memmory. Splits at 00 and returns first section to avoid junk.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="length">the length of the bytes to read</param>
/// <returns></returns>
public static string ReadString(IntPtr handle, long address, uint length)
{
if (length > 0)
{
byte[] buffer;
buffer = ReadBytes(handle, address, length);
return System.Text.ASCIIEncoding.Default.GetString(buffer).Split(new Char())[0];
}
else
{
string s = "";
byte temp = ReadByte(handle, address++);
while (temp != 0)
{
s += (char)temp;
temp = ReadByte(handle, address++);
}
return s;
}
}
/// <summary>
/// Write a specified number of bytes to a process.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="bytes"></param>
/// <param name="length"></param>
/// <returns></returns>
public static bool WriteBytes(IntPtr handle, long address, byte[] bytes, uint length)
{
IntPtr bytesWritten;
// Write to memory
int result = Util.WinApi.WriteProcessMemory(handle, new IntPtr(address), bytes, length, out bytesWritten);
return result != 0;
}
/// <summary>
/// Write an integer (32-bits) to memory.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool WriteInt32(IntPtr handle, long address, int value)
{
return WriteBytes(handle, address, BitConverter.GetBytes(value), 4);
}
/// <summary>
/// Write an uinteger (32-bits) to memory.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool WriteUInt32(IntPtr handle, long address, uint value)
{
return WriteBytes(handle, address, BitConverter.GetBytes(value), 4);
}
/// <summary>
/// Write an unsigned long (64-bits) to memory.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool WriteUInt64(IntPtr handle, long address, ulong value)
{
return WriteBytes(handle, address, BitConverter.GetBytes(value), 8);
}
/// <summary>
/// Write an integer (16-bits) to memory.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool WriteInt16(IntPtr handle, long address, short value)
{
return WriteBytes(handle, address, BitConverter.GetBytes(value), 2);
}
/// <summary>
/// Write an uinteger (16-bits) to memory.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool WriteUInt16(IntPtr handle, long address, ushort value)
{
return WriteBytes(handle, address, BitConverter.GetBytes(value), 2);
}
[Obsolete("Please use WriteInt32.")]
public static bool WriteInt(IntPtr handle, long address, int value)
{
byte[] bytes = BitConverter.GetBytes(value);
return WriteBytes(handle, address, bytes, 4);
}
/// <summary>
/// Write a double value to memory.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool WriteDouble(IntPtr handle, long address, double value)
{
byte[] bytes = BitConverter.GetBytes(value);
return WriteBytes(handle, address, bytes, 8);
}
/// <summary>
/// Write a byte to memory.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool WriteByte(IntPtr handle, long address, byte value)
{
return WriteBytes(handle, address, new byte[] { value }, 1);
}
/// <summary>
/// Write a string to memory without using econding.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="str"></param>
/// <returns></returns>
public static bool WriteStringNoEncoding(IntPtr handle, long address, string str)
{
str += '\0';
byte[] bytes = str.ToByteArray();
return WriteBytes(handle, address, bytes, (uint)bytes.Length);
}
/// <summary>
/// Write a string to memory.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="str"></param>
/// <returns></returns>
public static bool WriteString(IntPtr handle, long address, string str)
{
str += '\0';
byte[] bytes = System.Text.ASCIIEncoding.Default.GetBytes(str);
return WriteBytes(handle, address, bytes, (uint)bytes.Length);
}
/// <summary>
/// Set the RSA key. Different from WriteString because must overcome protection.
/// </summary>
/// <param name="handle"></param>
/// <param name="address"></param>
/// <param name="newKey"></param>
/// <returns></returns>
public static bool WriteRSA(IntPtr handle, long address, string newKey)
{
IntPtr bytesWritten;
int result;
WinApi.MemoryProtection oldProtection = 0;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] bytes = enc.GetBytes(newKey);
// Make it so we can write to the memory block
WinApi.VirtualProtectEx(
handle,
new IntPtr(address),
new IntPtr(bytes.Length),
WinApi.MemoryProtection.ExecuteReadWrite, ref oldProtection);
// Write to memory
result = WinApi.WriteProcessMemory(handle, new IntPtr(address), bytes, (uint)bytes.Length, out bytesWritten);
// Put the protection back on the memory block
WinApi.VirtualProtectEx(handle, new IntPtr(address), new IntPtr(bytes.Length), oldProtection, ref oldProtection);
return (result != 0);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Lucene.Net.Support
{
/*
* 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>
/// Represents a strongly typed list of objects that can be accessed by index.
/// Provides methods to manipulate lists. Also provides functionality
/// to compare lists against each other through an implementations of
/// <see cref="IEquatable{T}"/>, or to wrap an existing list to use
/// the same comparison logic as this one while not affecting any of its
/// other functionality.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
public class EquatableList<T> : IList<T>, IEquatable<IList<T>>
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
private readonly IList<T> list;
/// <summary>Initializes a new instance of the
/// <see cref="EquatableList{T}"/> class that is empty and has the
/// default initial capacity.</summary>
public EquatableList()
{
list = new List<T>();
}
/// <summary>
/// Initializes a new instance of <see cref="EquatableList{T}"/>.
/// <para/>
/// If the <paramref name="wrap"/> parameter is <c>true</c>, the
/// <paramref name="collection"/> is used as is without doing
/// a copy operation. Otherwise, the collection is copied
/// (which is the same operation as the
/// <see cref="EquatableList{T}.EquatableList(IEnumerable{T})"/> overload).
/// <para/>
/// The internal <paramref name="collection"/> is used for
/// all operations except for <see cref="Equals(object)"/>, <see cref="GetHashCode()"/>,
/// and <see cref="ToString()"/>, which are all based on deep analysis
/// of this collection and any nested collections.
/// </summary>
/// <param name="collection">The collection that will either be wrapped or copied
/// depending on the value of <paramref name="wrap"/>.</param>
/// <param name="wrap"><c>true</c> to wrap an existing <see cref="IList{T}"/> without copying,
/// or <c>false</c> to copy the collection into a new <see cref="List{T}"/>.</param>
public EquatableList(IList<T> collection, bool wrap)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (wrap)
{
this.list = collection;
}
else
{
this.list = new List<T>(collection);
}
}
/// <summary>
/// Initializes a new
/// instance of the <see cref="EquatableList{T}"/>
/// class that contains elements copied from the specified collection and has
/// sufficient capacity to accommodate the number of elements copied.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
public EquatableList(IEnumerable<T> collection)
{
list = new List<T>(collection);
}
/// <summary>Initializes a new instance of the <see cref="EquatableList{T}"/>
/// class that is empty and has the specified initial capacity.</summary>
/// <param name="capacity">The number of elements that the new list can initially store.</param>
public EquatableList(int capacity)
{
list = new List<T>(capacity);
}
#region IList<T> members
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
public virtual T this[int index]
{
get { return list[index]; }
set { list[index] = value; }
}
/// <summary>
/// Gets the number of elements contained in the <see cref="EquatableList{T}"/>.
/// </summary>
public virtual int Count
{
get { return list.Count; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="EquatableList{T}"/> is read-only.
/// </summary>
public virtual bool IsReadOnly
{
get { return list.IsReadOnly; }
}
/// <summary>
/// Adds an object to the end of the <see cref="EquatableList{T}"/>.
/// </summary>
/// <param name="item">The object to be added to the end of the <see cref="EquatableList{T}"/>. The value can be <c>null</c> for reference types.</param>
public virtual void Add(T item)
{
list.Add(item);
}
/// <summary>
/// Removes all items from the <see cref="EquatableList{T}"/>.
/// </summary>
public virtual void Clear()
{
list.Clear();
}
/// <summary>
/// Determines whether the <see cref="EquatableList{T}"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="EquatableList{T}"/>.</param>
/// <returns><c>true</c> if the Object is found in the <see cref="EquatableList{T}"/>; otherwise, <c>false</c>.</returns>
public virtual bool Contains(T item)
{
return list.Contains(item);
}
/// <summary>
/// Copies the entire <see cref="EquatableList{T}"/> to a compatible one-dimensional array,
/// starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the
/// destination of the elements copied from <see cref="EquatableList{T}"/>.
/// The Array must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public virtual void CopyTo(T[] array, int arrayIndex)
{
list.CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="EquatableList{T}"/>.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}"/> for the <see cref="EquatableList{T}"/>.</returns>
public virtual IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
/// <summary>
/// Determines the index of a specific <paramref name="item"/> in the <see cref="EquatableList{T}"/>.
/// </summary>
/// <param name="item">The object to locate in the <see cref="EquatableList{T}"/>.</param>
/// <returns>The index of <paramref name="item"/> if found in the list; otherwise, -1.</returns>
public virtual int IndexOf(T item)
{
return list.IndexOf(item);
}
/// <summary>
/// Inserts an item to the <see cref="EquatableList{T}"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="EquatableList{T}"/>.</param>
public virtual void Insert(int index, T item)
{
list.Insert(index, item);
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="EquatableList{T}"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="EquatableList{T}"/>.</param>
/// <returns><c>true</c> if <paramref name="item"/> was successfully removed from the
/// <see cref="EquatableList{T}"/>; otherwise, <c>false</c>. This method also returns
/// <c>false</c> if item is not found in the original <see cref="EquatableList{T}"/>.</returns>
public virtual bool Remove(T item)
{
return list.Remove(item);
}
/// <summary>
/// Removes the <see cref="EquatableList{T}"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public virtual void RemoveAt(int index)
{
list.RemoveAt(index);
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="EquatableList{T}"/>.
/// </summary>
/// <returns>An <see cref="IEnumerator"/> for the <see cref="EquatableList{T}"/>.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return list.GetEnumerator();
}
#endregion
#region Operator overrides
// TODO: When diverging from Java version of Lucene, can uncomment these to adhere to best practices when overriding the Equals method and implementing IEquatable<T>.
///// <summary>Overload of the == operator, it compares a
///// <see cref="EquatableList{T}"/> to an <see cref="IEnumerable{T}"/>
///// implementation.</summary>
///// <param name="x">The <see cref="EquatableList{T}"/> to compare
///// against <paramref name="y"/>.</param>
///// <param name="y">The <see cref="IEnumerable{T}"/> to compare
///// against <paramref name="x"/>.</param>
///// <returns>True if the instances are equal, false otherwise.</returns>
//public static bool operator ==(EquatableList<T> x, System.Collections.Generic.IEnumerable<T> y)
//{
// // Call Equals.
// return Equals(x, y);
//}
///// <summary>Overload of the == operator, it compares a
///// <see cref="EquatableList{T}"/> to an <see cref="IEnumerable{T}"/>
///// implementation.</summary>
///// <param name="y">The <see cref="EquatableList{T}"/> to compare
///// against <paramref name="x"/>.</param>
///// <param name="x">The <see cref="IEnumerable{T}"/> to compare
///// against <paramref name="y"/>.</param>
///// <returns>True if the instances are equal, false otherwise.</returns>
//public static bool operator ==(System.Collections.Generic.IEnumerable<T> x, EquatableList<T> y)
//{
// // Call equals.
// return Equals(x, y);
//}
///// <summary>Overload of the != operator, it compares a
///// <see cref="EquatableList{T}"/> to an <see cref="IEnumerable{T}"/>
///// implementation.</summary>
///// <param name="x">The <see cref="EquatableList{T}"/> to compare
///// against <paramref name="y"/>.</param>
///// <param name="y">The <see cref="IEnumerable{T}"/> to compare
///// against <paramref name="x"/>.</param>
///// <returns>True if the instances are not equal, false otherwise.</returns>
//public static bool operator !=(EquatableList<T> x, System.Collections.Generic.IEnumerable<T> y)
//{
// // Return the negative of the equals operation.
// return !(x == y);
//}
///// <summary>Overload of the != operator, it compares a
///// <see cref="EquatableList{T}"/> to an <see cref="IEnumerable{T}"/>
///// implementation.</summary>
///// <param name="y">The <see cref="EquatableList{T}"/> to compare
///// against <paramref name="x"/>.</param>
///// <param name="x">The <see cref="IEnumerable{T}"/> to compare
///// against <paramref name="y"/>.</param>
///// <returns>True if the instances are not equal, false otherwise.</returns>
//public static bool operator !=(System.Collections.Generic.IEnumerable<T> x, EquatableList<T> y)
//{
// // Return the negative of the equals operation.
// return !(x == y);
//}
#endregion
#region IEquatable<T> members
/// <summary>
/// Compares this sequence to another <see cref="IList{T}"/>
/// implementation, returning <c>true</c> if they are equal, <c>false</c> otherwise.
/// <para/>
/// The comparison takes into consideration any values in this collection and values
/// of any nested collections, but does not take into consideration the data type.
/// Therefore, <see cref="EquatableList{T}"/> can equal any <see cref="IList{T}"/>
/// with the exact same values in the same order.
/// </summary>
/// <param name="other">The other <see cref="IList{T}"/> implementation
/// to compare against.</param>
/// <returns><c>true</c> if the sequence in <paramref name="other"/>
/// is the same as this one.</returns>
public virtual bool Equals(IList<T> other)
{
return Collections.Equals(this, other);
}
#endregion
#region IClonable members
/// <summary>Clones the <see cref="EquatableList{T}"/>.</summary>
/// <remarks>This is a shallow clone.</remarks>
/// <returns>A new shallow clone of this
/// <see cref="EquatableList{T}"/>.</returns>
public virtual object Clone()
{
// Just create a new one, passing this to the constructor.
return new EquatableList<T>(this);
}
#endregion
#region Object overrides
/// <summary>
/// If the object passed implements <see cref="IList{T}"/>,
/// compares this sequence to <paramref name="other"/>, returning <c>true</c> if they
/// are equal, <c>false</c> otherwise.
/// <para/>
/// The comparison takes into consideration any values in this collection and values
/// of any nested collections, but does not take into consideration the data type.
/// Therefore, <see cref="EquatableList{T}"/> can equal any <see cref="IList{T}"/>
/// with the exact same values in the same order.
/// </summary>
/// <param name="other">The other object
/// to compare against.</param>
/// <returns><c>true</c> if the sequence in <paramref name="other"/>
/// is the same as this one.</returns>
public override bool Equals(object other)
{
if (!(other is IList<T>))
{
return false;
}
return this.Equals(other as IList<T>);
}
/// <summary>
/// Returns the hash code value for this list.
/// <para/>
/// The hash code determination takes into consideration any values in
/// this collection and values of any nested collections, but does not
/// take into consideration the data type. Therefore, the hash codes will
/// be exactly the same for this <see cref="EquatableList{T}"/> and another
/// <see cref="IList{T}"/> (including arrays) with the same values in the
/// same order.
/// </summary>
/// <returns>the hash code value for this list</returns>
public override int GetHashCode()
{
return Collections.GetHashCode(this);
}
/// <summary>
/// Returns a string representation of this collection (and any nested collections).
/// The string representation consists of a list of the collection's elements in
/// the order they are returned by its enumerator, enclosed in square brackets
/// ("[]"). Adjacent elements are separated by the characters ", " (comma and space).
/// </summary>
/// <returns>a string representation of this collection</returns>
public override string ToString()
{
return Collections.ToString(this);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapSearchModule")]
public class MapSearchModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Scene m_scene = null; // only need one for communication with GridService
List<Scene> m_scenes = new List<Scene>();
List<UUID> m_Clients;
IWorldMapModule m_WorldMap;
IWorldMapModule WorldMap
{
get
{
if (m_WorldMap == null)
m_WorldMap = m_scene.RequestModuleInterface<IWorldMapModule>();
return m_WorldMap;
}
}
#region ISharedRegionModule Members
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
{
m_scene = scene;
}
m_scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
m_Clients = new List<UUID>();
}
public void RemoveRegion(Scene scene)
{
m_scenes.Remove(scene);
if (m_scene == scene && m_scenes.Count > 0)
m_scene = m_scenes[0];
scene.EventManager.OnNewClient -= OnNewClient;
}
public void PostInitialise()
{
}
public void Close()
{
m_scene = null;
m_scenes.Clear();
}
public string Name
{
get { return "MapSearchModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void RegionLoaded(Scene scene)
{
}
#endregion
private void OnNewClient(IClientAPI client)
{
client.OnMapNameRequest += OnMapNameRequestHandler;
}
private void OnMapNameRequestHandler(IClientAPI remoteClient, string mapName, uint flags)
{
lock (m_Clients)
{
if (m_Clients.Contains(remoteClient.AgentId))
return;
m_Clients.Add(remoteClient.AgentId);
}
try
{
OnMapNameRequest(remoteClient, mapName, flags);
}
finally
{
lock (m_Clients)
m_Clients.Remove(remoteClient.AgentId);
}
}
private void OnMapNameRequest(IClientAPI remoteClient, string mapName, uint flags)
{
List<MapBlockData> blocks = new List<MapBlockData>();
if (mapName.Length < 3 || (mapName.EndsWith("#") && mapName.Length < 4))
{
// final block, closing the search result
AddFinalBlock(blocks);
// flags are agent flags sent from the viewer.
// they have different values depending on different viewers, apparently
remoteClient.SendMapBlock(blocks, flags);
remoteClient.SendAlertMessage("Use a search string with at least 3 characters");
return;
}
List<GridRegion> regionInfos = m_scene.GridService.GetRegionsByName(m_scene.RegionInfo.ScopeID, mapName, 20);
string mapNameOrig = mapName;
if (regionInfos.Count == 0)
{
// Hack to get around the fact that ll V3 now drops the port from the
// map name. See https://jira.secondlife.com/browse/VWR-28570
//
// Caller, use this magic form instead:
// secondlife://http|!!mygrid.com|8002|Region+Name/128/128
// or url encode if possible.
// the hacks we do with this viewer...
//
if (mapName.Contains("|"))
mapName = mapName.Replace('|', ':');
if (mapName.Contains("+"))
mapName = mapName.Replace('+', ' ');
if (mapName.Contains("!"))
mapName = mapName.Replace('!', '/');
if (mapName != mapNameOrig)
regionInfos = m_scene.GridService.GetRegionsByName(m_scene.RegionInfo.ScopeID, mapName, 20);
}
m_log.DebugFormat("[MAPSEARCHMODULE]: search {0} returned {1} regions. Flags={2}", mapName, regionInfos.Count, flags);
if (regionInfos.Count > 0)
{
foreach (GridRegion info in regionInfos)
{
if ((flags & 2) == 2) // V2 sends this
{
List<MapBlockData> datas = WorldMap.Map2BlockFromGridRegion(info, flags);
// ugh! V2-3 is very sensitive about the result being
// exactly the same as the requested name
if (regionInfos.Count == 1 && (mapName != mapNameOrig))
datas.ForEach(d => d.Name = mapNameOrig);
blocks.AddRange(datas);
}
else
{
MapBlockData data = WorldMap.MapBlockFromGridRegion(info, flags);
blocks.Add(data);
}
}
}
// final block, closing the search result
AddFinalBlock(blocks);
// flags are agent flags sent from the viewer.
// they have different values depending on different viewers, apparently
remoteClient.SendMapBlock(blocks, flags);
// send extra user messages for V3
// because the UI is very confusing
// while we don't fix the hard-coded urls
if (flags == 2)
{
if (regionInfos.Count == 0)
remoteClient.SendAlertMessage("No regions found with that name.");
// this seems unnecessary because found regions will show up in the search results
//else if (regionInfos.Count == 1)
// remoteClient.SendAlertMessage("Region found!");
}
}
private void AddFinalBlock(List<MapBlockData> blocks)
{
// final block, closing the search result
MapBlockData data = new MapBlockData();
data.Agents = 0;
data.Access = (byte)SimAccess.NonExistent;
data.MapImageId = UUID.Zero;
data.Name = "";
data.RegionFlags = 0;
data.WaterHeight = 0; // not used
data.X = 0;
data.Y = 0;
blocks.Add(data);
}
// private Scene GetClientScene(IClientAPI client)
// {
// foreach (Scene s in m_scenes)
// {
// if (client.Scene.RegionInfo.RegionHandle == s.RegionInfo.RegionHandle)
// return s;
// }
// return m_scene;
// }
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using NetGore.IO;
using SFML.Graphics;
namespace NetGore.Graphics
{
/// <summary>
/// A <see cref="GrhData"/> that contains multiple frames to create an animation.
/// </summary>
public sealed class AnimatedGrhData : GrhData
{
const string _framesNodeName = "Frames";
const string _speedValueKey = "Speed";
StationaryGrhData[] _frames;
Vector2 _size;
float _speed;
/// <summary>
/// Initializes a new instance of the <see cref="AnimatedGrhData"/> class.
/// </summary>
/// <param name="grhIndex">The <see cref="GrhIndex"/>.</param>
/// <param name="cat">The <see cref="SpriteCategorization"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="cat"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="grhIndex"/> is equal to GrhIndex.Invalid.</exception>
public AnimatedGrhData(GrhIndex grhIndex, SpriteCategorization cat) : base(grhIndex, cat)
{
_frames = new StationaryGrhData[0];
_speed = 1f / 300f;
}
/// <summary>
/// Initializes a new instance of the <see cref="AnimatedGrhData"/> class.
/// </summary>
/// <param name="r">The <see cref="IValueReader"/>.</param>
/// <param name="grhIndex">The <see cref="GrhIndex"/>.</param>
/// <param name="cat">The <see cref="SpriteCategorization"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="cat"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="grhIndex"/> is equal to GrhIndex.Invalid.</exception>
AnimatedGrhData(IValueReader r, GrhIndex grhIndex, SpriteCategorization cat) : base(grhIndex, cat)
{
var speed = r.ReadInt(_speedValueKey);
var frames = r.ReadMany(_framesNodeName, (xreader, xname) => xreader.ReadGrhIndex(xname));
_speed = 1f / speed;
_frames = CreateFrames(frames);
_size = GetMaxSize(_frames);
}
/// <summary>
/// When overridden in the derived class, gets the frames in an animated <see cref="GrhData"/>, or an
/// IEnumerable containing a reference to its self if stationary.
/// </summary>
public override IEnumerable<StationaryGrhData> Frames
{
get { return _frames; }
}
/// <summary>
/// When overridden in the derived class, gets the number of frames in this <see cref="GrhData"/>. If this
/// is not an animated <see cref="GrhData"/>, this value will always return 0.
/// </summary>
public override int FramesCount
{
get { return _frames.Length; }
}
/// <summary>
/// When overridden in the derived class, gets the size of the <see cref="GrhData"/>'s sprite in pixels.
/// </summary>
public override Vector2 Size
{
get { return _size; }
}
/// <summary>
/// Gets or sets the speed multiplier of the Grh animation where each frame lasts 1f/Speed milliseconds.
/// </summary>
public override float Speed
{
get { return _speed; }
}
/// <summary>
/// Creates the array of frames for an <see cref="AnimatedGrhData"/>.
/// </summary>
/// <param name="frameIndices">The indices of the frames.</param>
/// <returns>The array of <see cref="StationaryGrhData"/> frames.</returns>
/// <exception cref="GrhDataException">A frame in this <see cref="AnimatedGrhData"/> failed to be loaded.</exception>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "GrhData")]
StationaryGrhData[] CreateFrames(IList<GrhIndex> frameIndices)
{
var frames = new StationaryGrhData[frameIndices.Count];
for (var i = 0; i < frameIndices.Count; i++)
{
frames[i] = GrhInfo.GetData(frameIndices[i]) as StationaryGrhData;
if (frames[i] == null)
{
const string errmsg =
"Failed to load GrhData `{0}`. GrhData `{1}` needs it for frame index `{2}` (0-based), out of `{3}` frames total.";
var err = string.Format(errmsg, frames[i], this, i, frameIndices.Count);
throw new GrhDataException(this, err);
}
}
return frames;
}
/// <summary>
/// When overridden in the derived class, creates a new <see cref="GrhData"/> equal to this <see cref="GrhData"/>
/// except for the specified parameters.
/// </summary>
/// <param name="newCategorization">The <see cref="SpriteCategorization"/> to give to the new
/// <see cref="GrhData"/>.</param>
/// <param name="newGrhIndex">The <see cref="GrhIndex"/> to give to the new
/// <see cref="GrhData"/>.</param>
/// <returns>
/// A deep copy of this <see cref="GrhData"/>.
/// </returns>
protected override GrhData DeepCopy(SpriteCategorization newCategorization, GrhIndex newGrhIndex)
{
var copyArray = new StationaryGrhData[_frames.Length];
Array.Copy(_frames, copyArray, _frames.Length);
var copy = new AnimatedGrhData(newGrhIndex, newCategorization) { _frames = copyArray };
copy.SetSpeed(Speed);
return copy;
}
/// <summary>
/// When overridden in the derived class, gets the frame in an animated <see cref="GrhData"/> with the
/// corresponding index, or null if the index is out of range. If stationary, this will always return
/// a reference to its self, no matter what the index is.
/// </summary>
/// <param name="frameIndex">The index of the frame to get.</param>
/// <returns>
/// The frame with the given <paramref name="frameIndex"/>, or null if the <paramref name="frameIndex"/>
/// is invalid, or a reference to its self if this is not an animated <see cref="GrhData"/>.
/// </returns>
public override StationaryGrhData GetFrame(int frameIndex)
{
if (frameIndex < 0 || frameIndex >= _frames.Length)
return null;
return _frames[frameIndex];
}
/// <summary>
/// Reads a <see cref="GrhData"/> from an <see cref="IValueReader"/>.
/// </summary>
/// <param name="r">The <see cref="IValueReader"/> to read from.</param>
/// <returns>
/// The <see cref="GrhData"/> read from the <see cref="IValueReader"/>.
/// </returns>
public static AnimatedGrhData Read(IValueReader r)
{
GrhIndex grhIndex;
SpriteCategorization categorization;
ReadHeader(r, out grhIndex, out categorization);
return new AnimatedGrhData(r, grhIndex, categorization);
}
public void SetFrames(IEnumerable<GrhIndex> frameIndices)
{
SetFrames(CreateFrames(frameIndices.ToArray()));
}
public void SetFrames(IEnumerable<StationaryGrhData> frames)
{
_frames = frames.ToArray();
_size = GetMaxSize(_frames);
}
/// <summary>
/// Sets the speed of the <see cref="AnimatedGrhData"/>.
/// </summary>
/// <param name="newSpeed">The new speed.</param>
public void SetSpeed(float newSpeed)
{
// Ensure we are using the right units
if (newSpeed > 1.0f)
newSpeed = 1f / newSpeed;
_speed = newSpeed;
}
/// <summary>
/// When overridden in the derived class, writes the values unique to this derived type to the
/// <paramref name="writer"/>.
/// </summary>
/// <param name="writer">The <see cref="IValueWriter"/> to write to.</param>
protected override void WriteCustomValues(IValueWriter writer)
{
var frameIndices = _frames.Select(x => x.GrhIndex).ToArray();
writer.Write(_speedValueKey, (int)(1f / Speed));
writer.WriteMany(_framesNodeName, frameIndices, writer.Write);
}
}
}
| |
using Lucene.Net.Analysis.TokenAttributes;
using System;
using Lucene.Net.Documents;
using Lucene.Net.Support;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Lucene.Net.Analysis;
using NUnit.Framework;
using System.IO;
using BytesRef = Lucene.Net.Util.BytesRef;
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using TermVectorsReader = Lucene.Net.Codecs.TermVectorsReader;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
[TestFixture]
public class TestTermVectorsReader : LuceneTestCase
{
public TestTermVectorsReader()
{
InitializeInstanceFields();
}
private void InitializeInstanceFields()
{
Positions = new int[TestTerms.Length][];
Tokens = new TestToken[TestTerms.Length * TERM_FREQ];
}
//Must be lexicographically sorted, will do in setup, versus trying to maintain here
private string[] TestFields = new string[] { "f1", "f2", "f3", "f4" };
private bool[] TestFieldsStorePos = new bool[] { true, false, true, false };
private bool[] TestFieldsStoreOff = new bool[] { true, false, false, true };
private string[] TestTerms = new string[] { "this", "is", "a", "test" };
private int[][] Positions;
private Directory Dir;
private SegmentCommitInfo Seg;
private FieldInfos FieldInfos = new FieldInfos(new FieldInfo[0]);
private static int TERM_FREQ = 3;
internal class TestToken : IComparable<TestToken>
{
private readonly TestTermVectorsReader OuterInstance;
public TestToken(TestTermVectorsReader outerInstance)
{
this.OuterInstance = outerInstance;
}
internal string Text;
internal int Pos;
internal int StartOffset;
internal int EndOffset;
public virtual int CompareTo(TestToken other)
{
return Pos - other.Pos;
}
}
internal TestToken[] Tokens;
[SetUp]
public override void SetUp()
{
base.SetUp();
/*
for (int i = 0; i < testFields.Length; i++) {
fieldInfos.Add(testFields[i], true, true, testFieldsStorePos[i], testFieldsStoreOff[i]);
}
*/
Array.Sort(TestTerms);
int tokenUpto = 0;
for (int i = 0; i < TestTerms.Length; i++)
{
Positions[i] = new int[TERM_FREQ];
// first position must be 0
for (int j = 0; j < TERM_FREQ; j++)
{
// positions are always sorted in increasing order
Positions[i][j] = (int)(j * 10 + new Random(1).NextDouble() * 10);
TestToken token = Tokens[tokenUpto++] = new TestToken(this);
token.Text = TestTerms[i];
token.Pos = Positions[i][j];
token.StartOffset = j * 10;
token.EndOffset = j * 10 + TestTerms[i].Length;
}
}
Array.Sort(Tokens);
Dir = NewDirectory();
IndexWriter writer = new IndexWriter(Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MyAnalyzer(this)).SetMaxBufferedDocs(-1).SetMergePolicy(NewLogMergePolicy(false, 10)).SetUseCompoundFile(false));
Document doc = new Document();
for (int i = 0; i < TestFields.Length; i++)
{
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
if (TestFieldsStorePos[i] && TestFieldsStoreOff[i])
{
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
}
else if (TestFieldsStorePos[i] && !TestFieldsStoreOff[i])
{
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
}
else if (!TestFieldsStorePos[i] && TestFieldsStoreOff[i])
{
customType.StoreTermVectors = true;
customType.StoreTermVectorOffsets = true;
}
else
{
customType.StoreTermVectors = true;
}
doc.Add(new Field(TestFields[i], "", customType));
}
//Create 5 documents for testing, they all have the same
//terms
for (int j = 0; j < 5; j++)
{
writer.AddDocument(doc);
}
writer.Commit();
Seg = writer.NewestSegment();
writer.Dispose();
FieldInfos = SegmentReader.ReadFieldInfos(Seg);
}
[TearDown]
public override void TearDown()
{
Dir.Dispose();
base.TearDown();
}
private class MyTokenizer : Tokenizer
{
private readonly TestTermVectorsReader OuterInstance;
internal int TokenUpto;
internal readonly ICharTermAttribute TermAtt;
internal readonly IPositionIncrementAttribute PosIncrAtt;
internal readonly IOffsetAttribute OffsetAtt;
public MyTokenizer(TestTermVectorsReader outerInstance, TextReader reader)
: base(reader)
{
this.OuterInstance = outerInstance;
TermAtt = AddAttribute<ICharTermAttribute>();
PosIncrAtt = AddAttribute<IPositionIncrementAttribute>();
OffsetAtt = AddAttribute<IOffsetAttribute>();
}
public sealed override bool IncrementToken()
{
if (TokenUpto >= OuterInstance.Tokens.Length)
{
return false;
}
else
{
TestToken testToken = OuterInstance.Tokens[TokenUpto++];
ClearAttributes();
TermAtt.Append(testToken.Text);
OffsetAtt.SetOffset(testToken.StartOffset, testToken.EndOffset);
if (TokenUpto > 1)
{
PosIncrAtt.PositionIncrement = testToken.Pos - OuterInstance.Tokens[TokenUpto - 2].Pos;
}
else
{
PosIncrAtt.PositionIncrement = testToken.Pos + 1;
}
return true;
}
}
public override void Reset()
{
base.Reset();
this.TokenUpto = 0;
}
}
private class MyAnalyzer : Analyzer
{
private readonly TestTermVectorsReader OuterInstance;
public MyAnalyzer(TestTermVectorsReader outerInstance)
{
this.OuterInstance = outerInstance;
}
protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
return new TokenStreamComponents(new MyTokenizer(OuterInstance, reader));
}
}
[Test]
public virtual void Test()
{
//Check to see the files were created properly in setup
DirectoryReader reader = DirectoryReader.Open(Dir);
foreach (AtomicReaderContext ctx in reader.Leaves)
{
SegmentReader sr = (SegmentReader)ctx.Reader;
Assert.IsTrue(sr.FieldInfos.HasVectors);
}
reader.Dispose();
}
[Test]
public virtual void TestReader()
{
TermVectorsReader reader = Codec.Default.TermVectorsFormat.VectorsReader(Dir, Seg.Info, FieldInfos, NewIOContext(Random()));
for (int j = 0; j < 5; j++)
{
Terms vector = reader.Get(j).GetTerms(TestFields[0]);
Assert.IsNotNull(vector);
Assert.AreEqual(TestTerms.Length, vector.Count);
TermsEnum termsEnum = vector.GetIterator(null);
for (int i = 0; i < TestTerms.Length; i++)
{
BytesRef text = termsEnum.Next();
Assert.IsNotNull(text);
string term = text.Utf8ToString();
//System.out.println("Term: " + term);
Assert.AreEqual(TestTerms[i], term);
}
Assert.IsNull(termsEnum.Next());
}
reader.Dispose();
}
[Test]
public virtual void TestDocsEnum()
{
TermVectorsReader reader = Codec.Default.TermVectorsFormat.VectorsReader(Dir, Seg.Info, FieldInfos, NewIOContext(Random()));
for (int j = 0; j < 5; j++)
{
Terms vector = reader.Get(j).GetTerms(TestFields[0]);
Assert.IsNotNull(vector);
Assert.AreEqual(TestTerms.Length, vector.Count);
TermsEnum termsEnum = vector.GetIterator(null);
DocsEnum docsEnum = null;
for (int i = 0; i < TestTerms.Length; i++)
{
BytesRef text = termsEnum.Next();
Assert.IsNotNull(text);
string term = text.Utf8ToString();
//System.out.println("Term: " + term);
Assert.AreEqual(TestTerms[i], term);
docsEnum = TestUtil.Docs(Random(), termsEnum, null, docsEnum, DocsFlags.NONE);
Assert.IsNotNull(docsEnum);
int doc = docsEnum.DocID;
Assert.AreEqual(-1, doc);
Assert.IsTrue(docsEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, docsEnum.NextDoc());
}
Assert.IsNull(termsEnum.Next());
}
reader.Dispose();
}
[Test]
public virtual void TestPositionReader()
{
TermVectorsReader reader = Codec.Default.TermVectorsFormat.VectorsReader(Dir, Seg.Info, FieldInfos, NewIOContext(Random()));
//BytesRef[] terms; // LUCENENET NOTE: Not used in Lucene
Terms vector = reader.Get(0).GetTerms(TestFields[0]);
Assert.IsNotNull(vector);
Assert.AreEqual(TestTerms.Length, vector.Count);
TermsEnum termsEnum = vector.GetIterator(null);
DocsAndPositionsEnum dpEnum = null;
for (int i = 0; i < TestTerms.Length; i++)
{
BytesRef text = termsEnum.Next();
Assert.IsNotNull(text);
string term = text.Utf8ToString();
//System.out.println("Term: " + term);
Assert.AreEqual(TestTerms[i], term);
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsNotNull(dpEnum);
int doc = dpEnum.DocID;
Assert.AreEqual(-1, doc);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(dpEnum.Freq, Positions[i].Length);
for (int j = 0; j < Positions[i].Length; j++)
{
Assert.AreEqual(Positions[i][j], dpEnum.NextPosition());
}
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
doc = dpEnum.DocID;
Assert.AreEqual(-1, doc);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.IsNotNull(dpEnum);
Assert.AreEqual(dpEnum.Freq, Positions[i].Length);
for (int j = 0; j < Positions[i].Length; j++)
{
Assert.AreEqual(Positions[i][j], dpEnum.NextPosition());
Assert.AreEqual(j * 10, dpEnum.StartOffset);
Assert.AreEqual(j * 10 + TestTerms[i].Length, dpEnum.EndOffset);
}
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
}
Terms freqVector = reader.Get(0).GetTerms(TestFields[1]); //no pos, no offset
Assert.IsNotNull(freqVector);
Assert.AreEqual(TestTerms.Length, freqVector.Count);
termsEnum = freqVector.GetIterator(null);
Assert.IsNotNull(termsEnum);
for (int i = 0; i < TestTerms.Length; i++)
{
BytesRef text = termsEnum.Next();
Assert.IsNotNull(text);
string term = text.Utf8ToString();
//System.out.println("Term: " + term);
Assert.AreEqual(TestTerms[i], term);
Assert.IsNotNull(termsEnum.Docs(null, null));
Assert.IsNull(termsEnum.DocsAndPositions(null, null)); // no pos
}
reader.Dispose();
}
[Test]
public virtual void TestOffsetReader()
{
TermVectorsReader reader = Codec.Default.TermVectorsFormat.VectorsReader(Dir, Seg.Info, FieldInfos, NewIOContext(Random()));
Terms vector = reader.Get(0).GetTerms(TestFields[0]);
Assert.IsNotNull(vector);
TermsEnum termsEnum = vector.GetIterator(null);
Assert.IsNotNull(termsEnum);
Assert.AreEqual(TestTerms.Length, vector.Count);
DocsAndPositionsEnum dpEnum = null;
for (int i = 0; i < TestTerms.Length; i++)
{
BytesRef text = termsEnum.Next();
Assert.IsNotNull(text);
string term = text.Utf8ToString();
Assert.AreEqual(TestTerms[i], term);
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsNotNull(dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(dpEnum.Freq, Positions[i].Length);
for (int j = 0; j < Positions[i].Length; j++)
{
Assert.AreEqual(Positions[i][j], dpEnum.NextPosition());
}
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.IsNotNull(dpEnum);
Assert.AreEqual(dpEnum.Freq, Positions[i].Length);
for (int j = 0; j < Positions[i].Length; j++)
{
Assert.AreEqual(Positions[i][j], dpEnum.NextPosition());
Assert.AreEqual(j * 10, dpEnum.StartOffset);
Assert.AreEqual(j * 10 + TestTerms[i].Length, dpEnum.EndOffset);
}
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
}
reader.Dispose();
}
[Test]
public virtual void TestIllegalIndexableField()
{
Directory dir = NewDirectory();
RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Similarity, TimeZone);
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.StoreTermVectors = true;
ft.StoreTermVectorPayloads = true;
Document doc = new Document();
doc.Add(new Field("field", "value", ft));
try
{
w.AddDocument(doc);
Assert.Fail("did not hit exception");
}
catch (System.ArgumentException iae)
{
// Expected
Assert.AreEqual("cannot index term vector payloads without term vector positions (field=\"field\")", iae.Message);
}
ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.StoreTermVectors = false;
ft.StoreTermVectorOffsets = true;
doc = new Document();
doc.Add(new Field("field", "value", ft));
try
{
w.AddDocument(doc);
Assert.Fail("did not hit exception");
}
catch (System.ArgumentException iae)
{
// Expected
Assert.AreEqual("cannot index term vector offsets when term vectors are not indexed (field=\"field\")", iae.Message);
}
ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.StoreTermVectors = false;
ft.StoreTermVectorPositions = true;
doc = new Document();
doc.Add(new Field("field", "value", ft));
try
{
w.AddDocument(doc);
Assert.Fail("did not hit exception");
}
catch (System.ArgumentException iae)
{
// Expected
Assert.AreEqual("cannot index term vector positions when term vectors are not indexed (field=\"field\")", iae.Message);
}
ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.StoreTermVectors = false;
ft.StoreTermVectorPayloads = true;
doc = new Document();
doc.Add(new Field("field", "value", ft));
try
{
w.AddDocument(doc);
Assert.Fail("did not hit exception");
}
catch (System.ArgumentException iae)
{
// Expected
Assert.AreEqual("cannot index term vector payloads when term vectors are not indexed (field=\"field\")", iae.Message);
}
w.Dispose();
dir.Dispose();
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Indicators.Algo
File: ParabolicSar.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Indicators
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Ecng.Serialization;
using StockSharp.Algo.Candles;
using StockSharp.Localization;
/// <summary>
/// Trend indicator implementation - Parabolic SAR.
/// </summary>
/// <remarks>
/// http://ta.mql4.com/indicators/trends/parabolic_sar.
/// </remarks>
[DisplayName("Parabolic SAR")]
[DescriptionLoc(LocalizedStrings.Str809Key)]
[IndicatorIn(typeof(CandleIndicatorValue))]
public class ParabolicSar : BaseIndicator
{
private class CalcBuffer
{
private readonly ParabolicSar _ind;
private decimal _prevValue;
private bool _longPosition;
private decimal _xp; // Extreme Price
private decimal _af; // Acceleration factor
private int _prevBar;
private bool _afIncreased;
private int _reverseBar;
private decimal _reverseValue;
private decimal _prevSar;
private decimal _todaySar;
private IList<Candle> Candles => _ind._candles;
public CalcBuffer(ParabolicSar parent) => _ind = parent;
public CalcBuffer Clone() => (CalcBuffer) MemberwiseClone();
public decimal Calculate(Candle candle)
{
if (Candles.Count == 0)
Candles.Add(candle);
if (candle.OpenTime != Candles[Candles.Count - 1].OpenTime)
Candles.Add(candle);
else
Candles[Candles.Count - 1] = candle;
_prevValue = _ind.GetCurrentValue();
if (Candles.Count < 3)
return _prevValue;
if (Candles.Count == 3)
{
_longPosition = Candles[Candles.Count - 1].HighPrice > Candles[Candles.Count - 2].HighPrice;
var max = Candles.Max(t => t.HighPrice);
var min = Candles.Min(t => t.LowPrice);
_xp = _longPosition ? max : min;
_af = _ind.Acceleration;
return _xp + (_longPosition ? -1 : 1) * (max - min) * _af;
}
if (_afIncreased && _prevBar != Candles.Count)
_afIncreased = false;
var value = _prevValue;
if (_reverseBar != Candles.Count)
{
_todaySar = TodaySar(_prevValue + _af * (_xp - _prevValue));
for (var x = 1; x <= 2; x++)
{
if (_longPosition)
{
if (_todaySar > Candles[Candles.Count - 1 - x].LowPrice)
_todaySar = Candles[Candles.Count - 1 - x].LowPrice;
}
else
{
if (_todaySar < Candles[Candles.Count - 1 - x].HighPrice)
_todaySar = Candles[Candles.Count - 1 - x].HighPrice;
}
}
if ((_longPosition && (Candles[Candles.Count - 1].LowPrice < _todaySar || Candles[Candles.Count - 2].LowPrice < _todaySar))
|| (!_longPosition && (Candles[Candles.Count - 1].HighPrice > _todaySar || Candles[Candles.Count - 2].HighPrice > _todaySar)))
{
return Reverse();
}
if (_longPosition)
{
if (_prevBar != Candles.Count || Candles[Candles.Count - 1].LowPrice < _prevSar)
{
value = _todaySar;
_prevSar = _todaySar;
}
else
value = _prevSar;
if (Candles[Candles.Count - 1].HighPrice > _xp)
{
_xp = Candles[Candles.Count - 1].HighPrice;
AfIncrease();
}
}
else if (!_longPosition)
{
if (_prevBar != Candles.Count || Candles[Candles.Count - 1].HighPrice > _prevSar)
{
value = _todaySar;
_prevSar = _todaySar;
}
else
value = _prevSar;
if (Candles[Candles.Count - 1].LowPrice < _xp)
{
_xp = Candles[Candles.Count - 1].LowPrice;
AfIncrease();
}
}
}
else
{
if (_longPosition && Candles[Candles.Count - 1].HighPrice > _xp)
_xp = Candles[Candles.Count - 1].HighPrice;
else if (!_longPosition && Candles[Candles.Count - 1].LowPrice < _xp)
_xp = Candles[Candles.Count - 1].LowPrice;
value = _prevSar;
_todaySar = TodaySar(_longPosition ? Math.Min(_reverseValue, Candles[Candles.Count - 1].LowPrice) :
Math.Max(_reverseValue, Candles[Candles.Count - 1].HighPrice));
}
_prevBar = Candles.Count;
return value;
}
private decimal TodaySar(decimal todaySar)
{
if (_longPosition)
{
var lowestSar = Math.Min(Math.Min(todaySar, Candles[Candles.Count - 1].LowPrice), Candles[Candles.Count - 2].LowPrice);
todaySar = Candles[Candles.Count - 1].LowPrice > lowestSar ? lowestSar : Reverse();
}
else
{
var highestSar = Math.Max(Math.Max(todaySar, Candles[Candles.Count - 1].HighPrice), Candles[Candles.Count - 2].HighPrice);
todaySar = Candles[Candles.Count - 1].HighPrice < highestSar ? highestSar : Reverse();
}
return todaySar;
}
private decimal Reverse()
{
var todaySar = _xp;
if ((_longPosition && _prevSar > Candles[Candles.Count - 1].LowPrice) ||
(!_longPosition && _prevSar < Candles[Candles.Count - 1].HighPrice) || _prevBar != Candles.Count)
{
_longPosition = !_longPosition;
_reverseBar = Candles.Count;
_reverseValue = _xp;
_af = _ind.Acceleration;
_xp = _longPosition ? Candles[Candles.Count - 1].HighPrice : Candles[Candles.Count - 1].LowPrice;
_prevSar = todaySar;
}
else
todaySar = _prevSar;
return todaySar;
}
private void AfIncrease()
{
if (_afIncreased)
return;
_af = Math.Min(_ind.AccelerationMax, _af + _ind.AccelerationStep);
_afIncreased = true;
}
public void Reset()
{
Candles.Clear();
_prevValue = 0;
_longPosition = false;
_xp = 0;
_af = 0;
_prevBar = 0;
_afIncreased = false;
_reverseBar = 0;
_reverseValue = 0;
_prevSar = 0;
_todaySar = 0;
}
}
private readonly CalcBuffer _buf;
private readonly List<Candle> _candles = new();
private decimal _acceleration;
private decimal _accelerationStep;
private decimal _accelerationMax;
/// <summary>
/// Initializes a new instance of the <see cref="ParabolicSar"/>.
/// </summary>
public ParabolicSar()
{
_buf = new CalcBuffer(this);
Acceleration = 0.02M;
AccelerationStep = 0.02M;
AccelerationMax = 0.2M;
}
/// <summary>
/// Acceleration factor.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str810Key)]
[DescriptionLoc(LocalizedStrings.Str811Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal Acceleration
{
get => _acceleration;
set
{
_acceleration = value;
Reset();
}
}
/// <summary>
/// Acceleration factor step.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str812Key)]
[DescriptionLoc(LocalizedStrings.Str813Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal AccelerationStep
{
get => _accelerationStep;
set
{
_accelerationStep = value;
Reset();
}
}
/// <summary>
/// Maximum acceleration factor.
/// </summary>
[DisplayNameLoc(LocalizedStrings.MaxKey)]
[DescriptionLoc(LocalizedStrings.Str815Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal AccelerationMax
{
get => _accelerationMax;
set
{
_accelerationMax = value;
Reset();
}
}
/// <inheritdoc />
protected override IIndicatorValue OnProcess(IIndicatorValue input)
{
if (input.IsFinal)
IsFormed = true;
var b = input.IsFinal ? _buf : _buf.Clone();
var val = b.Calculate(input.GetValue<Candle>());
return val == 0 ? new DecimalIndicatorValue(this) : new DecimalIndicatorValue(this, val);
}
/// <inheritdoc />
public override void Reset()
{
base.Reset();
_buf.Reset();
}
/// <inheritdoc />
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Acceleration = storage.GetValue(nameof(Acceleration), 0.02M);
AccelerationMax = storage.GetValue(nameof(AccelerationMax), 0.2M);
AccelerationStep = storage.GetValue(nameof(AccelerationStep), 0.02M);
}
/// <inheritdoc />
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Acceleration), Acceleration);
storage.SetValue(nameof(AccelerationMax), AccelerationMax);
storage.SetValue(nameof(AccelerationStep), AccelerationStep);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using Newtonsoft.Json.Utilities;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
internal enum State
{
Start,
Property,
ObjectStart,
Object,
ArrayStart,
Array,
ConstructorStart,
Constructor,
Closed,
Error
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] StateArray;
internal static readonly State[][] StateArrayTempate = new[] {
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[]{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[]{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[]{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[]{ State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* Property */new[]{ State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value (this will be copied) */new[]{ State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }
};
internal static State[][] BuildStateArray()
{
var allStates = StateArrayTempate.ToList();
var errorStates = StateArrayTempate[0];
var valueStates = StateArrayTempate[7];
foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken)))
{
if (allStates.Count <= (int)valueToken)
{
switch (valueToken)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
allStates.Add(valueStates);
break;
default:
allStates.Add(errorStates);
break;
}
}
}
return allStates.ToArray();
}
static JsonWriter()
{
StateArray = BuildStateArray();
}
private readonly List<JsonPosition> _stack;
private JsonPosition _currentPosition;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the writer is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the writer is closed; otherwise false. The default is true.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get
{
int depth = _stack.Count;
if (Peek() != JsonContainerType.None)
depth++;
return depth;
}
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null);
}
}
}
internal string ContainerPath
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
return JsonPosition.BuildPath(_stack);
}
}
/// <summary>
/// Gets the path of the writer.
/// </summary>
public string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
IEnumerable<JsonPosition> positions = (!insideContainer)
? _stack
: _stack.Concat(new[] { _currentPosition });
return JsonPosition.BuildPath(positions);
}
}
private DateFormatHandling _dateFormatHandling;
private DateTimeZoneHandling _dateTimeZoneHandling;
private StringEscapeHandling _stringEscapeHandling;
private FloatFormatHandling _floatFormatHandling;
private string _dateFormatString;
private CultureInfo _culture;
/// <summary>
/// Indicates how JSON text output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting; }
set { _formatting = value; }
}
/// <summary>
/// Get or set how dates are written to JSON text.
/// </summary>
public DateFormatHandling DateFormatHandling
{
get { return _dateFormatHandling; }
set { _dateFormatHandling = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling when writing JSON text.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set { _dateTimeZoneHandling = value; }
}
/// <summary>
/// Get or set how strings are escaped when writing JSON text.
/// </summary>
public StringEscapeHandling StringEscapeHandling
{
get { return _stringEscapeHandling; }
set
{
_stringEscapeHandling = value;
OnStringEscapeHandlingChanged();
}
}
internal virtual void OnStringEscapeHandlingChanged()
{
// hacky but there is a calculated value that relies on StringEscapeHandling
}
/// <summary>
/// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>,
/// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>,
/// are written to JSON text.
/// </summary>
public FloatFormatHandling FloatFormatHandling
{
get { return _floatFormatHandling; }
set { _floatFormatHandling = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatting when writing JSON text.
/// </summary>
public string DateFormatString
{
get { return _dateFormatString; }
set { _dateFormatString = value; }
}
/// <summary>
/// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class.
/// </summary>
protected JsonWriter()
{
_stack = new List<JsonPosition>(4);
_currentState = State.Start;
_formatting = Formatting.None;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
CloseOutput = true;
}
internal void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
_currentPosition.Position++;
}
private void Push(JsonContainerType value)
{
if (_currentPosition.Type != JsonContainerType.None)
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
}
private JsonContainerType Pop()
{
JsonPosition oldPosition = _currentPosition;
if (_stack.Count > 0)
{
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
_currentPosition = new JsonPosition();
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public virtual void Close()
{
AutoCompleteAll();
}
/// <summary>
/// Writes the beginning of a Json object.
/// </summary>
public virtual void WriteStartObject()
{
InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object);
}
/// <summary>
/// Writes the end of a Json object.
/// </summary>
public virtual void WriteEndObject()
{
InternalWriteEnd(JsonContainerType.Object);
}
/// <summary>
/// Writes the beginning of a Json array.
/// </summary>
public virtual void WriteStartArray()
{
InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
InternalWriteEnd(JsonContainerType.Array);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
InternalWriteEnd(JsonContainerType.Constructor);
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
InternalWritePropertyName(name);
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param>
public virtual void WritePropertyName(string name, bool escape)
{
WritePropertyName(name);
}
/// <summary>
/// Writes the end of the current Json object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token and its children.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
WriteToken(reader, true, true);
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
/// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param>
public void WriteToken(JsonReader reader, bool writeChildren)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
WriteToken(reader, writeChildren, true);
}
internal void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate)
{
int initialDepth;
if (reader.TokenType == JsonToken.None)
initialDepth = -1;
else if (!IsStartToken(reader.TokenType))
initialDepth = reader.Depth + 1;
else
initialDepth = reader.Depth;
WriteToken(reader, initialDepth, writeChildren, writeDateConstructorAsDate);
}
internal void WriteToken(JsonReader reader, int initialDepth, bool writeChildren, bool writeDateConstructorAsDate)
{
do
{
switch (reader.TokenType)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && string.Equals(constructorName, "Date", StringComparison.Ordinal))
WriteConstructorDate(reader);
else
WriteStartConstructor(reader.Value.ToString());
break;
case JsonToken.PropertyName:
WritePropertyName(reader.Value.ToString());
break;
case JsonToken.Comment:
WriteComment((reader.Value != null) ? reader.Value.ToString() : null);
break;
case JsonToken.Integer:
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40)
if (reader.Value is BigInteger)
{
WriteValue((BigInteger)reader.Value);
}
else
#endif
{
WriteValue(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Float:
object value = reader.Value;
if (value is decimal)
WriteValue((decimal)value);
else if (value is double)
WriteValue((double)value);
else if (value is float)
WriteValue((float)value);
else
WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture));
break;
case JsonToken.String:
WriteValue(reader.Value.ToString());
break;
case JsonToken.Boolean:
WriteValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
#if !NET20
if (reader.Value is DateTimeOffset)
WriteValue((DateTimeOffset)reader.Value);
else
#endif
WriteValue(Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Raw:
WriteRawValue((reader.Value != null) ? reader.Value.ToString() : null);
break;
case JsonToken.Bytes:
WriteValue((byte[])reader.Value);
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type.");
}
}
while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
if (reader.TokenType != JsonToken.Integer)
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null);
long ticks = (long)reader.Value;
DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
if (!reader.Read())
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
if (reader.TokenType != JsonToken.EndConstructor)
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null);
WriteValue(date);
}
internal static bool IsEndToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private void WriteEnd(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
WriteEndObject();
break;
case JsonContainerType.Array:
WriteEndArray();
break;
case JsonContainerType.Constructor:
WriteEndConstructor();
break;
default:
throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null);
}
}
private void AutoCompleteAll()
{
while (Top > 0)
{
WriteEnd();
}
}
private JsonToken GetCloseTokenForType(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
return JsonToken.EndObject;
case JsonContainerType.Array:
return JsonToken.EndArray;
case JsonContainerType.Constructor:
return JsonToken.EndConstructor;
default:
throw JsonWriterException.Create(this, "No close token for type: " + type, null);
}
}
private void AutoCompleteClose(JsonContainerType type)
{
// write closing symbol and calculate new state
int levelsToComplete = 0;
if (_currentPosition.Type == type)
{
levelsToComplete = 1;
}
else
{
int top = Top - 2;
for (int i = top; i >= 0; i--)
{
int currentLevel = top - i;
if (_stack[currentLevel].Type == type)
{
levelsToComplete = i + 2;
break;
}
}
}
if (levelsToComplete == 0)
throw JsonWriterException.Create(this, "No token to close.", null);
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState == State.Property)
WriteNull();
if (_formatting == Formatting.Indented)
{
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
WriteIndent();
}
WriteEnd(token);
JsonContainerType currentLevelType = Peek();
switch (currentLevelType)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Array;
break;
case JsonContainerType.None:
_currentState = State.Start;
break;
default:
throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null);
}
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
// gets new state based on the current state and what is being written
State newState = StateArray[(int)tokenBeingWritten][(int)_currentState];
if (newState == State.Error)
throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null);
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
if (_formatting == Formatting.Indented)
{
if (_currentState == State.Property)
WriteIndentSpace();
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart)
|| (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start))
WriteIndent();
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
InternalWriteValue(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
InternalWriteValue(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
InternalWriteRaw();
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
// hack. want writer to change state as if a value had been written
UpdateScopeWithFinishedValue();
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
InternalWriteValue(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
InternalWriteValue(JsonToken.Date);
}
#if !NET20
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
InternalWriteValue(JsonToken.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{Int32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Single}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Double}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Boolean}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Char}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Byte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{SByte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Decimal}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{DateTime}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
#if !NET20
/// <summary>
/// Writes a <see cref="Nullable{DateTimeOffset}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
#endif
/// <summary>
/// Writes a <see cref="Nullable{Guid}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Guid}"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{TimeSpan}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="T:Byte[]"/> value.
/// </summary>
/// <param name="value">The <see cref="T:Byte[]"/> value to write.</param>
public virtual void WriteValue(byte[] value)
{
if (value == null)
WriteNull();
else
InternalWriteValue(JsonToken.Bytes);
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri value)
{
if (value == null)
WriteNull();
else
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
}
else
{
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40)
// this is here because adding a WriteValue(BigInteger) to JsonWriter will
// mean the user has to add a reference to System.Numerics.dll
if (value is BigInteger)
throw CreateUnsupportedTypeException(this, value);
#endif
WriteValue(this, ConvertUtils.GetTypeCode(value), value);
}
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
{
InternalWriteComment();
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
InternalWriteWhitespace(ws);
}
void IDisposable.Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_currentState != State.Closed)
Close();
}
internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value)
{
switch (typeCode)
{
case PrimitiveTypeCode.Char:
writer.WriteValue((char)value);
break;
case PrimitiveTypeCode.CharNullable:
writer.WriteValue((value == null) ? (char?)null : (char)value);
break;
case PrimitiveTypeCode.Boolean:
writer.WriteValue((bool)value);
break;
case PrimitiveTypeCode.BooleanNullable:
writer.WriteValue((value == null) ? (bool?)null : (bool)value);
break;
case PrimitiveTypeCode.SByte:
writer.WriteValue((sbyte)value);
break;
case PrimitiveTypeCode.SByteNullable:
writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value);
break;
case PrimitiveTypeCode.Int16:
writer.WriteValue((short)value);
break;
case PrimitiveTypeCode.Int16Nullable:
writer.WriteValue((value == null) ? (short?)null : (short)value);
break;
case PrimitiveTypeCode.UInt16:
writer.WriteValue((ushort)value);
break;
case PrimitiveTypeCode.UInt16Nullable:
writer.WriteValue((value == null) ? (ushort?)null : (ushort)value);
break;
case PrimitiveTypeCode.Int32:
writer.WriteValue((int)value);
break;
case PrimitiveTypeCode.Int32Nullable:
writer.WriteValue((value == null) ? (int?)null : (int)value);
break;
case PrimitiveTypeCode.Byte:
writer.WriteValue((byte)value);
break;
case PrimitiveTypeCode.ByteNullable:
writer.WriteValue((value == null) ? (byte?)null : (byte)value);
break;
case PrimitiveTypeCode.UInt32:
writer.WriteValue((uint)value);
break;
case PrimitiveTypeCode.UInt32Nullable:
writer.WriteValue((value == null) ? (uint?)null : (uint)value);
break;
case PrimitiveTypeCode.Int64:
writer.WriteValue((long)value);
break;
case PrimitiveTypeCode.Int64Nullable:
writer.WriteValue((value == null) ? (long?)null : (long)value);
break;
case PrimitiveTypeCode.UInt64:
writer.WriteValue((ulong)value);
break;
case PrimitiveTypeCode.UInt64Nullable:
writer.WriteValue((value == null) ? (ulong?)null : (ulong)value);
break;
case PrimitiveTypeCode.Single:
writer.WriteValue((float)value);
break;
case PrimitiveTypeCode.SingleNullable:
writer.WriteValue((value == null) ? (float?)null : (float)value);
break;
case PrimitiveTypeCode.Double:
writer.WriteValue((double)value);
break;
case PrimitiveTypeCode.DoubleNullable:
writer.WriteValue((value == null) ? (double?)null : (double)value);
break;
case PrimitiveTypeCode.DateTime:
writer.WriteValue((DateTime)value);
break;
case PrimitiveTypeCode.DateTimeNullable:
writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value);
break;
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
writer.WriteValue((DateTimeOffset)value);
break;
case PrimitiveTypeCode.DateTimeOffsetNullable:
writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value);
break;
#endif
case PrimitiveTypeCode.Decimal:
writer.WriteValue((decimal)value);
break;
case PrimitiveTypeCode.DecimalNullable:
writer.WriteValue((value == null) ? (decimal?)null : (decimal)value);
break;
case PrimitiveTypeCode.Guid:
writer.WriteValue((Guid)value);
break;
case PrimitiveTypeCode.GuidNullable:
writer.WriteValue((value == null) ? (Guid?)null : (Guid)value);
break;
case PrimitiveTypeCode.TimeSpan:
writer.WriteValue((TimeSpan)value);
break;
case PrimitiveTypeCode.TimeSpanNullable:
writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value);
break;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20 || WINDOWS_PHONE || SILVERLIGHT)
case PrimitiveTypeCode.BigInteger:
// this will call to WriteValue(object)
writer.WriteValue((BigInteger)value);
break;
case PrimitiveTypeCode.BigIntegerNullable:
// this will call to WriteValue(object)
writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value);
break;
#endif
case PrimitiveTypeCode.Uri:
writer.WriteValue((Uri)value);
break;
case PrimitiveTypeCode.String:
writer.WriteValue((string)value);
break;
case PrimitiveTypeCode.Bytes:
writer.WriteValue((byte[])value);
break;
#if !(PORTABLE || NETFX_CORE)
case PrimitiveTypeCode.DBNull:
writer.WriteNull();
break;
#endif
default:
#if !(PORTABLE || NETFX_CORE)
if (value is IConvertible)
{
// the value is a non-standard IConvertible
// convert to the underlying value and retry
IConvertible convertable = (IConvertible)value;
TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertable);
// if convertable has an underlying typecode of Object then attempt to convert it to a string
PrimitiveTypeCode resolvedTypeCode = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? PrimitiveTypeCode.String : typeInformation.TypeCode;
Type resolvedType = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? typeof(string) : typeInformation.Type;
object convertedValue = convertable.ToType(resolvedType, CultureInfo.InvariantCulture);
WriteValue(writer, resolvedTypeCode, convertedValue);
break;
}
else
#endif
{
throw CreateUnsupportedTypeException(writer, value);
}
}
}
private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value)
{
return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
/// <summary>
/// Sets the state of the JsonWriter,
/// </summary>
/// <param name="token">The JsonToken being written.</param>
/// <param name="value">The value being written.</param>
protected void SetWriteState(JsonToken token, object value)
{
switch (token)
{
case JsonToken.StartObject:
InternalWriteStart(token, JsonContainerType.Object);
break;
case JsonToken.StartArray:
InternalWriteStart(token, JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
InternalWriteStart(token, JsonContainerType.Constructor);
break;
case JsonToken.PropertyName:
if (!(value is string))
throw new ArgumentException("A name is required when setting property name state.", "value");
InternalWritePropertyName((string)value);
break;
case JsonToken.Comment:
InternalWriteComment();
break;
case JsonToken.Raw:
InternalWriteRaw();
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Bytes:
case JsonToken.Null:
case JsonToken.Undefined:
InternalWriteValue(token);
break;
case JsonToken.EndObject:
InternalWriteEnd(JsonContainerType.Object);
break;
case JsonToken.EndArray:
InternalWriteEnd(JsonContainerType.Array);
break;
case JsonToken.EndConstructor:
InternalWriteEnd(JsonContainerType.Constructor);
break;
default:
throw new ArgumentOutOfRangeException("token");
}
}
internal void InternalWriteEnd(JsonContainerType container)
{
AutoCompleteClose(container);
}
internal void InternalWritePropertyName(string name)
{
_currentPosition.PropertyName = name;
AutoComplete(JsonToken.PropertyName);
}
internal void InternalWriteRaw()
{
}
internal void InternalWriteStart(JsonToken token, JsonContainerType container)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
Push(container);
}
internal void InternalWriteValue(JsonToken token)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
}
internal void InternalWriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
throw JsonWriterException.Create(this, "Only white space characters should be used.", null);
}
}
internal void InternalWriteComment()
{
AutoComplete(JsonToken.Comment);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Newtonsoft.Json;
namespace SharePointPnP.PowerShell.Commands.Utilities.REST
{
internal static class RestHelper
{
public static T ExecuteGetRequest<T>(ClientContext context, string url, string select = null, string filter = null, string expand = null, uint? top = null)
{
var returnValue = ExecuteGetRequest(context, url, select, filter, expand);
var returnObject = JsonConvert.DeserializeObject<T>(returnValue);
return returnObject;
}
public static string ExecuteGetRequest(ClientContext context, string endPointUrl, string select = null, string filter = null, string expand = null, uint? top = null)
{
var url = endPointUrl;
if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
url = context.Url + "/_api/" + endPointUrl;
}
var restparams = new System.Collections.Generic.List<string>();
if (!string.IsNullOrEmpty(select))
{
restparams.Add($"$select={select}");
}
if (!string.IsNullOrEmpty(filter))
{
restparams.Add($"$filter={filter}");
}
if (!string.IsNullOrEmpty(expand))
{
restparams.Add($"$expand={expand}");
}
if (top.HasValue)
{
restparams.Add($"$top={top}");
}
if (restparams.Any())
{
url += $"?{string.Join("&", restparams)}";
}
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", context.GetAccessToken());
var returnValue = client.GetStringAsync(url).GetAwaiter().GetResult();
return returnValue;
}
public static T ExecutePostRequest<T>(ClientContext context, string url, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
var returnValue = ExecutePostRequestInternal(context, url, null, select, filter, expand);
return JsonConvert.DeserializeObject<T>(returnValue.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}
public static T ExecutePostRequest<T>(ClientContext context, string url, string content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null, string contentType = "application/json", uint? top = null)
{
HttpContent stringContent = null;
if (content != null)
{
stringContent = new StringContent(content);
if (contentType != null)
{
stringContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(contentType);
}
}
var returnValue = ExecutePostRequestInternal(context, url, stringContent, select, filter, expand, additionalHeaders, top);
return JsonConvert.DeserializeObject<T>(returnValue.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}
public static T ExecutePostRequest<T>(ClientContext context, string url, byte[] content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null, uint? top = null)
{
var byteArrayContent = new ByteArrayContent(content);
var returnValue = ExecutePostRequestInternal(context, url, byteArrayContent, select, filter, expand, additionalHeaders, top);
return JsonConvert.DeserializeObject<T>(returnValue.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}
public static HttpResponseMessage ExecutePostRequest(ClientContext context, string endPointUrl, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null, uint? top = null)
{
return ExecutePostRequestInternal(context, endPointUrl, null, select, filter, expand, additionalHeaders, top);
}
public static HttpResponseMessage ExecutePostRequest(ClientContext context, string endPointUrl, string content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null, string contentType = "application/json", uint? top = null)
{
HttpContent stringContent = null;
if (!string.IsNullOrEmpty(content))
{
stringContent = new StringContent(content);
}
if (stringContent != null && contentType != null)
{
stringContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(contentType);
}
return ExecutePostRequestInternal(context, endPointUrl, stringContent, select, filter, expand, additionalHeaders, top);
}
public static HttpResponseMessage ExecutePostRequest(ClientContext context, string endPointUrl, byte[] content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
var byteArrayContent = new ByteArrayContent(content);
return ExecutePostRequestInternal(context, endPointUrl, byteArrayContent, select, filter, expand, additionalHeaders);
}
private static HttpResponseMessage ExecutePostRequestInternal(ClientContext context, string endPointUrl, HttpContent content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null, uint? top = null)
{
var url = endPointUrl;
if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
url = context.Url + "/_api/" + endPointUrl;
}
var restparams = new System.Collections.Generic.List<string>();
if (!string.IsNullOrEmpty(select))
{
restparams.Add($"$select={select}");
}
if (!string.IsNullOrEmpty(filter))
{
restparams.Add($"$filter=({filter})");
}
if (!string.IsNullOrEmpty(expand))
{
restparams.Add($"$expand={expand}");
}
if (top.HasValue)
{
restparams.Add($"$top={top}");
}
if (restparams.Any())
{
url += $"?{string.Join("&", restparams)}";
}
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", context.GetAccessToken());
client.DefaultRequestHeaders.Add("X-RequestDigest", context.GetRequestDigest().GetAwaiter().GetResult());
if (additionalHeaders != null)
{
foreach (var key in additionalHeaders.Keys)
{
client.DefaultRequestHeaders.Add(key, additionalHeaders[key]);
}
}
var returnValue = client.PostAsync(url, content).GetAwaiter().GetResult();
returnValue.EnsureSuccessStatusCode();
return returnValue;
}
#region PUT
public static T ExecutePutRequest<T>(ClientContext context, string url, string content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null, string contentType = null)
{
HttpContent stringContent = new StringContent(content);
if (contentType != null)
{
stringContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(contentType);
}
var returnValue = ExecutePutRequestInternal(context, url, stringContent, select, filter, expand);
return JsonConvert.DeserializeObject<T>(returnValue.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}
public static T ExecutePutRequest<T>(ClientContext context, string url, byte[] content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
var byteArrayContent = new ByteArrayContent(content);
var returnValue = ExecutePutRequestInternal(context, url, byteArrayContent, select, filter, expand);
return JsonConvert.DeserializeObject<T>(returnValue.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}
public static HttpResponseMessage ExecutePutRequest(ClientContext context, string endPointUrl, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
return ExecutePutRequestInternal(context, endPointUrl, null, select, filter, expand, additionalHeaders);
}
public static HttpResponseMessage ExecutePutRequest(ClientContext context, string endPointUrl, string content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null, string contentType = null)
{
HttpContent stringContent = new StringContent(content);
if (contentType != null)
{
stringContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(contentType);
}
return ExecutePutRequestInternal(context, endPointUrl, stringContent, select, filter, expand, additionalHeaders);
}
public static HttpResponseMessage ExecutePutRequest(ClientContext context, string endPointUrl, byte[] content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
var byteArrayContent = new ByteArrayContent(content);
return ExecutePutRequestInternal(context, endPointUrl, byteArrayContent, select, filter, expand, additionalHeaders);
}
private static HttpResponseMessage ExecutePutRequestInternal(ClientContext context, string endPointUrl, HttpContent content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
var url = endPointUrl;
if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
url = context.Url + "/_api/" + endPointUrl;
}
var restparams = new System.Collections.Generic.List<string>();
if (!string.IsNullOrEmpty(select))
{
restparams.Add($"$select={select}");
}
if (!string.IsNullOrEmpty(filter))
{
restparams.Add($"$filter=({filter})");
}
if (!string.IsNullOrEmpty(expand))
{
restparams.Add($"$expand={expand}");
}
if (restparams.Any())
{
url += $"?{string.Join("&", restparams)}";
}
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", context.GetAccessToken());
client.DefaultRequestHeaders.Add("X-RequestDigest", context.GetRequestDigest().GetAwaiter().GetResult());
if (additionalHeaders != null)
{
foreach (var key in additionalHeaders.Keys)
{
client.DefaultRequestHeaders.Add(key, additionalHeaders[key]);
}
}
var returnValue = client.PutAsync(url, content).GetAwaiter().GetResult();
return returnValue;
}
#endregion
#region MERGE
public static T ExecuteMergeRequest<T>(ClientContext context, string url, string content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null, string contentType = null)
{
HttpContent stringContent = new StringContent(content);
if (contentType != null)
{
stringContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(contentType);
}
var returnValue = ExecuteMergeRequestInternal(context, url, stringContent, select, filter, expand);
return JsonConvert.DeserializeObject<T>(returnValue.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}
public static T ExecuteMergeRequest<T>(ClientContext context, string url, byte[] content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
var byteArrayContent = new ByteArrayContent(content);
var returnValue = ExecuteMergeRequestInternal(context, url, byteArrayContent, select, filter, expand);
return JsonConvert.DeserializeObject<T>(returnValue.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}
public static HttpResponseMessage ExecuteMergeRequest(ClientContext context, string endPointUrl, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
return ExecuteMergeRequestInternal(context, endPointUrl, null, select, filter, expand, additionalHeaders);
}
public static HttpResponseMessage ExecuteMergeRequest(ClientContext context, string endPointUrl, string content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null, string contentType = null)
{
HttpContent stringContent = new StringContent(content);
if (contentType != null)
{
stringContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(contentType);
}
return ExecuteMergeRequestInternal(context, endPointUrl, stringContent, select, filter, expand, additionalHeaders);
}
public static HttpResponseMessage ExecuteMergeRequest(ClientContext context, string endPointUrl, byte[] content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
var byteArrayContent = new ByteArrayContent(content);
return ExecuteMergeRequestInternal(context, endPointUrl, byteArrayContent, select, filter, expand, additionalHeaders);
}
private static HttpResponseMessage ExecuteMergeRequestInternal(ClientContext context, string endPointUrl, HttpContent content, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
var url = endPointUrl;
if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
url = context.Url + "/_api/" + endPointUrl;
}
var restparams = new System.Collections.Generic.List<string>();
if (!string.IsNullOrEmpty(select))
{
restparams.Add($"$select={select}");
}
if (!string.IsNullOrEmpty(filter))
{
restparams.Add($"$filter=({filter})");
}
if (!string.IsNullOrEmpty(expand))
{
restparams.Add($"$expand={expand}");
}
if (restparams.Any())
{
url += $"?{string.Join("&", restparams)}";
}
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", context.GetAccessToken());
client.DefaultRequestHeaders.Add("IF-MATCH", "*");
client.DefaultRequestHeaders.Add("X-RequestDigest", context.GetRequestDigest().GetAwaiter().GetResult());
client.DefaultRequestHeaders.Add("X-HTTP-Method", "MERGE");
if (additionalHeaders != null)
{
foreach (var key in additionalHeaders.Keys)
{
client.DefaultRequestHeaders.Add(key, additionalHeaders[key]);
}
}
var returnValue = client.PostAsync(url, content).GetAwaiter().GetResult();
return returnValue;
}
#endregion
#region DELETE
public static HttpResponseMessage ExecuteDeleteRequest(ClientContext context, string endPointUrl, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
return ExecuteDeleteRequestInternal(context, endPointUrl, select, filter, expand, additionalHeaders);
}
private static HttpResponseMessage ExecuteDeleteRequestInternal(ClientContext context, string endPointUrl, string select = null, string filter = null, string expand = null, Dictionary<string, string> additionalHeaders = null)
{
var url = endPointUrl;
if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
url = context.Url + "/_api/" + endPointUrl;
}
var restparams = new System.Collections.Generic.List<string>();
if (!string.IsNullOrEmpty(select))
{
restparams.Add($"$select={select}");
}
if (!string.IsNullOrEmpty(filter))
{
restparams.Add($"$filter=({filter})");
}
if (!string.IsNullOrEmpty(expand))
{
restparams.Add($"$expand={expand}");
}
if (restparams.Any())
{
url += $"?{string.Join("&", restparams)}";
}
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", context.GetAccessToken());
client.DefaultRequestHeaders.Add("X-RequestDigest", context.GetRequestDigest().GetAwaiter().GetResult());
client.DefaultRequestHeaders.Add("X-HTTP-Method", "DELETE");
if (additionalHeaders != null)
{
foreach (var key in additionalHeaders.Keys)
{
client.DefaultRequestHeaders.Add(key, additionalHeaders[key]);
}
}
var returnValue = client.DeleteAsync(url).GetAwaiter().GetResult();
return returnValue;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SelectManyQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// SelectMany is effectively a nested loops join. It is given two data sources, an
/// outer and an inner -- actually, the inner is sometimes calculated by invoking a
/// function for each outer element -- and we walk the outer, walking the entire
/// inner enumerator for each outer element. There is an optional result selector
/// function which can transform the output before yielding it as a result element.
///
/// Notes:
/// Although select many takes two enumerable objects as input, it appears to the
/// query analysis infrastructure as a unary operator. That's because it works a
/// little differently than the other binary operators: it has to re-open the right
/// child every time an outer element is walked. The right child is NOT partitioned.
/// </summary>
/// <typeparam name="TLeftInput"></typeparam>
/// <typeparam name="TRightInput"></typeparam>
/// <typeparam name="TOutput"></typeparam>
internal sealed class SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> : UnaryQueryOperator<TLeftInput, TOutput>
{
private readonly Func<TLeftInput, IEnumerable<TRightInput>> _rightChildSelector; // To select a new child each iteration.
private readonly Func<TLeftInput, int, IEnumerable<TRightInput>> _indexedRightChildSelector; // To select a new child each iteration.
private readonly Func<TLeftInput, TRightInput, TOutput> _resultSelector; // An optional result selection function.
private bool _prematureMerge = false; // Whether to prematurely merge the input of this operator.
private bool _limitsParallelism = false; // Whether to prematurely merge the input of this operator.
//---------------------------------------------------------------------------------------
// Initializes a new select-many operator.
//
// Arguments:
// leftChild - the left data source from which to pull data.
// rightChild - the right data source from which to pull data.
// rightChildSelector - if no right data source was supplied, the selector function
// will generate a new right child for every unique left element.
// resultSelector - a selection function for creating output elements.
//
internal SelectManyQueryOperator(IEnumerable<TLeftInput> leftChild,
Func<TLeftInput, IEnumerable<TRightInput>> rightChildSelector,
Func<TLeftInput, int, IEnumerable<TRightInput>> indexedRightChildSelector,
Func<TLeftInput, TRightInput, TOutput> resultSelector)
: base(leftChild)
{
Debug.Assert(leftChild != null, "left child data source cannot be null");
Debug.Assert(rightChildSelector != null || indexedRightChildSelector != null,
"either right child data or selector must be supplied");
Debug.Assert(rightChildSelector == null || indexedRightChildSelector == null,
"either indexed- or non-indexed child selector must be supplied (not both)");
Debug.Assert(typeof(TRightInput) == typeof(TOutput) || resultSelector != null,
"right input and output must be the same types, otherwise the result selector may not be null");
_rightChildSelector = rightChildSelector;
_indexedRightChildSelector = indexedRightChildSelector;
_resultSelector = resultSelector;
// If the SelectMany is indexed, elements must be returned in the order in which
// indices were assigned.
_outputOrdered = Child.OutputOrdered || indexedRightChildSelector != null;
InitOrderIndex();
}
private void InitOrderIndex()
{
OrdinalIndexState childIndexState = Child.OrdinalIndexState;
if (_indexedRightChildSelector != null)
{
// If this is an indexed SelectMany, we need the order keys to be Correct, so that we can pass them
// into the user delegate.
_prematureMerge = ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct);
_limitsParallelism = _prematureMerge && childIndexState != OrdinalIndexState.Shuffled;
}
else
{
if (OutputOrdered)
{
// If the output of this SelectMany is ordered, the input keys must be at least increasing. The
// SelectMany algorithm assumes that there will be no duplicate order keys, so if the order keys
// are Shuffled, we need to merge prematurely.
_prematureMerge = ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Increasing);
}
}
SetOrdinalIndexState(OrdinalIndexState.Increasing);
}
internal override void WrapPartitionedStream<TLeftKey>(
PartitionedStream<TLeftInput, TLeftKey> inputStream, IPartitionedStreamRecipient<TOutput> recipient, bool preferStriping, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
if (_indexedRightChildSelector != null)
{
PartitionedStream<TLeftInput, int> inputStreamInt;
// If the index is not correct, we need to reindex.
if (_prematureMerge)
{
ListQueryResults<TLeftInput> listResults =
QueryOperator<TLeftInput>.ExecuteAndCollectResults(inputStream, partitionCount, OutputOrdered, preferStriping, settings);
inputStreamInt = listResults.GetPartitionedStream();
}
else
{
inputStreamInt = (PartitionedStream<TLeftInput, int>)(object)inputStream;
}
WrapPartitionedStreamIndexed(inputStreamInt, recipient, settings);
return;
}
//
//
if (_prematureMerge)
{
PartitionedStream<TLeftInput, int> inputStreamInt =
QueryOperator<TLeftInput>.ExecuteAndCollectResults(inputStream, partitionCount, OutputOrdered, preferStriping, settings)
.GetPartitionedStream();
WrapPartitionedStreamNotIndexed(inputStreamInt, recipient, settings);
}
else
{
WrapPartitionedStreamNotIndexed(inputStream, recipient, settings);
}
}
/// <summary>
/// A helper method for WrapPartitionedStream. We use the helper to reuse a block of code twice, but with
/// a different order key type. (If premature merge occured, the order key type will be "int". Otherwise,
/// it will be the same type as "TLeftKey" in WrapPartitionedStream.)
/// </summary>
private void WrapPartitionedStreamNotIndexed<TLeftKey>(
PartitionedStream<TLeftInput, TLeftKey> inputStream, IPartitionedStreamRecipient<TOutput> recipient, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
var keyComparer = new PairComparer<TLeftKey, int>(inputStream.KeyComparer, Util.GetDefaultComparer<int>());
var outputStream = new PartitionedStream<TOutput, Pair>(partitionCount, keyComparer, OrdinalIndexState);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new SelectManyQueryOperatorEnumerator<TLeftKey>(inputStream[i], this, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
/// <summary>
/// Similar helper method to WrapPartitionedStreamNotIndexed, except that this one is for the indexed variant
/// of SelectMany (i.e., the SelectMany that passes indices into the user sequence-generating delegate)
/// </summary>
private void WrapPartitionedStreamIndexed(
PartitionedStream<TLeftInput, int> inputStream, IPartitionedStreamRecipient<TOutput> recipient, QuerySettings settings)
{
var keyComparer = new PairComparer<int, int>(inputStream.KeyComparer, Util.GetDefaultComparer<int>());
var outputStream = new PartitionedStream<TOutput, Pair<int, int>>(inputStream.PartitionCount, keyComparer, OrdinalIndexState);
for (int i = 0; i < inputStream.PartitionCount; i++)
{
outputStream[i] = new IndexedSelectManyQueryOperatorEnumerator(inputStream[i], this, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the left child and wrapping with a
// partition if needed. The right child is not opened yet -- this is always done on demand
// as the outer elements are enumerated.
//
internal override QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping)
{
QueryResults<TLeftInput> childQueryResults = Child.Open(settings, preferStriping);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TOutput> AsSequentialQuery(CancellationToken token)
{
if (_rightChildSelector != null)
{
if (_resultSelector != null)
{
return CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_rightChildSelector, _resultSelector);
}
return (IEnumerable<TOutput>)(object)(CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_rightChildSelector));
}
else
{
Debug.Assert(_indexedRightChildSelector != null);
if (_resultSelector != null)
{
return CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_indexedRightChildSelector, _resultSelector);
}
return (IEnumerable<TOutput>)(object)(CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_indexedRightChildSelector));
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return _limitsParallelism; }
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for executing the SelectMany logic.
//
class IndexedSelectManyQueryOperatorEnumerator : QueryOperatorEnumerator<TOutput, Pair<int, int>>
{
private readonly QueryOperatorEnumerator<TLeftInput, int> _leftSource; // The left data source to enumerate.
private readonly SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> _selectManyOperator; // The select many operator to use.
private IEnumerator<TRightInput> _currentRightSource; // The current enumerator we're using.
private IEnumerator<TOutput> _currentRightSourceAsOutput; // If we need to access the enumerator for output directly (no result selector).
private Mutables _mutables; // bag of frequently mutated value types [allocate in moveNext to avoid false-sharing]
private readonly CancellationToken _cancellationToken;
private class Mutables
{
internal int _currentRightSourceIndex = -1; // The index for the right data source.
internal TLeftInput _currentLeftElement; // The current element in the left data source.
internal int _currentLeftSourceIndex; // The current key in the left data source.
internal int _lhsCount; //counts the number of lhs elements enumerated. used for cancellation testing.
}
//---------------------------------------------------------------------------------------
// Instantiates a new select-many enumerator. Notice that the right data source is an
// enumera*BLE* not an enumera*TOR*. It is re-opened for every single element in the left
// data source.
//
internal IndexedSelectManyQueryOperatorEnumerator(QueryOperatorEnumerator<TLeftInput, int> leftSource,
SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> selectManyOperator,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(selectManyOperator != null);
_leftSource = leftSource;
_selectManyOperator = selectManyOperator;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Straightforward IEnumerator<T> methods.
//
internal override bool MoveNext(ref TOutput currentElement, ref Pair<int, int> currentKey)
{
while (true)
{
if (_currentRightSource == null)
{
_mutables = new Mutables();
// Check cancellation every few lhs-enumerations in case none of them are producing
// any outputs. Otherwise, we rely on the consumer of this operator to be performing the checks.
if ((_mutables._lhsCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We don't have a "current" right enumerator to use. We have to fetch the next
// one. If the left has run out of elements, however, we're done and just return
// false right away.
if (!_leftSource.MoveNext(ref _mutables._currentLeftElement, ref _mutables._currentLeftSourceIndex))
{
return false;
}
// Use the source selection routine to create a right child.
IEnumerable<TRightInput> rightChild =
_selectManyOperator._indexedRightChildSelector(_mutables._currentLeftElement, _mutables._currentLeftSourceIndex);
Debug.Assert(rightChild != null);
_currentRightSource = rightChild.GetEnumerator();
Debug.Assert(_currentRightSource != null);
// If we have no result selector, we will need to access the Current element of the right
// data source as though it is a TOutput. Unfortunately, we know that TRightInput must
// equal TOutput (we check it during operator construction), but the type system doesn't.
// Thus we would have to cast the result of invoking Current from type TRightInput to
// TOutput. This is no good, since the results could be value types. Instead, we save the
// enumerator object as an IEnumerator<TOutput> and access that later on.
if (_selectManyOperator._resultSelector == null)
{
_currentRightSourceAsOutput = (IEnumerator<TOutput>)(object)_currentRightSource;
Debug.Assert(_currentRightSourceAsOutput == _currentRightSource,
"these must be equal, otherwise the surrounding logic will be broken");
}
}
if (_currentRightSource.MoveNext())
{
_mutables._currentRightSourceIndex++;
// If the inner data source has an element, we can yield it.
if (_selectManyOperator._resultSelector != null)
{
// In the case of a selection function, use that to yield the next element.
currentElement = _selectManyOperator._resultSelector(_mutables._currentLeftElement, _currentRightSource.Current);
}
else
{
// Otherwise, the right input and output types must be the same. We use the
// casted copy of the current right source and just return its current element.
Debug.Assert(_currentRightSourceAsOutput != null);
currentElement = _currentRightSourceAsOutput.Current;
}
currentKey = new Pair<int, int>(_mutables._currentLeftSourceIndex, _mutables._currentRightSourceIndex);
return true;
}
else
{
// Otherwise, we have exhausted the right data source. Loop back around and try
// to get the next left element, then its right, and so on.
_currentRightSource.Dispose();
_currentRightSource = null;
_currentRightSourceAsOutput = null;
}
}
}
protected override void Dispose(bool disposing)
{
_leftSource.Dispose();
if (_currentRightSource != null)
{
_currentRightSource.Dispose();
}
}
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for executing the SelectMany logic.
//
class SelectManyQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TOutput, Pair>
{
private readonly QueryOperatorEnumerator<TLeftInput, TLeftKey> _leftSource; // The left data source to enumerate.
private readonly SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> _selectManyOperator; // The select many operator to use.
private IEnumerator<TRightInput> _currentRightSource; // The current enumerator we're using.
private IEnumerator<TOutput> _currentRightSourceAsOutput; // If we need to access the enumerator for output directly (no result selector).
private Mutables _mutables; // bag of frequently mutated value types [allocate in moveNext to avoid false-sharing]
private readonly CancellationToken _cancellationToken;
private class Mutables
{
internal int _currentRightSourceIndex = -1; // The index for the right data source.
internal TLeftInput _currentLeftElement; // The current element in the left data source.
internal TLeftKey _currentLeftKey; // The current key in the left data source.
internal int _lhsCount; // Counts the number of lhs elements enumerated. used for cancellation testing.
}
//---------------------------------------------------------------------------------------
// Instantiates a new select-many enumerator. Notice that the right data source is an
// enumera*BLE* not an enumera*TOR*. It is re-opened for every single element in the left
// data source.
//
internal SelectManyQueryOperatorEnumerator(QueryOperatorEnumerator<TLeftInput, TLeftKey> leftSource,
SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> selectManyOperator,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(selectManyOperator != null);
_leftSource = leftSource;
_selectManyOperator = selectManyOperator;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Straightforward IEnumerator<T> methods.
//
internal override bool MoveNext(ref TOutput currentElement, ref Pair currentKey)
{
while (true)
{
if (_currentRightSource == null)
{
_mutables = new Mutables();
// Check cancellation every few lhs-enumerations in case none of them are producing
// any outputs. Otherwise, we rely on the consumer of this operator to be performing the checks.
if ((_mutables._lhsCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We don't have a "current" right enumerator to use. We have to fetch the next
// one. If the left has run out of elements, however, we're done and just return
// false right away.
if (!_leftSource.MoveNext(ref _mutables._currentLeftElement, ref _mutables._currentLeftKey))
{
return false;
}
// Use the source selection routine to create a right child.
IEnumerable<TRightInput> rightChild = _selectManyOperator._rightChildSelector(_mutables._currentLeftElement);
Debug.Assert(rightChild != null);
_currentRightSource = rightChild.GetEnumerator();
Debug.Assert(_currentRightSource != null);
// If we have no result selector, we will need to access the Current element of the right
// data source as though it is a TOutput. Unfortunately, we know that TRightInput must
// equal TOutput (we check it during operator construction), but the type system doesn't.
// Thus we would have to cast the result of invoking Current from type TRightInput to
// TOutput. This is no good, since the results could be value types. Instead, we save the
// enumerator object as an IEnumerator<TOutput> and access that later on.
if (_selectManyOperator._resultSelector == null)
{
_currentRightSourceAsOutput = (IEnumerator<TOutput>)(object)_currentRightSource;
Debug.Assert(_currentRightSourceAsOutput == _currentRightSource,
"these must be equal, otherwise the surrounding logic will be broken");
}
}
if (_currentRightSource.MoveNext())
{
_mutables._currentRightSourceIndex++;
// If the inner data source has an element, we can yield it.
if (_selectManyOperator._resultSelector != null)
{
// In the case of a selection function, use that to yield the next element.
currentElement = _selectManyOperator._resultSelector(_mutables._currentLeftElement, _currentRightSource.Current);
}
else
{
// Otherwise, the right input and output types must be the same. We use the
// casted copy of the current right source and just return its current element.
Debug.Assert(_currentRightSourceAsOutput != null);
currentElement = _currentRightSourceAsOutput.Current;
}
currentKey = new Pair(_mutables._currentLeftKey, _mutables._currentRightSourceIndex);
return true;
}
else
{
// Otherwise, we have exhausted the right data source. Loop back around and try
// to get the next left element, then its right, and so on.
_currentRightSource.Dispose();
_currentRightSource = null;
_currentRightSourceAsOutput = null;
}
}
}
protected override void Dispose(bool disposing)
{
_leftSource.Dispose();
if (_currentRightSource != null)
{
_currentRightSource.Dispose();
}
}
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
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 License
using System;
using System.Collections.Generic;
using System.Reflection;
using JsonFx.CodeGen;
namespace JsonFx.Serialization.Resolvers
{
/// <summary>
/// Controls name resolution for IDataReader / IDataWriter using DataContract attributes
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/en-us/library/kd1dc9w5.aspx
/// </remarks>
public class DataContractResolverStrategy : PocoResolverStrategy
{
#region Fields
private const string DataContractAssemblyName = "System.Runtime.Serialization";
private const string DataContractTypeName = "System.Runtime.Serialization.DataContractAttribute";
private const string DataMemberTypeName = "System.Runtime.Serialization.DataMemberAttribute";
private const string IgnoreDataMemberTypeName = "System.Runtime.Serialization.IgnoreDataMemberAttribute";
private static readonly Type DataContractType;
private static readonly Type DataMemberType;
private static readonly Type IgnoreDataMemberType;
private static readonly GetterDelegate DataContractNameGetter;
private static readonly GetterDelegate DataContractNamespaceGetter;
private static readonly GetterDelegate DataMemberNameGetter;
#endregion Fields
#region Init
/// <summary>
/// CCtor
/// </summary>
static DataContractResolverStrategy()
{
string[] assemblyName = typeof(Object).Assembly.FullName.Split(',');
assemblyName[0] = DataContractAssemblyName;
Assembly assembly = Assembly.Load(String.Join(",", assemblyName));
DataContractType = assembly.GetType(DataContractTypeName);
DataMemberType = assembly.GetType(DataMemberTypeName);
IgnoreDataMemberType = assembly.GetType(IgnoreDataMemberTypeName);
if (DataContractType != null)
{
PropertyInfo property = DataContractType.GetProperty("Name", BindingFlags.Public|BindingFlags.Instance|BindingFlags.FlattenHierarchy);
DataContractNameGetter = DynamicMethodGenerator.GetPropertyGetter(property);
property = DataContractType.GetProperty("Namespace", BindingFlags.Public|BindingFlags.Instance|BindingFlags.FlattenHierarchy);
DataContractNamespaceGetter = DynamicMethodGenerator.GetPropertyGetter(property);
}
if (DataContractResolverStrategy.DataMemberType != null)
{
PropertyInfo property = DataMemberType.GetProperty("Name", BindingFlags.Public|BindingFlags.Instance|BindingFlags.FlattenHierarchy);
DataMemberNameGetter = DynamicMethodGenerator.GetPropertyGetter(property);
}
}
#endregion Init
#region Name Resolution Methods
/// <summary>
/// Gets a value indicating if the property is to be serialized.
/// </summary>
/// <param name="member"></param>
/// <param name="isImmutableType"></param>
/// <returns></returns>
public override bool IsPropertyIgnored(PropertyInfo member, bool isImmutableType)
{
Type objType = member.ReflectedType ?? member.DeclaringType;
if (TypeCoercionUtility.HasAttribute(objType, DataContractResolverStrategy.DataContractType))
{
// use DataContract rules: member must be marked and not ignored
return
!TypeCoercionUtility.HasAttribute(member, DataContractResolverStrategy.DataMemberType) ||
TypeCoercionUtility.HasAttribute(member, DataContractResolverStrategy.IgnoreDataMemberType);
}
// use POCO rules: must be public read/write (or anonymous object)
return base.IsPropertyIgnored(member, isImmutableType);
}
/// <summary>
/// Gets a value indicating if the field is to be serialized.
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
public override bool IsFieldIgnored(FieldInfo member)
{
Type objType = member.ReflectedType ?? member.DeclaringType;
if (TypeCoercionUtility.HasAttribute(objType, DataContractResolverStrategy.DataContractType))
{
// use DataContract rules: member must be marked and not ignored
return
!TypeCoercionUtility.HasAttribute(member, DataContractResolverStrategy.DataMemberType) ||
TypeCoercionUtility.HasAttribute(member, DataContractResolverStrategy.IgnoreDataMemberType);
}
// use POCO rules: must be public read/write
return base.IsFieldIgnored(member);
}
/// <summary>
/// Gets a delegate which determines if the property or field should not be serialized based upon its value.
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
public override ValueIgnoredDelegate GetValueIgnoredCallback(MemberInfo member)
{
return null;
}
/// <summary>
/// Gets the serialized name for the member.
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
public override IEnumerable<DataName> GetName(MemberInfo member)
{
string localName, ns;
Attribute typeAttr;
if (member is Type)
{
typeAttr = TypeCoercionUtility.GetAttribute(member, DataContractResolverStrategy.DataContractType);
if (typeAttr == null)
{
yield break;
}
localName = (string)DataContractResolverStrategy.DataContractNameGetter(typeAttr);
ns = (string)DataContractResolverStrategy.DataContractNamespaceGetter(typeAttr);
if (!String.IsNullOrEmpty(localName))
{
yield return new DataName(localName, null, ns);
}
yield break;
}
typeAttr = TypeCoercionUtility.GetAttribute(member.DeclaringType, DataContractResolverStrategy.DataContractType);
if (typeAttr == null)
{
yield break;
}
ns = (string)DataContractResolverStrategy.DataContractNamespaceGetter(typeAttr);
Attribute memberAttr = TypeCoercionUtility.GetAttribute(member, DataContractResolverStrategy.DataMemberType);
if (memberAttr == null)
{
yield break;
}
localName = (string)DataContractResolverStrategy.DataMemberNameGetter(memberAttr);
if (!String.IsNullOrEmpty(localName))
{
// members inherit DataContract namespaces
yield return new DataName(localName, null, ns);
}
}
#endregion Name Resolution Methods
}
}
| |
/*
* CCControlSwitch.h
*
* Copyright 2012 Yannick Loriot. All rights reserved.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
using System.Diagnostics;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
public delegate void CCSwitchValueChangedDelegate(object sender, bool bState);
/** @class CCControlSwitch Switch control for Cocos2D. */
public class CCControlSwitch : CCControl
{
bool on;
float initialTouchXPosition;
CCControlSwitchSprite switchSprite;
public event CCSwitchValueChangedDelegate OnValueChanged;
#region Properties
public bool HasMoved { get; private set; }
public override bool Enabled
{
get { return base.Enabled; }
set
{
base.Enabled = value;
if (switchSprite != null)
{
switchSprite.Opacity = (byte) (value ? 255 : 128);
}
}
}
public bool On
{
get { return on; }
set
{
bool notify = false;
if(on != value)
{
on = value;
notify = true;
}
switchSprite.RunAction (
new CCActionTween (
0.2f,
"sliderXPosition",
switchSprite.SliderXPosition,
(on) ? switchSprite.OnPosition : switchSprite.OffPosition
)
);
if(notify)
{
SendActionsForControlEvents(CCControlEvent.ValueChanged);
if (OnValueChanged != null)
{
OnValueChanged(this, on);
}
}
}
}
#endregion Properties
#region Constructors
public CCControlSwitch(CCSprite maskSprite, CCSprite onSprite, CCSprite offSprite, CCSprite thumbSprite)
: this(maskSprite, onSprite, offSprite, thumbSprite, null, null)
{
}
public CCControlSwitch(CCSprite maskSprite, CCSprite onSprite, CCSprite offSprite, CCSprite thumbSprite, CCLabelTtf onLabel,
CCLabelTtf offLabel)
{
Debug.Assert(maskSprite != null, "Mask must not be nil.");
Debug.Assert(onSprite != null, "onSprite must not be nil.");
Debug.Assert(offSprite != null, "offSprite must not be nil.");
Debug.Assert(thumbSprite != null, "thumbSprite must not be nil.");
on = true;
switchSprite = new CCControlSwitchSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel);
switchSprite.Position = new CCPoint(switchSprite.ContentSize.Width / 2, switchSprite.ContentSize.Height / 2);
AddChild(switchSprite);
IgnoreAnchorPointForPosition = false;
AnchorPoint = new CCPoint(0.5f, 0.5f);
ContentSize = switchSprite.ContentSize;
// Register Touch Event
var touchListener = new CCEventListenerTouchOneByOne();
touchListener.IsSwallowTouches = true;
touchListener.OnTouchBegan = OnTouchBegan;
touchListener.OnTouchMoved = OnTouchMoved;
touchListener.OnTouchEnded = OnTouchEnded;
touchListener.OnTouchCancelled = OnTouchCancelled;
AddEventListener(touchListener);
}
#endregion Constructors
public CCPoint LocationFromTouch(CCTouch touch)
{
CCPoint touchLocation = touch.LocationOnScreen;
touchLocation = WorldToParentspace(Layer.ScreenToWorldspace(touchLocation));
return touchLocation;
}
#region Event handling
bool OnTouchBegan(CCTouch touch, CCEvent touchEvent)
{
if (!IsTouchInside(touch) || !Enabled)
{
return false;
}
HasMoved = false;
CCPoint location = LocationFromTouch(touch);
initialTouchXPosition = location.X - switchSprite.SliderXPosition;
switchSprite.ThumbSprite.Color = new CCColor3B(166, 166, 166);
switchSprite.NeedsLayout();
return true;
}
void OnTouchMoved(CCTouch pTouch, CCEvent touchEvent)
{
CCPoint location = LocationFromTouch(pTouch);
location = new CCPoint(location.X - initialTouchXPosition, 0);
HasMoved = true;
switchSprite.SliderXPosition = location.X;
}
void OnTouchEnded(CCTouch pTouch, CCEvent touchEvent)
{
CCPoint location = LocationFromTouch(pTouch);
switchSprite.ThumbSprite.Color = new CCColor3B(255, 255, 255);
if (HasMoved)
{
On = !(location.X < switchSprite.ContentSize.Width / 2);
}
else
{
On = !on;
}
}
void OnTouchCancelled(CCTouch pTouch, CCEvent touchEvent)
{
CCPoint location = LocationFromTouch(pTouch);
switchSprite.ThumbSprite.Color = new CCColor3B(255, 255, 255);
if (HasMoved)
{
On = !(location.X < switchSprite.ContentSize.Width / 2);
}
else
{
On = !on;
}
}
#endregion Event handling
}
public class CCControlSwitchSprite : CCSprite, ICCActionTweenDelegate
{
float sliderXPosition;
#region Properties
public float OnPosition { get; set; }
public float OffPosition { get; set; }
public CCSprite MaskSprite { get; set; }
public CCSprite OnSprite { get; set; }
public CCSprite OffSprite { get; set; }
public CCSprite ThumbSprite { get; set; }
public CCLabelTtf OnLabel { get; set; }
public CCLabelTtf OffLabel { get; set; }
public float OnSideWidth
{
get { return OnSprite.ContentSize.Width; }
}
public float OffSideWidth
{
get { return OffSprite.ContentSize.Height; }
}
public float SliderXPosition
{
get { return sliderXPosition; }
set
{
if (value <= OffPosition)
{
// Off
value = OffPosition;
}
else if (value >= OnPosition)
{
// On
value = OnPosition;
}
sliderXPosition = value;
NeedsLayout();
}
}
#endregion Properties
#region Constructors
public CCControlSwitchSprite(CCSprite maskSprite, CCSprite onSprite, CCSprite offSprite, CCSprite thumbSprite,
CCLabelTtf onLabel, CCLabelTtf offLabel)
: base((CCTexture2D)null, new CCRect(0.0f, 0.0f, maskSprite.TextureRectInPixels.Size.Width, maskSprite.TextureRectInPixels.Size.Height))
{
OnPosition = 0;
OffPosition = -onSprite.ContentSize.Width + thumbSprite.ContentSize.Width / 2;
sliderXPosition = OnPosition;
OnSprite = onSprite;
OffSprite = offSprite;
ThumbSprite = thumbSprite;
OnLabel = onLabel;
OffLabel = offLabel;
MaskSprite = maskSprite;
AddChild(ThumbSprite);
NeedsLayout();
}
#endregion Constructors
public virtual void UpdateTweenAction(float value, string key)
{
//CCLog.Log("key = {0}, value = {1}", key, value);
SliderXPosition = value;
}
protected override void Draw()
{
// CCDrawManager.SharedDrawManager.BlendFunc(CCBlendFunc.AlphaBlend);
// CCDrawManager.SharedDrawManager.BindTexture(Texture);
// CCDrawManager.SharedDrawManager.DrawQuad(ref quad);
}
public void NeedsLayout()
{
OnSprite.Position = new CCPoint(OnSprite.ContentSize.Width / 2 + sliderXPosition, OnSprite.ContentSize.Height / 2);
OffSprite.Position = new CCPoint(OnSprite.ContentSize.Width + OffSprite.ContentSize.Width / 2 + sliderXPosition, OffSprite.ContentSize.Height / 2);
ThumbSprite.Position = new CCPoint(OnSprite.ContentSize.Width + sliderXPosition, MaskSprite.ContentSize.Height / 2);
if (OnLabel != null)
{
OnLabel.Position = new CCPoint(OnSprite.Position.X - ThumbSprite.ContentSize.Width / 6, OnSprite.ContentSize.Height / 2);
}
if (OffLabel != null)
{
OffLabel.Position = new CCPoint(OffSprite.Position.X + ThumbSprite.ContentSize.Width / 6, OffSprite.ContentSize.Height / 2);
}
var rt = new CCRenderTexture(
MaskSprite.TextureRectInPixels.Size,
MaskSprite.TextureRectInPixels.Size,
CCSurfaceFormat.Color, CCDepthFormat.None, CCRenderTargetUsage.DiscardContents
);
rt.BeginWithClear(0, 0, 0, 0);
OnSprite.Visit();
OffSprite.Visit();
if (OnLabel != null)
{
OnLabel.Visit();
}
if (OffLabel != null)
{
OffLabel.Visit();
}
MaskSprite.AnchorPoint = new CCPoint(0, 0);
MaskSprite.BlendFunc = new CCBlendFunc(CCOGLES.GL_ZERO, CCOGLES.GL_SRC_ALPHA);
MaskSprite.Visit();
rt.End();
Texture = rt.Sprite.Texture;
ContentSize = MaskSprite.ContentSize;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using gView.Framework.IO;
using gView.Framework.Geometry;
namespace gView.Framework.Geometry
{
public class PersistableGeometry : IPersistable
{
IGeometry _geometry = null;
public PersistableGeometry()
{
}
public PersistableGeometry(IGeometry geometry)
{
_geometry = geometry;
}
public IGeometry Geometry
{
get { return _geometry; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
PersistablePoint ppoint = stream.Load("Point", null, new PersistablePoint(new Point())) as PersistablePoint;
if (ppoint != null && ppoint.Point != null)
{
_geometry = ppoint.Point;
return;
}
PersistablePointCollection pmultipoint = stream.Load("Multipoint", null, new PersistablePointCollection(new MultiPoint())) as PersistablePointCollection;
if (pmultipoint != null && pmultipoint.PointCollection is IMultiPoint)
{
_geometry = pmultipoint.PointCollection as IMultiPoint;
return;
}
PersistablePolyline ppolyline = stream.Load("Polyline", null, new PersistablePolyline(new Polyline())) as PersistablePolyline;
if (ppolyline != null && ppolyline.Polyline != null)
{
_geometry = ppolyline.Polyline;
return;
}
PersistablePolygon ppolygon = stream.Load("Polygon", null, new PersistablePolygon(new Polygon())) as PersistablePolygon;
if (ppolygon != null && ppolygon.Polygon != null)
{
_geometry = ppolygon.Polygon;
return;
}
PersistableEnvelope penvelope = stream.Load("Envelope", null, new PersistableEnvelope(new Envelope())) as PersistableEnvelope;
if (penvelope != null && penvelope.Envelope != null)
{
_geometry = penvelope.Envelope;
return;
}
PersistableAggregateGeometry pageometry = stream.Load("AggregateGeometry", null, new PersistableAggregateGeometry(new AggregateGeometry())) as PersistableAggregateGeometry;
if (pageometry != null && pageometry.AggregateGeometry != null)
{
_geometry = pageometry.AggregateGeometry;
return;
}
}
public void Save(IPersistStream stream)
{
if (_geometry == null || stream == null) return;
if (_geometry is IPoint)
stream.Save("Point", new PersistablePoint(_geometry as IPoint));
else if (_geometry is IMultiPoint)
stream.Save("Multipoint", new PersistablePointCollection(_geometry as IMultiPoint));
else if (_geometry is IPolyline)
stream.Save("Polyline", new PersistablePolyline(_geometry as IPolyline));
else if (_geometry is Polygon)
stream.Save("Polygon", new PersistablePolygon(_geometry as IPolygon));
else if (_geometry is IEnvelope)
stream.Save("Envelope", new PersistableEnvelope(_geometry as IEnvelope));
else if (_geometry is IAggregateGeometry)
stream.Save("AggregateGeometry", new PersistableAggregateGeometry(_geometry as IAggregateGeometry));
}
#endregion
}
internal class PersistablePoint : IPersistable
{
IPoint _point = null;
public PersistablePoint(IPoint point)
{
_point = point;
}
public IPoint Point
{
get { return _point; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_point==null || stream == null) return;
_point.X = (double)stream.Load("x", 0.0);
_point.Y = (double)stream.Load("y", 0.0);
}
public void Save(IPersistStream stream)
{
if (_point == null) return;
stream.Save("x", _point.X);
stream.Save("y", _point.Y);
}
#endregion
}
internal class PersistablePointCollection : IPersistable
{
IPointCollection _pColl;
public PersistablePointCollection(IPointCollection pcoll)
{
_pColl = pcoll;
}
public IPointCollection PointCollection
{
get { return _pColl; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_pColl==null || stream == null) return;
PersistablePoint p;
while ((p = stream.Load("v", null, new PersistablePoint(new Point())) as PersistablePoint) != null)
{
_pColl.AddPoint(p.Point);
}
}
public void Save(IPersistStream stream)
{
if (_pColl == null) return;
for (int i = 0; i < _pColl.PointCount; i++)
stream.Save("v", new PersistablePoint(_pColl[i]));
}
#endregion
}
internal class PersistablePolyline : IPersistable
{
private IPolyline _polyline;
public PersistablePolyline(IPolyline polyline)
{
_polyline = polyline;
}
public IPolyline Polyline
{
get { return _polyline; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_polyline == null || stream == null) return;
PersistablePointCollection p;
while ((p = stream.Load("Path", null, new PersistablePointCollection(new Path())) as PersistablePointCollection) != null)
{
_polyline.AddPath(p.PointCollection as IPath);
}
}
public void Save(IPersistStream stream)
{
if (_polyline == null || stream == null) return;
for (int i = 0; i < _polyline.PathCount; i++)
stream.Save("Path", new PersistablePointCollection(_polyline[i]));
}
#endregion
}
internal class PersistablePolygon : IPersistable
{
private IPolygon _polygon;
public PersistablePolygon(IPolygon polygon)
{
_polygon = polygon;
}
public IPolygon Polygon
{
get { return _polygon; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_polygon == null || stream == null) return;
PersistablePointCollection p;
while ((p = stream.Load("Ring", null, new PersistablePointCollection(new Ring())) as PersistablePointCollection) != null)
{
_polygon.AddRing(p.PointCollection as IRing);
}
}
public void Save(IPersistStream stream)
{
if (_polygon == null || stream == null) return;
for (int i = 0; i < _polygon.RingCount; i++)
stream.Save("Ring", new PersistablePointCollection(_polygon[i]));
}
#endregion
}
internal class PersistableAggregateGeometry : IPersistable
{
private IAggregateGeometry _ageometry;
public PersistableAggregateGeometry(IAggregateGeometry ageometry)
{
_ageometry = ageometry;
}
public IAggregateGeometry AggregateGeometry
{
get { return _ageometry; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_ageometry == null || stream == null) return;
PersistableGeometry p;
while ((p = stream.Load("Geometry", null, new PersistableGeometry()) as PersistableGeometry) != null)
{
_ageometry.AddGeometry(p.Geometry);
}
}
public void Save(IPersistStream stream)
{
if (_ageometry == null || stream == null) return;
for (int i = 0; i < _ageometry.GeometryCount; i++)
stream.Save("Geometry", new PersistableGeometry(_ageometry[i]));
}
#endregion
}
internal class PersistableEnvelope : IPersistable
{
private IEnvelope _envelope;
public PersistableEnvelope(IEnvelope envelope)
{
_envelope = envelope;
}
public IEnvelope Envelope
{
get { return _envelope; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (stream == null || _envelope == null) return;
PersistablePoint lowerleft = (PersistablePoint)stream.Load("lowerleft", new PersistablePoint(new Point()), new PersistablePoint(new Point()));
PersistablePoint upperright = (PersistablePoint)stream.Load("upperright", new PersistablePoint(new Point()), new PersistablePoint(new Point()));
_envelope.minx = Math.Min(lowerleft.Point.X, upperright.Point.X);
_envelope.miny = Math.Min(lowerleft.Point.Y, upperright.Point.Y);
_envelope.maxx = Math.Max(lowerleft.Point.X, upperright.Point.X);
_envelope.maxy = Math.Max(lowerleft.Point.Y, upperright.Point.Y);
}
public void Save(IPersistStream stream)
{
if (stream == null || _envelope == null) return;
stream.Save("lowerleft", new PersistablePoint(_envelope.LowerLeft));
stream.Save("upperright", new PersistablePoint(_envelope.UpperRight));
}
#endregion
}
}
| |
#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
namespace PdfSharp.Drawing
{
///<summary>
/// Specifies all pre-defined colors. Used to identify the pre-defined colors and to
/// localize their names.
/// </summary>
public enum XKnownColor
{
/// <summary>A pre-defined color.</summary>
AliceBlue = 0,
/// <summary>A pre-defined color.</summary>
AntiqueWhite = 1,
/// <summary>A pre-defined color.</summary>
Aqua = 2,
/// <summary>A pre-defined color.</summary>
Aquamarine = 3,
/// <summary>A pre-defined color.</summary>
Azure = 4,
/// <summary>A pre-defined color.</summary>
Beige = 5,
/// <summary>A pre-defined color.</summary>
Bisque = 6,
/// <summary>A pre-defined color.</summary>
Black = 7,
/// <summary>A pre-defined color.</summary>
BlanchedAlmond = 8,
/// <summary>A pre-defined color.</summary>
Blue = 9,
/// <summary>A pre-defined color.</summary>
BlueViolet = 10,
/// <summary>A pre-defined color.</summary>
Brown = 11,
/// <summary>A pre-defined color.</summary>
BurlyWood = 12,
/// <summary>A pre-defined color.</summary>
CadetBlue = 13,
/// <summary>A pre-defined color.</summary>
Chartreuse = 14,
/// <summary>A pre-defined color.</summary>
Chocolate = 15,
/// <summary>A pre-defined color.</summary>
Coral = 16,
/// <summary>A pre-defined color.</summary>
CornflowerBlue = 17,
/// <summary>A pre-defined color.</summary>
Cornsilk = 18,
/// <summary>A pre-defined color.</summary>
Crimson = 19,
/// <summary>A pre-defined color.</summary>
Cyan = 20,
/// <summary>A pre-defined color.</summary>
DarkBlue = 21,
/// <summary>A pre-defined color.</summary>
DarkCyan = 22,
/// <summary>A pre-defined color.</summary>
DarkGoldenrod = 23,
/// <summary>A pre-defined color.</summary>
DarkGray = 24,
/// <summary>A pre-defined color.</summary>
DarkGreen = 25,
/// <summary>A pre-defined color.</summary>
DarkKhaki = 26,
/// <summary>A pre-defined color.</summary>
DarkMagenta = 27,
/// <summary>A pre-defined color.</summary>
DarkOliveGreen = 28,
/// <summary>A pre-defined color.</summary>
DarkOrange = 29,
/// <summary>A pre-defined color.</summary>
DarkOrchid = 30,
/// <summary>A pre-defined color.</summary>
DarkRed = 31,
/// <summary>A pre-defined color.</summary>
DarkSalmon = 32,
/// <summary>A pre-defined color.</summary>
DarkSeaGreen = 33,
/// <summary>A pre-defined color.</summary>
DarkSlateBlue = 34,
/// <summary>A pre-defined color.</summary>
DarkSlateGray = 35,
/// <summary>A pre-defined color.</summary>
DarkTurquoise = 36,
/// <summary>A pre-defined color.</summary>
DarkViolet = 37,
/// <summary>A pre-defined color.</summary>
DeepPink = 38,
/// <summary>A pre-defined color.</summary>
DeepSkyBlue = 39,
/// <summary>A pre-defined color.</summary>
DimGray = 40,
/// <summary>A pre-defined color.</summary>
DodgerBlue = 41,
/// <summary>A pre-defined color.</summary>
Firebrick = 42,
/// <summary>A pre-defined color.</summary>
FloralWhite = 43,
/// <summary>A pre-defined color.</summary>
ForestGreen = 44,
/// <summary>A pre-defined color.</summary>
Fuchsia = 45,
/// <summary>A pre-defined color.</summary>
Gainsboro = 46,
/// <summary>A pre-defined color.</summary>
GhostWhite = 47,
/// <summary>A pre-defined color.</summary>
Gold = 48,
/// <summary>A pre-defined color.</summary>
Goldenrod = 49,
/// <summary>A pre-defined color.</summary>
Gray = 50,
/// <summary>A pre-defined color.</summary>
Green = 51,
/// <summary>A pre-defined color.</summary>
GreenYellow = 52,
/// <summary>A pre-defined color.</summary>
Honeydew = 53,
/// <summary>A pre-defined color.</summary>
HotPink = 54,
/// <summary>A pre-defined color.</summary>
IndianRed = 55,
/// <summary>A pre-defined color.</summary>
Indigo = 56,
/// <summary>A pre-defined color.</summary>
Ivory = 57,
/// <summary>A pre-defined color.</summary>
Khaki = 58,
/// <summary>A pre-defined color.</summary>
Lavender = 59,
/// <summary>A pre-defined color.</summary>
LavenderBlush = 60,
/// <summary>A pre-defined color.</summary>
LawnGreen = 61,
/// <summary>A pre-defined color.</summary>
LemonChiffon = 62,
/// <summary>A pre-defined color.</summary>
LightBlue = 63,
/// <summary>A pre-defined color.</summary>
LightCoral = 64,
/// <summary>A pre-defined color.</summary>
LightCyan = 65,
/// <summary>A pre-defined color.</summary>
LightGoldenrodYellow = 66,
/// <summary>A pre-defined color.</summary>
LightGray = 67,
/// <summary>A pre-defined color.</summary>
LightGreen = 68,
/// <summary>A pre-defined color.</summary>
LightPink = 69,
/// <summary>A pre-defined color.</summary>
LightSalmon = 70,
/// <summary>A pre-defined color.</summary>
LightSeaGreen = 71,
/// <summary>A pre-defined color.</summary>
LightSkyBlue = 72,
/// <summary>A pre-defined color.</summary>
LightSlateGray = 73,
/// <summary>A pre-defined color.</summary>
LightSteelBlue = 74,
/// <summary>A pre-defined color.</summary>
LightYellow = 75,
/// <summary>A pre-defined color.</summary>
Lime = 76,
/// <summary>A pre-defined color.</summary>
LimeGreen = 77,
/// <summary>A pre-defined color.</summary>
Linen = 78,
/// <summary>A pre-defined color.</summary>
Magenta = 79,
/// <summary>A pre-defined color.</summary>
Maroon = 80,
/// <summary>A pre-defined color.</summary>
MediumAquamarine = 81,
/// <summary>A pre-defined color.</summary>
MediumBlue = 82,
/// <summary>A pre-defined color.</summary>
MediumOrchid = 83,
/// <summary>A pre-defined color.</summary>
MediumPurple = 84,
/// <summary>A pre-defined color.</summary>
MediumSeaGreen = 85,
/// <summary>A pre-defined color.</summary>
MediumSlateBlue = 86,
/// <summary>A pre-defined color.</summary>
MediumSpringGreen = 87,
/// <summary>A pre-defined color.</summary>
MediumTurquoise = 88,
/// <summary>A pre-defined color.</summary>
MediumVioletRed = 89,
/// <summary>A pre-defined color.</summary>
MidnightBlue = 90,
/// <summary>A pre-defined color.</summary>
MintCream = 91,
/// <summary>A pre-defined color.</summary>
MistyRose = 92,
/// <summary>A pre-defined color.</summary>
Moccasin = 93,
/// <summary>A pre-defined color.</summary>
NavajoWhite = 94,
/// <summary>A pre-defined color.</summary>
Navy = 95,
/// <summary>A pre-defined color.</summary>
OldLace = 96,
/// <summary>A pre-defined color.</summary>
Olive = 97,
/// <summary>A pre-defined color.</summary>
OliveDrab = 98,
/// <summary>A pre-defined color.</summary>
Orange = 99,
/// <summary>A pre-defined color.</summary>
OrangeRed = 100,
/// <summary>A pre-defined color.</summary>
Orchid = 101,
/// <summary>A pre-defined color.</summary>
PaleGoldenrod = 102,
/// <summary>A pre-defined color.</summary>
PaleGreen = 103,
/// <summary>A pre-defined color.</summary>
PaleTurquoise = 104,
/// <summary>A pre-defined color.</summary>
PaleVioletRed = 105,
/// <summary>A pre-defined color.</summary>
PapayaWhip = 106,
/// <summary>A pre-defined color.</summary>
PeachPuff = 107,
/// <summary>A pre-defined color.</summary>
Peru = 108,
/// <summary>A pre-defined color.</summary>
Pink = 109,
/// <summary>A pre-defined color.</summary>
Plum = 110,
/// <summary>A pre-defined color.</summary>
PowderBlue = 111,
/// <summary>A pre-defined color.</summary>
Purple = 112,
/// <summary>A pre-defined color.</summary>
Red = 113,
/// <summary>A pre-defined color.</summary>
RosyBrown = 114,
/// <summary>A pre-defined color.</summary>
RoyalBlue = 115,
/// <summary>A pre-defined color.</summary>
SaddleBrown = 116,
/// <summary>A pre-defined color.</summary>
Salmon = 117,
/// <summary>A pre-defined color.</summary>
SandyBrown = 118,
/// <summary>A pre-defined color.</summary>
SeaGreen = 119,
/// <summary>A pre-defined color.</summary>
SeaShell = 120,
/// <summary>A pre-defined color.</summary>
Sienna = 121,
/// <summary>A pre-defined color.</summary>
Silver = 122,
/// <summary>A pre-defined color.</summary>
SkyBlue = 123,
/// <summary>A pre-defined color.</summary>
SlateBlue = 124,
/// <summary>A pre-defined color.</summary>
SlateGray = 125,
/// <summary>A pre-defined color.</summary>
Snow = 126,
/// <summary>A pre-defined color.</summary>
SpringGreen = 127,
/// <summary>A pre-defined color.</summary>
SteelBlue = 128,
/// <summary>A pre-defined color.</summary>
Tan = 129,
/// <summary>A pre-defined color.</summary>
Teal = 130,
/// <summary>A pre-defined color.</summary>
Thistle = 131,
/// <summary>A pre-defined color.</summary>
Tomato = 132,
/// <summary>A pre-defined color.</summary>
Transparent = 133,
/// <summary>A pre-defined color.</summary>
Turquoise = 134,
/// <summary>A pre-defined color.</summary>
Violet = 135,
/// <summary>A pre-defined color.</summary>
Wheat = 136,
/// <summary>A pre-defined color.</summary>
White = 137,
/// <summary>A pre-defined color.</summary>
WhiteSmoke = 138,
/// <summary>A pre-defined color.</summary>
Yellow = 139,
/// <summary>A pre-defined color.</summary>
YellowGreen = 140,
}
}
| |
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization;
namespace Facebook
{
/// <summary>
/// Represents an object encoded in JSON. Can be either a dictionary
/// mapping strings to other objects, an array of objects, or a single
/// object, which represents a scalar.
/// </summary>
public class JSONObject
{
/// <summary>
/// Creates a JSONObject by parsing a string.
/// This is the only correct way to create a JSONObject.
/// </summary>
public static JSONObject CreateFromString(string s)
{
object o;
JavaScriptSerializer js = new JavaScriptSerializer();
try
{
o = js.DeserializeObject(s);
}
catch (ArgumentException)
{
throw new FacebookAPIException("JSONException", "Not a valid JSON string.");
}
return Create(o);
}
/// <summary>
/// Returns true if this JSONObject represents a dictionary.
/// </summary>
public bool IsDictionary
{
get
{
return _dictData != null;
}
}
/// <summary>
/// Returns true if this JSONObject represents an array.
/// </summary>
public bool IsArray
{
get
{
return _arrayData != null;
}
}
/// <summary>
/// Returns true if this JSONObject represents a string value.
/// </summary>
public bool IsString
{
get
{
return _stringData != null;
}
}
/// <summary>
/// Returns true if this JSONObject represents an integer value.
/// </summary>
public bool IsInteger
{
get
{
Int64 tmp;
return Int64.TryParse(_stringData, out tmp);
}
}
/// <summary>
/// Returns true if this JSONOBject represents a boolean value.
/// </summary>
public bool IsBoolean
{
get
{
bool tmp;
return bool.TryParse(_stringData, out tmp);
}
}
/// <summary>
/// Returns this JSONObject as a dictionary
/// </summary>
public Dictionary<string, JSONObject> Dictionary
{
get
{
return _dictData;
}
}
/// <summary>
/// Returns this JSONObject as an array
/// </summary>
public JSONObject[] Array
{
get
{
return _arrayData;
}
}
/// <summary>
/// Returns this JSONObject as a string
/// </summary>
public string String
{
get
{
return _stringData;
}
}
/// <summary>
/// Returns this JSONObject as an integer
/// </summary>
public Int64 Integer
{
get
{
return Convert.ToInt64(_stringData);
}
}
/// <summary>
/// Returns this JSONObject as a boolean
/// </summary>
public bool Boolean
{
get
{
return Convert.ToBoolean(_stringData);
}
}
/// <summary>
/// Prints the JSONObject as a formatted string, suitable for viewing.
/// </summary>
public string ToDisplayableString()
{
StringBuilder sb = new StringBuilder();
RecursiveObjectToString(this, sb, 0);
return sb.ToString();
}
#region Private Members
private string _stringData;
private JSONObject[] _arrayData;
private Dictionary<string, JSONObject> _dictData;
private JSONObject()
{ }
/// <summary>
/// Recursively constructs this JSONObject
/// </summary>
private static JSONObject Create(object o)
{
JSONObject obj = new JSONObject();
if (o is object[])
{
object[] objArray = o as object[];
obj._arrayData = new JSONObject[objArray.Length];
for (int i = 0; i < obj._arrayData.Length; ++i)
{
obj._arrayData[i] = Create(objArray[i]);
}
}
else if (o is Dictionary<string, object>)
{
obj._dictData = new Dictionary<string, JSONObject>();
Dictionary<string, object> dict =
o as Dictionary<string, object>;
foreach (string key in dict.Keys)
{
obj._dictData[key] = Create(dict[key]);
}
}
else if (o != null) // o is a scalar
{
obj._stringData = o.ToString();
}
return obj;
}
private static void RecursiveObjectToString(JSONObject obj,
StringBuilder sb, int level)
{
if (obj.IsDictionary)
{
sb.AppendLine();
RecursiveDictionaryToString(obj, sb, level + 1);
}
else if (obj.IsArray)
{
foreach (JSONObject o in obj.Array)
{
RecursiveObjectToString(o, sb, level);
sb.AppendLine();
}
}
else // some sort of scalar value
{
sb.Append(obj.String);
}
}
private static void RecursiveDictionaryToString(JSONObject obj,
StringBuilder sb, int level)
{
foreach (KeyValuePair<string, JSONObject> kvp in obj.Dictionary)
{
sb.Append(' ', level * 2);
sb.Append(kvp.Key);
sb.Append(" => ");
RecursiveObjectToString(kvp.Value, sb, level);
sb.AppendLine();
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Store;
using Microsoft.WindowsAzure.Management.Store.Models;
namespace Microsoft.WindowsAzure.Management.Store
{
/// <summary>
/// Provides REST operations for working with cloud services from the
/// Windows Azure store service.
/// </summary>
internal partial class CloudServiceOperations : IServiceOperations<StoreManagementClient>, ICloudServiceOperations
{
/// <summary>
/// Initializes a new instance of the CloudServiceOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal CloudServiceOperations(StoreManagementClient client)
{
this._client = client;
}
private StoreManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Store.StoreManagementClient.
/// </summary>
public StoreManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Create Cloud Service operation creates a Windows Azure cloud
/// service in a Windows Azure subscription.
/// </summary>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<AddOnOperationStatusResponse> BeginCreatingAsync(CloudServiceCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Description == null)
{
throw new ArgumentNullException("parameters.Description");
}
if (parameters.GeoRegion == null)
{
throw new ArgumentNullException("parameters.GeoRegion");
}
if (parameters.Label == null)
{
throw new ArgumentNullException("parameters.Label");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/CloudServices/" + parameters.Name + "/";
// 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("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement cloudServiceElement = new XElement(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(cloudServiceElement);
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
cloudServiceElement.Add(nameElement);
XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
labelElement.Value = parameters.Label;
cloudServiceElement.Add(labelElement);
XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
descriptionElement.Value = parameters.Description;
cloudServiceElement.Add(descriptionElement);
XElement geoRegionElement = new XElement(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure"));
geoRegionElement.Value = parameters.GeoRegion;
cloudServiceElement.Add(geoRegionElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AddOnOperationStatusResponse result = null;
result = new AddOnOperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Create Cloud Service operation creates a Windows Azure cloud
/// service in a Windows Azure subscription.
/// </summary>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<AddOnOperationStatusResponse> CreateAsync(CloudServiceCreateParameters parameters, CancellationToken cancellationToken)
{
StoreManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
AddOnOperationStatusResponse response = await client.CloudServices.BeginCreatingAsync(parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
AddOnOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// The List Cloud Services operation enumerates Windows Azure Store
/// entries that are provisioned for a subscription.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response structure for the Cloud Service List operation.
/// </returns>
public async Task<CloudServiceListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/CloudServices/";
// 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("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CloudServiceListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CloudServiceListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement cloudServicesSequenceElement = responseDoc.Element(XName.Get("CloudServices", "http://schemas.microsoft.com/windowsazure"));
if (cloudServicesSequenceElement != null)
{
foreach (XElement cloudServicesElement in cloudServicesSequenceElement.Elements(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure")))
{
CloudServiceListResponse.CloudService cloudServiceInstance = new CloudServiceListResponse.CloudService();
result.CloudServices.Add(cloudServiceInstance);
XElement nameElement = cloudServicesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
cloudServiceInstance.Name = nameInstance;
}
XElement labelElement = cloudServicesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
if (labelElement != null)
{
string labelInstance = TypeConversion.FromBase64String(labelElement.Value);
cloudServiceInstance.Label = labelInstance;
}
XElement descriptionElement = cloudServicesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
if (descriptionElement != null)
{
string descriptionInstance = descriptionElement.Value;
cloudServiceInstance.Description = descriptionInstance;
}
XElement geoRegionElement = cloudServicesElement.Element(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure"));
if (geoRegionElement != null)
{
string geoRegionInstance = geoRegionElement.Value;
cloudServiceInstance.GeoRegion = geoRegionInstance;
}
XElement resourcesSequenceElement = cloudServicesElement.Element(XName.Get("Resources", "http://schemas.microsoft.com/windowsazure"));
if (resourcesSequenceElement != null)
{
foreach (XElement resourcesElement in resourcesSequenceElement.Elements(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure")))
{
CloudServiceListResponse.CloudService.AddOnResource resourceInstance = new CloudServiceListResponse.CloudService.AddOnResource();
cloudServiceInstance.Resources.Add(resourceInstance);
XElement resourceProviderNamespaceElement = resourcesElement.Element(XName.Get("ResourceProviderNamespace", "http://schemas.microsoft.com/windowsazure"));
if (resourceProviderNamespaceElement != null)
{
string resourceProviderNamespaceInstance = resourceProviderNamespaceElement.Value;
resourceInstance.Namespace = resourceProviderNamespaceInstance;
}
XElement typeElement = resourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
resourceInstance.Type = typeInstance;
}
XElement nameElement2 = resourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance2 = nameElement2.Value;
resourceInstance.Name = nameInstance2;
}
XElement planElement = resourcesElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
if (planElement != null)
{
string planInstance = planElement.Value;
resourceInstance.Plan = planInstance;
}
XElement schemaVersionElement = resourcesElement.Element(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure"));
if (schemaVersionElement != null)
{
string schemaVersionInstance = schemaVersionElement.Value;
resourceInstance.SchemaVersion = schemaVersionInstance;
}
XElement eTagElement = resourcesElement.Element(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure"));
if (eTagElement != null)
{
string eTagInstance = eTagElement.Value;
resourceInstance.ETag = eTagInstance;
}
XElement stateElement = resourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
resourceInstance.State = stateInstance;
}
XElement usageMetersSequenceElement = resourcesElement.Element(XName.Get("UsageMeters", "http://schemas.microsoft.com/windowsazure"));
if (usageMetersSequenceElement != null)
{
foreach (XElement usageMetersElement in usageMetersSequenceElement.Elements(XName.Get("UsageMeter", "http://schemas.microsoft.com/windowsazure")))
{
CloudServiceListResponse.CloudService.AddOnResource.UsageLimit usageMeterInstance = new CloudServiceListResponse.CloudService.AddOnResource.UsageLimit();
resourceInstance.UsageLimits.Add(usageMeterInstance);
XElement nameElement3 = usageMetersElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement3 != null)
{
string nameInstance3 = nameElement3.Value;
usageMeterInstance.Name = nameInstance3;
}
XElement unitElement = usageMetersElement.Element(XName.Get("Unit", "http://schemas.microsoft.com/windowsazure"));
if (unitElement != null)
{
string unitInstance = unitElement.Value;
usageMeterInstance.Unit = unitInstance;
}
XElement includedElement = usageMetersElement.Element(XName.Get("Included", "http://schemas.microsoft.com/windowsazure"));
if (includedElement != null)
{
long includedInstance = long.Parse(includedElement.Value, CultureInfo.InvariantCulture);
usageMeterInstance.AmountIncluded = includedInstance;
}
XElement usedElement = usageMetersElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure"));
if (usedElement != null)
{
long usedInstance = long.Parse(usedElement.Value, CultureInfo.InvariantCulture);
usageMeterInstance.AmountUsed = usedInstance;
}
}
}
XElement outputItemsSequenceElement = resourcesElement.Element(XName.Get("OutputItems", "http://schemas.microsoft.com/windowsazure"));
if (outputItemsSequenceElement != null)
{
foreach (XElement outputItemsElement in outputItemsSequenceElement.Elements(XName.Get("OutputItem", "http://schemas.microsoft.com/windowsazure")))
{
string outputItemsKey = outputItemsElement.Element(XName.Get("Key", "http://schemas.microsoft.com/windowsazure")).Value;
string outputItemsValue = outputItemsElement.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure")).Value;
resourceInstance.OutputItems.Add(outputItemsKey, outputItemsValue);
}
}
XElement operationStatusElement = resourcesElement.Element(XName.Get("OperationStatus", "http://schemas.microsoft.com/windowsazure"));
if (operationStatusElement != null)
{
CloudServiceListResponse.CloudService.AddOnResource.OperationStatus operationStatusInstance = new CloudServiceListResponse.CloudService.AddOnResource.OperationStatus();
resourceInstance.Status = operationStatusInstance;
XElement typeElement2 = operationStatusElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement2 != null)
{
string typeInstance2 = typeElement2.Value;
operationStatusInstance.Type = typeInstance2;
}
XElement resultElement = operationStatusElement.Element(XName.Get("Result", "http://schemas.microsoft.com/windowsazure"));
if (resultElement != null)
{
string resultInstance = resultElement.Value;
operationStatusInstance.Result = resultInstance;
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
namespace Ionic.Zlib
{
/// <summary>
/// A class for compressing and decompressing streams using the Deflate algorithm.
/// </summary>
///
/// <remarks>
///
/// <para>
/// The DeflateStream is a <see
/// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see
/// cref="System.IO.Stream"/>. It adds DEFLATE compression or decompression to any
/// stream.
/// </para>
///
/// <para>
/// Using this stream, applications can compress or decompress data via stream
/// <c>Read</c> and <c>Write</c> operations. Either compresssion or decompression
/// can occur through either reading or writing. The compression format used is
/// DEFLATE, which is documented in <see
/// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE
/// Compressed Data Format Specification version 1.3.".
/// </para>
///
/// <para>
/// This class is similar to <see cref="ZlibStream"/>, except that
/// <c>ZlibStream</c> adds the <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
/// 1950 - ZLIB</see> framing bytes to a compressed stream when compressing, or
/// expects the RFC1950 framing bytes when decompressing. The <c>DeflateStream</c>
/// does not.
/// </para>
///
/// </remarks>
///
/// <seealso cref="ZlibStream" />
/// <seealso cref="GZipStream" />
public class DeflateStream : System.IO.Stream
{
internal ZlibBaseStream _baseStream;
internal System.IO.Stream _innerStream;
bool _disposed;
/// <summary>
/// Create a DeflateStream using the specified CompressionMode.
/// </summary>
///
/// <remarks>
/// When mode is <c>CompressionMode.Compress</c>, the DeflateStream will use
/// the default compression level. The "captive" stream will be closed when
/// the DeflateStream is closed.
/// </remarks>
///
/// <example>
/// This example uses a DeflateStream to compress data from a file, and writes
/// the compressed data to another file.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
/// {
/// using (Stream compressor = new DeflateStream(raw, CompressionMode.Compress))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".deflated")
/// Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the DeflateStream will compress or decompress.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode)
: this(stream, mode, CompressionLevel.Default, false)
{
}
/// <summary>
/// Create a DeflateStream using the specified CompressionMode and the specified CompressionLevel.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is
/// ignored. The "captive" stream will be closed when the DeflateStream is
/// closed.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example uses a DeflateStream to compress data from a file, and writes
/// the compressed data to another file.
///
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
/// {
/// using (Stream compressor = new DeflateStream(raw,
/// CompressionMode.Compress,
/// CompressionLevel.BestCompression))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n= -1;
/// while (n != 0)
/// {
/// if (n > 0)
/// compressor.Write(buffer, 0, n);
/// n= input.Read(buffer, 0, buffer.Length);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".deflated")
/// Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream to be read or written while deflating or inflating.</param>
/// <param name="mode">Indicates whether the <c>DeflateStream</c> will compress or decompress.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level)
: this(stream, mode, level, false)
{
}
/// <summary>
/// Create a <c>DeflateStream</c> using the specified
/// <c>CompressionMode</c>, and explicitly specify whether the
/// stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// memory stream that will be re-read after compression. Specify true for
/// the <paramref name="leaveOpen"/> parameter to leave the stream open.
/// </para>
///
/// <para>
/// The <c>DeflateStream</c> will use the default compression level.
/// </para>
///
/// <para>
/// See the other overloads of this constructor for example code.
/// </para>
/// </remarks>
///
/// <param name="stream">
/// The stream which will be read or written. This is called the
/// "captive" stream in other places in this documentation.
/// </param>
///
/// <param name="mode">
/// Indicates whether the <c>DeflateStream</c> will compress or decompress.
/// </param>
///
/// <param name="leaveOpen">true if the application would like the stream to
/// remain open after inflation/deflation.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen)
: this(stream, mode, CompressionLevel.Default, leaveOpen)
{
}
/// <summary>
/// Create a <c>DeflateStream</c> using the specified <c>CompressionMode</c>
/// and the specified <c>CompressionLevel</c>, and explicitly specify whether
/// the stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored.
/// </para>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// <see cref="System.IO.MemoryStream"/> that will be re-read after
/// compression. Specify true for the <paramref name="leaveOpen"/> parameter
/// to leave the stream open.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a <c>DeflateStream</c> to compress data from
/// a file, and store the compressed data into another file.
///
/// <code>
/// using (var output = System.IO.File.Create(fileToCompress + ".deflated"))
/// {
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n= -1;
/// while (n != 0)
/// {
/// if (n > 0)
/// compressor.Write(buffer, 0, n);
/// n= input.Read(buffer, 0, buffer.Length);
/// }
/// }
/// }
/// // can write additional data to the output stream here
/// }
/// </code>
///
/// <code lang="VB">
/// Using output As FileStream = File.Create(fileToCompress & ".deflated")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using compressor As Stream = New DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// ' can write additional data to the output stream here.
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the DeflateStream will compress or decompress.</param>
/// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)
{
_innerStream = stream;
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.DEFLATE, leaveOpen);
}
#region Zlib properties
/// <summary>
/// This property sets the flush behavior on the stream.
/// </summary>
/// <remarks> See the ZLIB documentation for the meaning of the flush behavior.
/// </remarks>
virtual public FlushType FlushMode
{
get { return (this._baseStream._flushMode); }
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
this._baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is
/// 1024 bytes. The minimum size is 128 bytes. You may get better performance
/// with a larger buffer. Then again, you might not. You would have to test
/// it.
/// </para>
///
/// <para>
/// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the
/// stream. If you try to set it afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get
{
return this._baseStream._bufferSize;
}
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
if (this._baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin));
this._baseStream._bufferSize = value;
}
}
/// <summary>
/// The ZLIB strategy to be used during compression.
/// </summary>
///
/// <remarks>
/// By tweaking this parameter, you may be able to optimize the compression for
/// data with particular characteristics.
/// </remarks>
public CompressionStrategy Strategy
{
get
{
return this._baseStream.Strategy;
}
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
this._baseStream.Strategy = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get
{
return this._baseStream._z.TotalBytesIn;
}
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get
{
return this._baseStream._z.TotalBytesOut;
}
}
#endregion
#region System.IO.Stream methods
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not result in a <c>Close()</c> call on the captive
/// stream. See the constructors that have a <c>leaveOpen</c> parameter
/// for more information.
/// </para>
/// <para>
/// Application code won't call this code directly. This method may be
/// invoked in two distinct scenarios. If disposing == true, the method
/// has been called directly or indirectly by a user's code, for example
/// via the public Dispose() method. In this case, both managed and
/// unmanaged resources can be referenced and disposed. If disposing ==
/// false, the method has been called by the runtime from inside the
/// object finalizer and this method should not reference other objects;
/// in that case only unmanaged resources must be referenced or
/// disposed.
/// </para>
/// </remarks>
/// <param name="disposing">
/// true if the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (this._baseStream != null))
this._baseStream.Close();
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream.Flush();
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Writer)
return this._baseStream._z.TotalBytesOut;
if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Reader)
return this._baseStream._z.TotalBytesIn;
return 0;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Read data from the stream.
/// </summary>
/// <remarks>
///
/// <para>
/// If you wish to use the <c>DeflateStream</c> to compress data while
/// reading, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Compress</c>, providing an uncompressed data stream.
/// Then call Read() on that <c>DeflateStream</c>, and the data read will be
/// compressed as you read. If you wish to use the <c>DeflateStream</c> to
/// decompress data while reading, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Decompress</c>, providing a readable compressed data
/// stream. Then call Read() on that <c>DeflateStream</c>, and the data read
/// will be decompressed as you read.
/// </para>
///
/// <para>
/// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer into which the read data should be placed.</param>
/// <param name="offset">the offset within that data array to put the first byte read.</param>
/// <param name="count">the number of bytes to read.</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream.Read(buffer, offset, count);
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">this is irrelevant, since it will always throw!</param>
/// <param name="origin">this is irrelevant, since it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">this is irrelevant, since it will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
/// <remarks>
///
/// <para>
/// If you wish to use the <c>DeflateStream</c> to compress data while
/// writing, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Compress</c>, and a writable output stream. Then call
/// <c>Write()</c> on that <c>DeflateStream</c>, providing uncompressed data
/// as input. The data sent to the output stream will be the compressed form
/// of the data written. If you wish to use the <c>DeflateStream</c> to
/// decompress data while writing, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Decompress</c>, and a writable output stream. Then
/// call <c>Write()</c> on that stream, providing previously compressed
/// data. The data sent to the output stream will be the decompressed form of
/// the data written.
/// </para>
///
/// <para>
/// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>,
/// but not both.
/// </para>
///
/// </remarks>
///
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream.Write(buffer, offset, count);
}
#endregion
/// <summary>
/// Compress a string into a byte array using DEFLATE (RFC 1951).
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="DeflateStream.UncompressString(byte[])"/>.
/// </remarks>
///
/// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso>
/// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso>
/// <seealso cref="GZipStream.CompressString(string)">GZipStream.CompressString(string)</seealso>
/// <seealso cref="ZlibStream.CompressString(string)">ZlibStream.CompressString(string)</seealso>
///
/// <param name="s">
/// A string to compress. The string will first be encoded
/// using UTF8, then compressed.
/// </param>
///
/// <returns>The string in compressed form</returns>
public static byte[] CompressString(String s)
{
using (var ms = new System.IO.MemoryStream())
{
System.IO.Stream compressor =
new DeflateStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
ZlibBaseStream.CompressString(s, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Compress a byte array into a new byte array using DEFLATE.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="DeflateStream.UncompressBuffer(byte[])"/>.
/// </remarks>
///
/// <seealso cref="DeflateStream.CompressString(string)">DeflateStream.CompressString(string)</seealso>
/// <seealso cref="DeflateStream.UncompressBuffer(byte[])">DeflateStream.UncompressBuffer(byte[])</seealso>
/// <seealso cref="GZipStream.CompressBuffer(byte[])">GZipStream.CompressBuffer(byte[])</seealso>
/// <seealso cref="ZlibStream.CompressBuffer(byte[])">ZlibStream.CompressBuffer(byte[])</seealso>
///
/// <param name="b">
/// A buffer to compress.
/// </param>
///
/// <returns>The data in compressed form</returns>
public static byte[] CompressBuffer(byte[] b)
{
using (var ms = new System.IO.MemoryStream())
{
System.IO.Stream compressor =
new DeflateStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression );
ZlibBaseStream.CompressBuffer(b, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Uncompress a DEFLATE'd byte array into a single string.
/// </summary>
///
/// <seealso cref="DeflateStream.CompressString(String)">DeflateStream.CompressString(String)</seealso>
/// <seealso cref="DeflateStream.UncompressBuffer(byte[])">DeflateStream.UncompressBuffer(byte[])</seealso>
/// <seealso cref="GZipStream.UncompressString(byte[])">GZipStream.UncompressString(byte[])</seealso>
/// <seealso cref="ZlibStream.UncompressString(byte[])">ZlibStream.UncompressString(byte[])</seealso>
///
/// <param name="compressed">
/// A buffer containing DEFLATE-compressed data.
/// </param>
///
/// <returns>The uncompressed string</returns>
public static String UncompressString(byte[] compressed)
{
using (var input = new System.IO.MemoryStream(compressed))
{
System.IO.Stream decompressor =
new DeflateStream(input, CompressionMode.Decompress);
return ZlibBaseStream.UncompressString(compressed, decompressor);
}
}
/// <summary>
/// Uncompress a DEFLATE'd byte array into a byte array.
/// </summary>
///
/// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso>
/// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso>
/// <seealso cref="GZipStream.UncompressBuffer(byte[])">GZipStream.UncompressBuffer(byte[])</seealso>
/// <seealso cref="ZlibStream.UncompressBuffer(byte[])">ZlibStream.UncompressBuffer(byte[])</seealso>
///
/// <param name="compressed">
/// A buffer containing data that has been compressed with DEFLATE.
/// </param>
///
/// <returns>The data in uncompressed form</returns>
public static byte[] UncompressBuffer(byte[] compressed)
{
using (var input = new System.IO.MemoryStream(compressed))
{
System.IO.Stream decompressor =
new DeflateStream( input, CompressionMode.Decompress );
return ZlibBaseStream.UncompressBuffer(compressed, decompressor);
}
}
}
}
| |
//
// Copyright 2011-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using Plugin.Geolocator.Abstractions;
using System;
using System.Threading.Tasks;
using Android.Locations;
using System.Threading;
using Android.App;
using Android.OS;
using System.Linq;
using Android.Content;
using Android.Content.PM;
using Plugin.Permissions;
namespace Plugin.Geolocator
{
/// <summary>
/// Implementation for Feature
/// </summary>
public class GeolocatorImplementation : IGeolocator
{
/// <summary>
/// Default constructor
/// </summary>
public GeolocatorImplementation()
{
DesiredAccuracy = 100;
manager = (LocationManager)Application.Context.GetSystemService(Context.LocationService);
providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray();
}
/// <inheritdoc/>
public event EventHandler<PositionErrorEventArgs> PositionError;
/// <inheritdoc/>
public event EventHandler<PositionEventArgs> PositionChanged;
/// <inheritdoc/>
public bool IsListening
{
get { return listener != null; }
}
/// <inheritdoc/>
public double DesiredAccuracy
{
get;
set;
}
/// <inheritdoc/>
public bool SupportsHeading
{
get
{
return true; //Kind of, you should use the Compass plugin for better results
}
}
/// <inheritdoc/>
public bool IsGeolocationAvailable
{
get { return providers.Length > 0; }
}
/// <inheritdoc/>
public bool IsGeolocationEnabled
{
get { return providers.Any(manager.IsProviderEnabled); }
}
/// <inheritdoc/>
public async Task<Position> GetPositionAsync(int timeoutMilliseconds = Timeout.Infinite, CancellationToken? cancelToken = null, bool includeHeading = false)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permissions.Abstractions.Permission.Location).ConfigureAwait(false);
if (status != Permissions.Abstractions.PermissionStatus.Granted)
{
Console.WriteLine("Currently does not have Location permissions, requesting permissions");
var request = await CrossPermissions.Current.RequestPermissionsAsync(Permissions.Abstractions.Permission.Location);
if (request[Permissions.Abstractions.Permission.Location] != Permissions.Abstractions.PermissionStatus.Granted)
{
Console.WriteLine("Location permission denied, can not get positions async.");
return null;
}
providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray();
}
if (providers.Length == 0)
{
providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray();
}
if (timeoutMilliseconds <= 0 && timeoutMilliseconds != Timeout.Infinite)
throw new ArgumentOutOfRangeException("timeoutMilliseconds", "timeout must be greater than or equal to 0");
if (!cancelToken.HasValue)
cancelToken = CancellationToken.None;
var tcs = new TaskCompletionSource<Position>();
if (!IsListening)
{
GeolocationSingleListener singleListener = null;
singleListener = new GeolocationSingleListener((float)DesiredAccuracy, timeoutMilliseconds, providers.Where(manager.IsProviderEnabled),
finishedCallback: () =>
{
for (int i = 0; i < providers.Length; ++i)
manager.RemoveUpdates(singleListener);
});
if (cancelToken != CancellationToken.None)
{
cancelToken.Value.Register(() =>
{
singleListener.Cancel();
for (int i = 0; i < providers.Length; ++i)
manager.RemoveUpdates(singleListener);
}, true);
}
try
{
Looper looper = Looper.MyLooper() ?? Looper.MainLooper;
int enabled = 0;
for (int i = 0; i < providers.Length; ++i)
{
if (manager.IsProviderEnabled(providers[i]))
enabled++;
manager.RequestLocationUpdates(providers[i], 0, 0, singleListener, looper);
}
if (enabled == 0)
{
for (int i = 0; i < providers.Length; ++i)
manager.RemoveUpdates(singleListener);
tcs.SetException(new GeolocationException(GeolocationError.PositionUnavailable));
return await tcs.Task.ConfigureAwait(false);
}
}
catch (Java.Lang.SecurityException ex)
{
tcs.SetException(new GeolocationException(GeolocationError.Unauthorized, ex));
return await tcs.Task.ConfigureAwait(false);
}
return await singleListener.Task.ConfigureAwait(false);
}
// If we're already listening, just use the current listener
lock (positionSync)
{
if (lastPosition == null)
{
if (cancelToken != CancellationToken.None)
{
cancelToken.Value.Register(() => tcs.TrySetCanceled());
}
EventHandler<PositionEventArgs> gotPosition = null;
gotPosition = (s, e) =>
{
tcs.TrySetResult(e.Position);
PositionChanged -= gotPosition;
};
PositionChanged += gotPosition;
}
else
{
tcs.SetResult(lastPosition);
}
}
return await tcs.Task.ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<bool> StartListeningAsync(int minTime, double minDistance, bool includeHeading = false, ListenerSettings settings = null)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permissions.Abstractions.Permission.Location).ConfigureAwait(false);
if (status != Permissions.Abstractions.PermissionStatus.Granted)
{
Console.WriteLine("Currently does not have Location permissions, requesting permissions");
var request = await CrossPermissions.Current.RequestPermissionsAsync(Permissions.Abstractions.Permission.Location);
if (request[Permissions.Abstractions.Permission.Location] != Permissions.Abstractions.PermissionStatus.Granted)
{
Console.WriteLine("Location permission denied, can not get positions async.");
return false;
}
providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray();
}
if (providers.Length == 0)
{
providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray();
}
if (minTime < 0)
throw new ArgumentOutOfRangeException("minTime");
if (minDistance < 0)
throw new ArgumentOutOfRangeException("minDistance");
if (IsListening)
throw new InvalidOperationException("This Geolocator is already listening");
listener = new GeolocationContinuousListener(manager, TimeSpan.FromMilliseconds(minTime), providers);
listener.PositionChanged += OnListenerPositionChanged;
listener.PositionError += OnListenerPositionError;
Looper looper = Looper.MyLooper() ?? Looper.MainLooper;
for (int i = 0; i < providers.Length; ++i)
manager.RequestLocationUpdates(providers[i], minTime, (float)minDistance, listener, looper);
return true;
}
/// <inheritdoc/>
public Task<bool> StopListeningAsync()
{
if (listener == null)
return Task.FromResult(true);
listener.PositionChanged -= OnListenerPositionChanged;
listener.PositionError -= OnListenerPositionError;
for (int i = 0; i < providers.Length; ++i)
manager.RemoveUpdates(listener);
listener = null;
return Task.FromResult(true);
}
private string[] providers;
private readonly LocationManager manager;
private string headingProvider;
private GeolocationContinuousListener listener;
private readonly object positionSync = new object();
private Position lastPosition;
/// <inheritdoc/>
private void OnListenerPositionChanged(object sender, PositionEventArgs e)
{
if (!IsListening) // ignore anything that might come in afterwards
return;
lock (positionSync)
{
lastPosition = e.Position;
var changed = PositionChanged;
if (changed != null)
changed(this, e);
}
}
/// <inheritdoc/>
private async void OnListenerPositionError(object sender, PositionErrorEventArgs e)
{
await StopListeningAsync();
var error = PositionError;
if (error != null)
error(this, e);
}
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
internal static DateTimeOffset GetTimestamp(Location location)
{
return new DateTimeOffset(Epoch.AddMilliseconds(location.Time));
}
}
}
| |
// This file was generated by the Gtk# code generator.
// Any changes made will be lost if regenerated.
namespace Gtk {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#region Autogenerated code
public partial class HeaderBar : Gtk.Container {
public HeaderBar (IntPtr raw) : base(raw) {}
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gtk_header_bar_new();
public HeaderBar () : base (IntPtr.Zero)
{
if (GetType () != typeof (HeaderBar)) {
CreateNativeObject (new string [0], new GLib.Value[0]);
return;
}
Raw = gtk_header_bar_new();
}
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool gtk_header_bar_get_has_subtitle(IntPtr raw);
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void gtk_header_bar_set_has_subtitle(IntPtr raw, bool setting);
[GLib.Property ("has-subtitle")]
public bool HasSubtitle {
get {
bool raw_ret = gtk_header_bar_get_has_subtitle(Handle);
bool ret = raw_ret;
return ret;
}
set {
gtk_header_bar_set_has_subtitle(Handle, value);
}
}
public class HeaderBarChild : Gtk.Container.ContainerChild {
protected internal HeaderBarChild (Gtk.Container parent, Gtk.Widget child) : base (parent, child) {}
[Gtk.ChildProperty ("pack-type")]
public Gtk.PackType PackType {
get {
GLib.Value val = parent.ChildGetProperty (child, "pack-type");
Gtk.PackType ret = (Gtk.PackType) (Enum) val;
val.Dispose ();
return ret;
}
set {
GLib.Value val = new GLib.Value((Enum) value);
parent.ChildSetProperty(child, "pack-type", val);
val.Dispose ();
}
}
[Gtk.ChildProperty ("position")]
public int Position {
get {
GLib.Value val = parent.ChildGetProperty (child, "position");
int ret = (int) val;
val.Dispose ();
return ret;
}
set {
GLib.Value val = new GLib.Value(value);
parent.ChildSetProperty(child, "position", val);
val.Dispose ();
}
}
}
public override Gtk.Container.ContainerChild this [Gtk.Widget child] {
get {
return new HeaderBarChild (this, child);
}
}
[StructLayout (LayoutKind.Sequential)]
struct GtkHeaderBarClass {
IntPtr GtkReserved1;
IntPtr GtkReserved2;
IntPtr GtkReserved3;
IntPtr GtkReserved4;
}
static uint class_offset = ((GLib.GType) typeof (Gtk.Container)).GetClassSize ();
static Dictionary<GLib.GType, GtkHeaderBarClass> class_structs;
static GtkHeaderBarClass GetClassStruct (GLib.GType gtype, bool use_cache)
{
if (class_structs == null)
class_structs = new Dictionary<GLib.GType, GtkHeaderBarClass> ();
if (use_cache && class_structs.ContainsKey (gtype))
return class_structs [gtype];
else {
IntPtr class_ptr = new IntPtr (gtype.GetClassPtr ().ToInt64 () + class_offset);
GtkHeaderBarClass class_struct = (GtkHeaderBarClass) Marshal.PtrToStructure (class_ptr, typeof (GtkHeaderBarClass));
if (use_cache)
class_structs.Add (gtype, class_struct);
return class_struct;
}
}
static void OverrideClassStruct (GLib.GType gtype, GtkHeaderBarClass class_struct)
{
IntPtr class_ptr = new IntPtr (gtype.GetClassPtr ().ToInt64 () + class_offset);
Marshal.StructureToPtr (class_struct, class_ptr, false);
}
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gtk_header_bar_get_custom_title(IntPtr raw);
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void gtk_header_bar_set_custom_title(IntPtr raw, IntPtr title_widget);
public Gtk.Widget CustomTitle {
get {
IntPtr raw_ret = gtk_header_bar_get_custom_title(Handle);
Gtk.Widget ret = GLib.Object.GetObject(raw_ret) as Gtk.Widget;
return ret;
}
set {
gtk_header_bar_set_custom_title(Handle, value == null ? IntPtr.Zero : value.Handle);
}
}
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gtk_header_bar_get_decoration_layout(IntPtr raw);
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void gtk_header_bar_set_decoration_layout(IntPtr raw, IntPtr layout);
public string DecorationLayout {
get {
IntPtr raw_ret = gtk_header_bar_get_decoration_layout(Handle);
string ret = GLib.Marshaller.Utf8PtrToString (raw_ret);
return ret;
}
set {
IntPtr native_value = GLib.Marshaller.StringToPtrGStrdup (value);
gtk_header_bar_set_decoration_layout(Handle, native_value);
GLib.Marshaller.Free (native_value);
}
}
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool gtk_header_bar_get_show_close_button(IntPtr raw);
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void gtk_header_bar_set_show_close_button(IntPtr raw, bool setting);
public bool ShowCloseButton {
get {
bool raw_ret = gtk_header_bar_get_show_close_button(Handle);
bool ret = raw_ret;
return ret;
}
set {
gtk_header_bar_set_show_close_button(Handle, value);
}
}
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gtk_header_bar_get_subtitle(IntPtr raw);
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void gtk_header_bar_set_subtitle(IntPtr raw, IntPtr subtitle);
public string Subtitle {
get {
IntPtr raw_ret = gtk_header_bar_get_subtitle(Handle);
string ret = GLib.Marshaller.Utf8PtrToString (raw_ret);
return ret;
}
set {
IntPtr native_value = GLib.Marshaller.StringToPtrGStrdup (value);
gtk_header_bar_set_subtitle(Handle, native_value);
GLib.Marshaller.Free (native_value);
}
}
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gtk_header_bar_get_title(IntPtr raw);
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void gtk_header_bar_set_title(IntPtr raw, IntPtr title);
public string Title {
get {
IntPtr raw_ret = gtk_header_bar_get_title(Handle);
string ret = GLib.Marshaller.Utf8PtrToString (raw_ret);
return ret;
}
set {
IntPtr native_value = GLib.Marshaller.StringToPtrGStrdup (value);
gtk_header_bar_set_title(Handle, native_value);
GLib.Marshaller.Free (native_value);
}
}
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gtk_header_bar_get_type();
public static new GLib.GType GType {
get {
IntPtr raw_ret = gtk_header_bar_get_type();
GLib.GType ret = new GLib.GType(raw_ret);
return ret;
}
}
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void gtk_header_bar_pack_end(IntPtr raw, IntPtr child);
public void PackEnd(Gtk.Widget child) {
gtk_header_bar_pack_end(Handle, child == null ? IntPtr.Zero : child.Handle);
}
[DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void gtk_header_bar_pack_start(IntPtr raw, IntPtr child);
public void PackStart(Gtk.Widget child) {
gtk_header_bar_pack_start(Handle, child == null ? IntPtr.Zero : child.Handle);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Bolt.Tools.Generators;
using Microsoft.Extensions.CommandLineUtils;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Bolt.Tools.Configuration
{
public class RootConfiguration
{
private static readonly AnsiConsole Console = AnsiConsole.GetOutput(true);
private readonly Dictionary<string, DocumentGenerator> _documents = new Dictionary<string, DocumentGenerator>();
public RootConfiguration(AssemblyCache cache)
{
Contracts = new List<InterfaceConfiguration>();
AssemblyCache = cache;
Assemblies = new List<string>();
}
[JsonIgnore]
public AssemblyCache AssemblyCache { get; private set; }
public List<string> Assemblies { get; set; }
[JsonProperty(Required = Required.Always)]
public List<InterfaceConfiguration> Contracts { get; set; }
[JsonIgnore]
public bool IgnoreGeneratorErrors { get; set; }
public string Modifier { get; set; }
public bool FullTypeNames { get; set; }
[JsonIgnore]
public string OutputDirectory { get; set; }
public static RootConfiguration CreateFromConfig(AssemblyCache cache, string file)
{
file = Path.GetFullPath(file);
string content = File.ReadAllText(file);
return CreateFromConfig(cache, Path.GetDirectoryName(file), content);
}
public static RootConfiguration CreateFromConfig(AssemblyCache cache, string outputDirectory, string content)
{
var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include, Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() };
RootConfiguration configuration = JsonConvert.DeserializeObject<RootConfiguration>(content, settings);
configuration.OutputDirectory = outputDirectory;
configuration.AssemblyCache = cache;
foreach (InterfaceConfiguration contract in configuration.Contracts)
{
contract.Parent = configuration;
}
return configuration;
}
public static RootConfiguration CreateFromAssembly(AssemblyCache cache, string assembly, bool internalVisibility)
{
RootConfiguration root = new RootConfiguration(cache)
{
Contracts = new List<InterfaceConfiguration>()
};
Assembly loadedAssembly = null;
if (!string.IsNullOrEmpty(assembly) && File.Exists(assembly))
{
root.Assemblies = new List<string> { Path.GetFullPath(assembly) };
loadedAssembly = cache.Loader.Load(assembly);
}
if (loadedAssembly != null)
{
foreach (var type in root.AssemblyCache.GetTypes(loadedAssembly))
{
root.AddContract(type.GetTypeInfo(), internalVisibility);
}
}
return root;
}
public string Serialize()
{
return JsonConvert.SerializeObject(
this,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() });
}
public IEnumerable<InterfaceConfiguration> AddContractsFromNamespace(string namespaceName, bool internalVisibility)
{
foreach (var type in AssemblyCache.GetTypes(namespaceName))
{
InterfaceConfiguration contract = AddContract(type.GetTypeInfo(), internalVisibility);
if (contract != null)
{
yield return contract;
}
Console.WriteLine($"Contract '{type.Name.Bold()}' added.");
}
}
public IEnumerable<InterfaceConfiguration> AddAllContracts(bool internalVisibility)
{
foreach (var type in AssemblyCache.GetTypes())
{
InterfaceConfiguration contract = AddContract(type.GetTypeInfo(), internalVisibility);
if (contract != null)
{
yield return contract;
}
Console.WriteLine($"Contract '{type.Name.Bold()}' added.");
}
}
public InterfaceConfiguration AddContract(string name, bool internalVisibility)
{
var type = AssemblyCache.GetType(name);
var addedContract = AddContract(type.GetTypeInfo(), internalVisibility);
if (addedContract != null)
{
Console.WriteLine($"Contract '{type.Name.Bold()}' added.");
}
else
{
Console.WriteLine($"Contract '{type.Name.Bold()}' not found.");
}
return addedContract;
}
public InterfaceConfiguration AddContract(TypeInfo type, bool internalVisibility)
{
if (type == null)
{
return null;
}
if (!type.IsInterface)
{
return null;
}
if (Contracts.FirstOrDefault(existing => existing.Contract == type.FullName) != null)
{
return null;
}
InterfaceConfiguration c = new InterfaceConfiguration
{
Parent = this,
Contract = type.FullName,
Modifier = internalVisibility ? "internal" : "public",
ForceAsyncMethod = true,
ForceSyncMethod = true,
Namespace = type.Namespace
};
Contracts.Add(c);
return c;
}
public int Generate()
{
if (Assemblies != null)
{
List<string> directories =
Assemblies.Select(Path.GetDirectoryName)
.Concat(new[] { Directory.GetCurrentDirectory() })
.Distinct()
.ToList();
foreach (string dir in directories)
{
AssemblyCache.Loader.AddDirectory(dir);
}
foreach (string assembly in Assemblies)
{
AssemblyCache.Loader.Load(assembly);
}
}
Stopwatch watch = Stopwatch.StartNew();
foreach (InterfaceConfiguration contract in Contracts)
{
try
{
contract.Generate();
}
catch (Exception e)
{
if (!IgnoreGeneratorErrors)
{
return Program.HandleError($"Failed to generate contract: {contract.Contract.Bold().White()}", e);
}
Program.HandleError($"Skipped contract generation: {contract.Contract.Bold().White()}", e);
}
}
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Generating files ... ");
foreach (var filesInDirectory in _documents.GroupBy(f => Path.GetDirectoryName(f.Key)))
{
Console.WriteLine(string.Join(string.Empty, Enumerable.Repeat("-", filesInDirectory.Key.Count() + 12).ToArray()));
Console.WriteLine($"Directory: {filesInDirectory.Key.Bold().White()}");
Console.WriteLine(Environment.NewLine);
foreach (var documentGenerator in filesInDirectory)
{
try
{
string status;
string result = documentGenerator.Value.GetResult();
if (File.Exists(documentGenerator.Key))
{
string prev = File.ReadAllText(documentGenerator.Key);
if (prev != result)
{
File.WriteAllText(documentGenerator.Key, result);
status = "Overwritten".Green().Bold();
}
else
{
status = "Skipped".White();
}
}
else
{
string directory = Path.GetDirectoryName(documentGenerator.Key);
if (directory != null && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
File.WriteAllText(documentGenerator.Key, result);
status = "Generated".Green();
}
Console.WriteLine($"{status}: {Path.GetFileName(documentGenerator.Key).White().Bold()}");
}
catch (Exception e)
{
return Program.HandleError($"File Generation Failed: {Path.GetFileName(documentGenerator.Key).White()}", e);
}
}
}
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Status:");
Console.WriteLine($"{(_documents.Count + " Files Generated,").Green().Bold()} {watch.ElapsedMilliseconds}ms elapsed");
Console.WriteLine(Environment.NewLine);
return 0;
}
public DocumentGenerator GetDocument(string output)
{
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
if (!_documents.ContainsKey(output))
{
_documents[output] = new DocumentGenerator();
if (FullTypeNames)
{
_documents[output].Formatter.ForceFullTypeNames = true;
}
}
return _documents[output];
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.